C++ Programs to swap two numbers

In this article, we are going to learn how to swap two numbers in C++. We will take input from the user as two numbers and then we will swap these two numbers. This means if variable a holds a value x and variable b holds y value, after swapping a will hold value y and
variable b will hold value x.In this article, we are going to learn this by using multiple techniques.

C++ Programs to swap two numbers


  • C++ program to Swap two numbers using a third variable
  • C++ program to Swap two numbers without using third variable

1.C++ program to Swap two numbers using a third variable


In this example, we are going to swap two numbers. First, we will ask the user to enter two numbers. Once the user will enter the numbers then we will swap them with the help of a third variable. We will use this third variable as a placeholder for one variable until we swap it with the second variable. Let us understand this with the help of the below code.

#include <iostream>

using namespace std;

int main()
{
    int Num1 ,Num2,SwapNo;
    cout << "Please enter value of Number1: ";
    cin >> Num1;
    cout << "Please enter value of Number2: ";
    cin >> Num2;
    SwapNo=Num1;
    Num1=Num2;
    Num2=SwapNo;
    cout<<"Swapped Numbers are:";
	cout<< Number1: "<< Num1 << " Number2: " << Num2;
    return 0;
}

Output

Please enter value of Number1: 7
Please enter value of Number2: 5
Swapped Numbers are:Number1: 5 Number2: 7

2. C++ program to Swap two numbers without using third variable


In this example, we are going to swap two numbers. First, we will ask the user to enter two numbers. Once the user will enter the numbers then we will swap them without taking the help of a third variable.We will use the addition and subtraction operators on the two given numbers to perform the swapping. Let us understand this with the help of the below code.

#include <iostream>

using namespace std;

int main()
{
    int Num1 ,Num2;
    cout << "Please enter value of Number1: ";
    cin >> Num1;
    cout << "Please enter value of Number2: ";
    cin >> Num2;
    Num1=Num1+Num2;
    Num2=Num1-Num2;
    Num1=Num1-Num2;
    cout<<"Swapped Numbers are:";
	cout<< Number1: "<< Num1 << " Number2: " << Num2;
    return 0;
}

Output

Please enter value of Number1: 9
Please enter value of Number2: 12
Swapped Numbers are:Number1: 12 Number2: 9