Write a Program Swap Two Numbers in c++
Write a program to swap two numbers .In this Program we uses Two Method for
swap two numbers. First program we uses Temporary Variable in swap two numbers and second method we don't use temporary variable in swap two numbers.
Example 1:Write a program to swap two numbers using Temporary Variable
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int a=10,b=20,tmp;
cout<<"-swap two numbers-"<<endl;
cout<<"Without swap a and b"<<endl;
cout << "a = " << a << ", b = " << b << endl;
tmp = a;
a = b;
b = tmp;
cout << "\nAfter a and b swapping." << endl;
cout << "a = " << a << ", b = " << b << endl;
return 0;
}
Above swap two numbers program we using temparay variable ,we copied a variable in tmp variable then we copied b variable in a (variable) after copied temp variable in b;
Output:
Without swap a and b
a = 10, b = 20
After a and b swapping.
a = 20, b = 10
Example 2: Write a program to swap two numbers Without using Temporary Variable.
#include <iostream>
using namespace std;
int main()
{
int a=10,b=20;
cout<<"Without swap a and b"<<endl;
cout << "a = " << a << ", b = " << b << endl;
a=a+b;
b=a-b;
a=a-b;
cout << "\nAfter a and b swapping." << endl;
cout << "a = " << a << ", b = " << b << endl;
return 0;
}
Output:-
Without swap a and b
a = 10, b = 20
After a and b swapping.
a = 20, b = 10
Above swap two numbers program we add a =a+b and then b=a-b.Again we a=a-b.So finaly a=20 and b=10;