C++ Program to Swap Two Variables Without Third Variable

C++ programs to swap two numbers without using third variable have been shown here. The algorithm, pseudocode and time complexity of the programs have been covered here. Check here the flowchart of the programs.






1. C++ Program & output to Swap Two Numbers Without Third Variable (Using Addition and Subtraction)

Code has been copied
/**********************************************
            alphabetacoder.com
C++ program to swap two numbers without third
variable but using arithmetic operators + and -
***********************************************/
#include <iostream>

using namespace std;

int main() {
    // declare variables
    int num1, num2;

    // take input of two numbers 
    cout << "Enter two numbers = ";
    cin >> num1;
    cin >> num2;

    //show numbers before swapping
    cout << "Before swapping: number1 = " << num1 << " and number2 = " << num2 << endl;

    //do swapping using + and -
    num1 = num1 + num2;
    num2 = num1 - num2;
    num1 = num1 - num2;

    //show numbers after swapping
    cout << "After swapping: number1 = " << num1 << " and number2 = " << num2 << endl;

    return 0;
}

Output


Enter two numbers = 5 10

Before swapping: number1 = 5 and number2 = 10

After swapping: number1 = 10 and number2 = 5




2. C++ Program & output to Swap Two Numbers Without Third Variable (Using Multiplication and Division)

Code has been copied
/**********************************************
            alphabetacoder.com
C++ program to swap two numbers without third
variable but using arithmetic operators * and /
***********************************************/
#include <iostream>

using namespace std;

int main() {
    // declare variables
    int num1, num2;

    // take input of two numbers 
    cout << "Enter two numbers = ";
    cin >> num1;
    cin >> num2;

    //show numbers before swapping
    cout << "Before swapping: number1 = " << num1 << " and number2 = " << num2 << endl;

    //do swapping using * and /
    num1 = num1 * num2;
    num2 = num1 / num2;
    num1 = num1 / num2;

    //show numbers after swapping
    cout << "After swapping: number1 = " << num1 << " and number2 = " << num2 << endl;

    return 0;
}

Output


Enter two numbers = 5 10

Before swapping: number1 = 5 and number2 = 10

After swapping: number1 = 10 and number2 = 5