C++ Program to Swap Two Numbers (Using a temporary variable)

by | Jan 5, 2023 | C++, C++ Programs

Home » C++ » C++ Programs » C++ Program to Swap Two Numbers (Using a temporary variable)

Introduction

In this program, you will learn to swap two numbers entered by the user in the C++ language using a third temporary variable.

To understand this program, you should know about

1. C Data types

2. C programming operators

Program

#include<iostream>

using namespace std;

int main()

{

int num1, num2;

cout<<"Enter two numbers: "<<endl;

cin>>num1>>num2;




cout<<"Before swapping:\nnum1="<<num1<<"\nnum2="<<num2<<endl;

int temp; // temp is temporary variable

// swapping

temp=num1;

num1=num2;

num2=temp;




cout<<"After swapping:\nnum1="<<num1<<"\nnum2="<<num2<<endl;

return 0;

}

 

Output

Explanation

In the above program, the user is asked to enter two values that get stored in num1 and num2.

The user enters num1=25 and num2=52.

int temp; by declaring this temporary variable ‘temp’ we will swap the numbers entered by the user.

temp=num1; the value of variable ‘num1’ is assigned to variable ‘temp’. This results in a vacancy in the memory block of variable ‘num1’. Thus, temp=25

num1=num2; the value of variable ‘num2’ is assigned to ‘num1’. Now, there is a vacancy in the memory block of variable ‘num2’. Thus, num1=52

num2=temp; the value of ‘temp’ is assigned to ‘num2’. Thus, num2=25

Hence the values entered by the user are swapped.

 

Author

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author