C++ Program to Swap Two Numbers without using Third Variable

In this tutorial, we will write a program to swap numbers without using a temporary variable in C++. . There are two ways to swap variables.

  1. Using + and
  2. Using * and /

Let us go through each of them with a C program. You may check out the following program.

Both of the programs take the user input for two integers and swap those two values in two separate ways without using a temporary variable.


C++ Program to Swap Two Numbers without using Third Variable

1. Using + and –

#include <iostream>
using namespace std;

int main()
{
  int num1, num2;

  cout << "Enter the first number: ";
  cin >> num1;
  cout << "Enter the second number: ";
  cin >> num2;

  num1 = num1 + num2;  //a = 10 + 20 = 30
  num2 = num1 - num2;  //b = 30 - 20 = 10
  num1 = num1 - num2;  //a = 30 - 10 = 20

  cout << "\nResult after Swapping Two Numbers:\n";
  cout << "num1: " << num1;
  cout << "\nnum2: " << num2;

  return 0;
}

Output:

Enter the first number: 10
Enter the second number: 20

Result after Swapping Two Numbers:
num1: 20
num2: 10


2. Using * and /

#include <iostream>
using namespace std;

int main()
{
  int num1, num2;

  cout << "Enter the first number: ";
  cin >> num1;
  cout << "Enter the second number: ";
  cin >> num2;

  num1 = num1 * num2; //a = 10 * 20 = 200
  num2 = num1 / num2; //b = 200 / 20 = 10
  num1 = num1 / num2; //a = 200 / 10 = 20

  cout << "\nResult after Swapping Two Numbers:\n";
  cout << "num1: " << num1;
  cout << "\nnum2: " << num2;

  return 0;
}

Output:

Enter the first number: 5
Enter the second number: 10

Result after Swapping Two Numbers:
num1: 10
num2: 5

Note that the swapping using / and * will not work if one of the swapping values is zero (0).

You may go through the following program in C++: