C++ Program for Swapping of 2 Variables using 3rd Variable

In this C++ Programming practical, we will perform Swapping of 2 Variables using 3rd Variable in C++. The third variable will act as a temporary variable to perform the swapping.

Swapping of 2 Variables using 3rd Variable in C++
#include <iostream>
using namespace std;

int main() {
    int a,b,c;
    cout<<"Enter value of a: ";
    cin>>a;
    cout<<"Enter value of b: ";
    cin>>b;
    cout<<"Before Swapping: a: "<<a<<" b: "<<b<<endl;
    // start: swapping logic
    c=a;
    a=b;
    b=c;
    // end: swapping logic
    cout<<"After Swapping: a: "<<a<<" b: "<<b<<endl;
	return 0;
}
Output
Enter value of a: 4
Enter value of b: 5
Before Swapping a: 4 b: 5
After Swapping a: 5 b: 4

Leave a Reply

Your email address will not be published. Required fields are marked *