Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to swap two values of 2 no.

C++ Code Example — Basic Programs

ADVERTISEMENT

WAP to swap two values of 2 no.

Objective

Write a C++ program to swap the values of two variables using a third variable.

Algorithm / Approach

  1. Declare three variables: a, b, and temp.
  2. Read values for a and b.
  3. Print the values before swapping.
  4. Store the value of a in temp: temp = a.
  5. Overwrite a with the value of b: a = b.
  6. Overwrite b with the original value of a stored in temp: b = temp.
  7. Print the values after swapping.
main.cpp
#include<iostream>
using namespace std;
int main(){
 int a, b, temp;
 cout<< "Enter Values of A and B: ";
 cin>>a>>b;
 cout<<"Before Swapping ";
 cout<<"A = "<< a<<" B = "<< b;
 cout<< endl;
 temp = a;
 a = b;
 b = temp;
 cout<<"After Swapping ";
 cout<<"A = "<< a<<" B = "<< b;
 cout<< endl;
return 0;
}

Expected Output

Enter Values of A and B: 10 20
Before Swapping A = 10 B = 20
After Swapping A = 20 B = 10

Explanation of the Program

  • Swapping variables is a fundamental concept in programming, heavily used in sorting algorithms.
  • Think of the variables as two cups containing different liquids. To swap the liquids without mixing them, you must use a third empty cup (temp) to temporarily hold one liquid while you move the other.

Complexity

Time Complexity O(1)
Space Complexity O(1)
ADVERTISEMENT