Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to swap two values without using third variable

C++ Code Example — Basic Programs

ADVERTISEMENT

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

  1. Read two variables: a and b.
  2. Add both numbers and store the sum in a: a = a + b.
  3. Subtract b from the new a to extract the original a, and store it in b: b = a - b.
  4. Subtract the new b from a to extract the original b, and store it in a: 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)
ADVERTISEMENT