C++ Program to Swap Two Numbers Using Temporary Variable

In this program we will learn how to swap two numbers with third(temp) variable. Swapping means interchanging. For example, if in your cpp program you have taken two variables a and b where a = 4 and b = 5, then before swapping a = 4, b = 5 after swapping a = 5, b = 4. In the first cpp program to swap numbers we will use a temporary variable to swap two numbers.

Example: Swap Two Numbers Using Temporary Variable

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

#include <iostream>

using namespacestd;

intmain()

{

intnumber1,number2;

inttemp;

cout<<"Enter first integer: ";

cin>>number1;

cout<<"Enter second integer: ";

cin>>number2;

cout<<"a = "<<number1<<" b = "<<number2<<endl;

temp=number1;

number1=number2;

number2=temp;

cout<<"After Swapping"<<endl;

cout<<"a = "<<number1<<" b = "<<number2<<endl;

return0;

}

When you run the program, the output will be following:

1

2

3

4

5

Enter first integer: 3

Enter second integer: 5

a = 3 b = 5

After Swapping

a = 5 b = 3

First, we declare a temporary variable then take two numbers from the user input.

The contents of the first variable is copied into the temp variable. Then, the contents of the second variable is copied to the first variable.

Finally, the contents of the temp variable is copied back to the second variable which completes the swapping process.