Here is a C++ program to swap two numbers without using temporary variable.
Before swapping
A = 3, B = 4
After swapping
A = 4, B = 3
C++ Program to swap two numbers using a temporary variable
This program uses a temporary third variable temp of type int. Temporary variable is used to store the value of first number. Then we copy second variable in to first variable. As we have saved the value of first variable in temp, we can reassign it not to second variable. This is the safest way to swap two variables.
#include <iostream> using namespace std; int main() { int num1, num2, temp; cout << "Enter Two Integers\n"; cin >> num1 >> num2; cout << "Before Swapping\n"; cout << "Num1 = " << num1 << "\nNum2 = " << num2 << endl; // Swap two numbers temp = num1; num1 = num2; num2 = temp; cout << "After Swapping\n"; cout << "Num1 = " << num1 << "\nNum2 = " << num2; return 0; }Output
Enter Two Integers 5 12 Before Swapping Num1 = 5 Num2 = 12 After Swapping Num1 = 12 Num2 = 5
C++ Program to swap two numbers without using a temporary variable
We first store the sum of two input numbers in the first input variable. The numbers can then be swapped using the sum and subtraction from sum. There is one problem in this approach, the sum of both numbers may overflow the range of integer, in that case we will get wrong values.
#include <iostream> using namespace std; int main() { int num1, num2, temp; cout << "Enter Two Integers\n"; cin >> num1 >> num2; cout << "Before Swapping\n"; cout << "Num1 = " << num1 << "\nNum2 = " << num2 << endl; // Swap two numbers num1 = num1 + num2; num2 = num1 - num2; num1 = num1 - num2; cout << "After Swapping\n"; cout << "Num1 = " << num1 << "\nNum2 = " << num2; return 0; }Output
Enter Two Integers 9 11 Before Swapping Num1 = 9 Num2 = 11 After Swapping Num1 = 11 Num2 = 9
C++ Program to swap two numbers using XOR operator
#include <iostream> using namespace std; int main() { int num1, num2, temp; cout << "Enter Two Integers\n"; cin >> num1 >> num2; cout << "Before Swapping\n"; cout << "Num1 = " << num1 << "\nNum2 = " << num2 << endl; // Swap two numbers num1 = num1 ^ num2; num2 = num1 ^ num2; num1 = num1 ^ num2; cout << "After Swapping\n"; cout << "Num1 = " << num1 << "\nNum2 = " << num2; return 0; }Output
Enter Two Integers 9 11 Before Swapping Num1 = 9 Num2 = 11 After Swapping Num1 = 11 Num2 = 9
Recommended Posts