C++ Program to swap two numbers without using third variable


In this program, You will learn how to swap two numbers without using third variable in C++.


num1 = num1 + num2

num2 = num1 - num2

num1 = num1 - num2


Example: How to swap two numbers without using third variable in C++

Run it Now
#include<iostream>
using namespace std;

int main() {

    int num1, num2;
    cout << "Enter Two numbers :";
    cin >> num1>>num2;

    num1 = num1 + num2;
    num2 = num1 - num2;
    num1 = num1 - num2;

    cout << "\nAfter Swapping :";

    cout << "\nNum1 is :" << num1;
    cout << "\nNum2 is :" << num2;

    return 0;
}

Output:

Enter Two numbers :12 24
After Swapping :
Num1 is :24
Num2 is :12