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
- Declare three variables:
a,b, andtemp. - Read values for
aandb. - Print the values before swapping.
- Store the value of
aintemp:temp = a. - Overwrite
awith the value ofb:a = b. - Overwrite
bwith the original value ofastored intemp:b = temp. - 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)