Swapping two variables in c++

By
Advertisement
Swapping in C++ is interchange the value of two variables with each other to do this task you have to declare third variable . Without using third variable you have to use mathematical logic . See the both programs below .





Program using third variable.

#include<iostream>
using namespace std;

int main()
{
int a=10 ,b=50; //initialize variable with values;
int temp; //third temporary variable is declared.

cout<<"a ="<<a<<" " <<"b ="<<b<<endl; //value before swaping

temp = a;
a = b;
b = a;

cout<<"a ="<<a<<" " <<"b ="<<b<<endl; //value before swaping

system("pause");


}


Program without using third variable.



#include<iostream>
using namespace std;

int main()
{
int a=10 ,b=50; //initialize variable with values;

cout<<"a ="<<a<<" " <<"b ="<<b<<endl; //value before swaping

a=a+b;
b=a-b;
a=a-b;

cout<<"a ="<<a<<" " <<"b ="<<b<<endl; //value before swaping

system("pause");


}
swapping

0 comments:

Post a Comment