Algorithm
-
Declare variables:
num1, num2, and temp are declared to store the two numbers and a temporary variable for swapping.
Input two numbers:
The user is prompted to input the values for num1 and num2.
Swap the numbers using a temporary variable:
The values of num1 and num2 are swapped using a temporary variable temp. This is a common technique to exchange values between two variables.
Display the swapped numbers:
The program prints the values of num1 and num2 after swapping to confirm the swap.
Code Examples
#1 Code Example-C++ Programing Swap Numbers (Using Temporary Variable)
Code -
C++ Programming
#include <iostream>
using namespace std;
int main()
{
int a = 5, b = 10, 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;
}
Copy The Code &
Try With Live Editor
Output
a = 5, b = 10
After swapping.
a = 10, b = 5
#2 Code Example- C++ Programing Swap Numbers Without Using Temporary Variables
Code -
C++ Programming
#include <iostream>
using namespace std;
int main()
{
int a = 5, b = 10;
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;
}
Copy The Code &
Try With Live Editor
Output
a = 5, b = 10
After swapping.
a = 10, b = 5
Demonstration
C++ Programing Example to Swap Two Numbers- DevsEnv