Friday, 21 September 2018

Swapping of two numbers using three variables in C++

Swapping of two numbers using the third variable




Swapping is the process of exchanging or interchanging the values stored in two variables. Swapping of two number is done by two variable method and three variable method. This program is done by three variable method. E.g. a=5 and b=6 then after swapping the values we get a=6 and b=5.












Write a program in C++ to swap values of two integer variables using the third variable.


We will take two values from the users and store the values in two variables. We will also declare another variable and use it for swapping the two numbers. Finally, we will display the swapped values.


Program



#include<iostream.h>
#include<conio.h>
void main()
{
int a,b,swap;
clrscr();
cout<<"Enter first number in a=";
cin>>a;
cout<<"Enter second number in b=";
cin>>b;
swap=b;
b=a;
a=swap;
cout<<"\nAfter swapping:"<<endl;
cout<<"The new value in a="<<a<<endl;
cout<<"The new value in b="<<b;
getch();
}



    



Output



Swapping of variables
SWAPPING OF TWO VALUES USING THE THIRD VARIABLE










Explanation


In this program, we interchanged the values of two variables (b) using the third variable (swap). We assign the value of a in swap. Then we assigned the value of b to a. Again we assign the value of swap to a. After this, we get the swapped values in variables a and b.





No comments:

Post a Comment