C++ program to swap two numbers

In this article, we will discuss another basic and one of the important programs of c++, the swapping of two numbers. Before going further let's understand what swapping is. Swapping means exchange. For example, if a variable 'a' stores a value 5 and another variable 'b' stores a value 10 then after swapping the value of a and b will be interchanged, i.e., the value of a becomes 20 and the value of b becomes 10. But for swapping two numbers we need a third temporary variable. Let's understand this by an example. Suppose we have two glasses, one filled with juice and the other with water. So, for exchanging juice and water we need another glass to empty one of the two glasses (say juice) and then fill it with the remaining item (here, water). In this way, swapping takes place.


Given below is the code for swapping two numbers using c++:-

#include<iostream>

using namespace std;

int main()

{

int a,b,temp;

      cout<<"Enter value of a: ";

      cin>>a;

      cout<<"\nEnter value of b: ";

      cin>>b; 

temp=a;

 a=b;

 b=temp;

     cout<<"\nAfter swapping a ="<<a<<" and b = "<<b;

return 0;

}


OUTPUT:-

Enter value of a : 5

Enter value of b : 10

After swapping a = 10 and b = 5


Explanation

In the above program, we define three variables a,b, and temp. a and b are two integers that hold an integer value and the temp variable is 0 in starting Now, we take two user inputs in a and b. To swap the values of a and b we use the temp variable. After swapping the value, we print using cout stream

Post a Comment

0 Comments