WAP to swap two values without using third variable
Objective
Write a C++ program to swap the values of two variables without using a third variable.
Algorithm / Approach
- Read two variables:
aandb. - Add both numbers and store the sum in
a:a = a + b. - Subtract
bfrom the newato extract the originala, and store it inb:b = a - b. - Subtract the new
bfromato extract the originalb, and store it ina:a = a - b.
main.cpp
#include<iostream>
using namespace std;
int main() {
int a, b;
cout<<"Enter Values for A and B: ";
cin>>a>>b;
cout<<"Before Swapping ";
cout<<"A = "<< a<<" B = "<< b;
cout<< endl;
a = a+b;
b = a-b;
a = a-b;
cout<<"After Swapping ";
cout<<"A = "<< a<<" B = "<< b;
cout<< endl;
return 0;
}
Expected Output
Enter Values for A and B: 10 20 Before Swapping A = 10 B = 20 After Swapping A = 20 B = 10
Explanation of the Program
- This is a clever mathematical trick to swap two variables without consuming extra memory (useful in highly constrained environments).
- By temporarily storing the combined sum of both variables in the first variable, we can mathematically isolate and extract the original values one by one.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)