W.A.P. TO SWAP VARIABLES
Swapping of variables is a easy task in programming while using a temporary variable but the catch in this task is, do you know what is swapping of variables ?
swapping can be understand by this Example .
assume you have two buckets one have red color water and other have blue water .First we have to do naming ceremany of buckets
let R is the name of bucket contains red water .
and Bis the name of bucket contains blue water.
SWAPPING
swapping is the process in which the content(VALUE) of one container(VARIABLE) is exchanged with other container(VARIABLE)
In above scenario when water of B bucket is exchanged with water of R bucket is called swapping
and after swapping R contain Blue water and B contain Red water
How this possible ?
Its simple
1 take a blank bucket name as C
2 Pour water of B to blank bucket3 Pour water of R to B
3 Now Pour the water of new bucket we called it C to B
result : B contain Red Water and R contain Blue Water
C is our Temporary bucket
Program for swapping in C++ with temporary variable
#include <iostream>
using namespace std;
int main()
{
int a = 5, b = 10, temp;
cout << "Before swapping." << endl;
cout << "a = " << a << ", b = " << b << endl;
temp = a;
a = b;
b = temp;
cout << "\nAfter swapping." << endl;
cout << "a = " << a << ", b = " << b << endl;
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int a = 5, b = 10;
cout << "Before swapping." << endl;
cout << "a = " << a << ", b = " << b << endl;
a = a + b;
b = a - b;
a = a - b;
cout << "\nAfter swapping." << endl;
cout << "a = " << a << ", b = " << b << endl;
return 0;
}
Program for swapping in C++ without temporary variable.
#include <iostream>
using namespace std;
int main()
{
int a = 5, b = 10;
cout << "Before swapping." << endl;
cout << "a = " << a << ", b = " << b << endl;
a = a + b;
b = a - b;
a = a - b;
cout << "\nAfter swapping." << endl;
cout << "a = " << a << ", b = " << b << endl;
return 0;
}
summary (without temporary variable)
suppose
a=10
b=5
step 1
a=a+b
a=15
step 2
b=a-b
b=15-5
b=10
step 3
a=a-b
a=15-10
a=5
before swapping the value of A and B is 10 and 5 respectively
after swapping the value of A and B is 5 and 10 respectively
This comment has been removed by the author.
ReplyDelete