C++ Program to swap two numbers

In this C++ program, we need to swap the values in two variables.

What is the swapping of two numbers?

Swapping two numbers means exchanging the values of two variables. If you have a=1 and b=2, the values of the variables a and b are mutually exchanged. After swapping the result are a=2 and b=1. This operation can be made either by using an extra variable or can be done without the help of an additional variable. The simplest method to swap two variables is to use a third variable. 

How can we implement swapping in C++?

The program always starts with the main function. Within the main body declare 3 integer type variables to store the two numbers and one is a temporary variable used to help to swap operation. 

Ask the user to enter two numbers using the object cout and read the entered values to two variables a and b using the object cin.Display the current value of the variables a and on the screen using cout.Access the next line with the help of the command endlendl is a command or a manipulator used to insert a new line character.

The content of the first variable is copied into the temp variable. Then the content of the second variable is copied to the first variable. Now the content of the temporary variable is copied to the second variable. And now the swapping process is completed. Display the result after swapping on the screen using cout.

For example

  1. Initially, you have a=10 and b=20; You have a third variable called temp; Then swapping can be performed as follows
  2. Load the value of variable a to temp; temp=a
  3. Now variable a is free then load the value of variable b to a; a=b
  4. Now variable b is free and loads the value of a from temp to b; b=temp
  5. The result will be like; a=20 and b=10.
Swap 2 Numbers

Algorithm

Step 1:  Call the header file iostream.

Step 2:  Use the namespace std.

Step 3:  Open the integer type main function; int main().

Step 4:  Declare integer type variables; a, b, temp.

Step 5:  Print a message on the screen to “Enter two numbers:” using cout.

Step 6:  Read the first number to variable a and the second number to variable b using cin.

Step 7:  Display the values of variables before swapping on the screen using cout.

Step8 :  Perform swapping.

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

Step 9: Display the values of variable a and after swapping on the screen.

Step 10: Exit.
 

C++ Source Code

                                          #include <iostream>
using namespace std;

int main() {

  int a, b, temp;
    
  cout << "Enter two numbers: ";
  cin >> a >> b;

    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

Enter two numbers: 10
20
Before swapping.
a = 10, b = 20

After swapping.
a = 20, b = 10