C++ Swapping of 2 Variables Without using 3rd Variable

In this C++ programming tutorial we will see Swapping of 2 Variables Without using 3rd Variable in C++ programming. We won’t be using any third temporary variable to perform swapping but will apply mathematical operations in a systematic way to perform the swapping.

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

int main() {
 int a,b;
   
    cout<<"Enter value of a: ";
    cin>>a;
    cout<<"Enter value of b: ";
    cin>>b;
    a=a+b;
    b=a-b;
    a=a-b;
    cout<<"After swap a: "<<a<<" b: "<<b;
    return 0;
}
Output
Enter value of a: 4
Enter value of b: 5
After swap a: 5 b: 4

Leave a Reply

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