How To Swap Two Numbers in C++

Swapping means exchanging the values stored in variables. The value of first variable would be assigned to second variable and value of second variable would be assigned to first variable. This can be accomplished using a third variable. Often it is called temporary variable because it stores values temporarily. There are three necessary steps to swap two numbers in C++:

  • Assign value of first variable to temporary variable.
  • Assign value of second variable to first variable.
  • Assign value of temporary variable to second variable.

Code To Swap Two Numbers In C++:

#include<iostream>
using namespace std;
int main()
 {	
 	int num1,num2,temp;
	cout<<"ENTER FIRST INTEGER: ";
	cin>>num1;
	cout<<"ENTER SECOND INTEGER: ";
	cin>>num2;
	cout<<"\n---Values Before Swapping---\n"<<endl;
	cout<<"FIRST INTEGER: "<<num1<<endl;
	cout<<"SECOND INTEGER: "<<num2<<endl;
	temp=num1;
	num1=num2;
	num2=temp;
	cout<<"\n---Values After Swapping---\n"<<endl;
	cout<<"FIRST INTEGER: "<<num1<<endl;
	cout<<"SECOND INTEGER: "<<num2<<endl;
	return 0;
 }

Dry Run:

Lets see how this code is executed in memory of computer. First it asks user to enter two numbers. Lets assume that numbers entered by user are 5 and 10.

5

num1

10

num2

0

temp


temp=num1;

5

num1

10

num2

5

temp


num1=num2;

10

num1

10

num2

5

temp


num2=temp;

10

num1

5

num2

5

temp

Now you can see that the values of num1 and num2 has been exchanged. This is how swapping of two numbers is done in C++.

Program output:

Output of Swap Two Numbers in C++

Thanks for reading this article. If you have any question then you can ask me in comments,

You can also Click Here to Download Exercise Files.