# Program in C++ to swap two values with and without using temporary variable:

Hi guys, welcome to another tutorial on C++, in this tutorial we will learn how to swap two different values by writing a program for it in C++ but first we will see how to swap two values by using a temporary variable.
Understanding the logic behind the swapping of two variables using temporary variable:
First we will declare three variables a,b and c and will take input from the user for the two declared variables a and b after that we will assign variable c to the value of a , now c has the value of a and now after that we will assign a to the value of b and then we will assign b to the value of c which now contains the previous value of a, the piece of code for the will look something like this

c=a; a=b; b=c;

Look a the picture below to make the concept more clear:

code for the above logic:

#include<iostream> using namespace std; int main(){ int a,b,c; cout<<"Enter two numbers to swap"; cin>>a>>b; cout<<"Values before swaping a="<<a<<" b="<<b; c=a; a=b; b=c; cout<<"values after swapping a="<<a<<"b="<<b; return 0; }

Now let's make a program to swap two values in c++ without using a third variablethere are two methods to make such program1.Addition and subtraction method2.Multiplication and division method
First-Method

#include<iostream> using namespace std; int main(){ int a,b; cout<<"Enter two numbers to swap"; cin>>a>>b; cout<<"Values before swaping a="<<a<<" b="<<b; a=a+b; b=a-b; a=a-b; cout<<"values after swapping a="<<a<<"b="<<b; return 0; }

to explain the above logic let's take some value of variable a and b let say a=10 and b=3nowa = a+b = 10+3 //new value of a=13b = a-b = 13-3 //new value of b =10a = a-b = 13-10 //new value of a= 3
Second method:

#include<iostream> using namespace std; int main(){ int a,b; cout<<"Enter two numbers to swap"; cin>>a>>b; a=a*b; b=a/b; a=a/b; cout<<"Values before swaping a="<<a<<" b="<<b; cout<<"values after swapping a="<<a<<"b="<<b; return 0; }

to explain the above logic let's take some value of variable a and b let say a=10 and b=3
a = a * b //a = 10 * 3 =30b = a/b // b = 30 / 3 = 10a= a/b // a = 30 / 10 = 3
Note: in the above method the values of the variables will not change.
So that's it for now hope you guys like it, see you guys in the next article till then goodbye.if you like the article please share it and help us grow.

Понравилась статья? Поделиться с друзьями: