C++ program to swap two numbers

Swapping refers to the exchanging of values stored in different variables. For example, if there are two variables named a and b, and the value inside a is 4 and inside b is 5. Then swapping these two variables would result in –

a = 5 and b = 4.

In this program we will learn how to swap the values of two variables.

To understand this example you should have the knowledge of following topics in c++ –

  • Variable declaration.
  • Cout statement

Example 1

In this example we will swap the values of two variables with the help of a third variable.

#include <iostream>
using namespace std;
int main()
{
    int x = 4, y = 7, z;
    cout << "Initial Values -" << endl;
    cout << "x = " << x << ", y = " << y << endl;
    z = x;
    x = y;
    y = z;

    cout << "\nValues after swapping -" << endl;
    cout << "x = " << x << ", y = " << y << endl;

    return 0;

}

Output

Initial Values -

x = 4, y = 7

Values after swapping -

x = 7, y = 4

Explanation

  • First of all, inside main function we have declared three variables named x, y and z and initilized x and y  with 4 and 7 respectively.
  • Then we have printed the values of x and y.
  • Next we have stored the value (or more specifically w have copied the value of x to the variable z), So now z = 4.
  • After that we have stored the value of y in x. So now the value inside x is 7.
  • Then we have stored the value of z in y. So the value inside y is now 4.
  • Lastly we have displayed the swapped values.

Example 2

Swapping without using third variable.

#include <iostream>
using namespace std;
int main()
{
    int x = 5, y = 10;
    cout << "values before swapping -" << endl;
    cout << "x = " << x << ", y = " << y << endl;

    x = x + y;
    y = x - y;
    x = x - y;

    cout << "\nValues after swapping -" << endl;
    cout << "x = " << x << ", y = " << y << endl;

    return 0;
}