This is the most basic of swapping two numbers in C++ program. This tutorial provides you with the source code to swap numbers in C++.
There are basically two ways to swap numbers.
- Using third Variable
- Without using third variable.
In this section, we will learn using the third variable and in the next section, you will learn without the use of the third variable.
C++ Program to Swap Two Numbers using a Third Variable
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | #include <iostream> using namespace std; int main() { int num1, num2, temp; cout << "Enter num1: "; cin >> num1; cout << "Enter num2: "; cin >> num2; temp = num1; num1 = num2; num2 = temp; cout << "\nResult after Swapping Two Numbers:\n"; cout << "num1: " << num1; cout << "\nnum2: " << num2; return 0; } |
Output:
Enter num1: 10
Enter num2: 20
Result after Swapping Two Numbers:
num1: 20
num2: 10
The program takes the two numbers from the users as input and swaps those values using a third or temporary variable. Finally, print the result of swapped values.
You may go through the following program in C++: