Thursday, 28 August 2014

Filled Under: ,

C++ Program to Swap Two Numbers

Share
C++ Program to Swap Two Numbers:Swapping means to interchange the value of two variables.For example if  variable a store 10 and another variable b store 20 then after swapping  b has 10 and a has 20. In C/C++ we can do the swapping in two way :- 
  • using extra variable
  • without using extra variable
C++ Program to Swap Two Numbers


C++ Program to Swap Two Numbers using extra variable

#include <iostream>
using namespace std;

int main() {
    
    int a = 25, b = 15, 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;
}

Output

Before swapping.a = 25, b = 15 
After swapping. a = 15, b = 25

C++ Program to Swap Two Numbers without using extra variable


#include <iostream>
using namespace std;

int main() {
    
    int a = 25, b = 15;

    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;
}


Output

Before swapping.a = 25, b = 15 
After swapping. a = 15, b = 25