New Tutorials:   NUMPY    TKINTER    KOTLIN    JAVASCRIPT    SASS/SCSS    PL/SQL    Matplotlib    C++ Programs
See the Tutorial List

C++ Swap two numbers without using a 3rd variable

Hello Everyone!

In this tutorial, we will learn how to Swap two numbers without using a 3rd variable, in the C++ programming language.

Code:

#include <iostream>
using namespace std;

int main()
{
    cout << "\n\nWelcome to Studytonight :-)\n\n\n";
    cout << " =====  Program to Swap two numbers without using a 3rd variable ===== \n\n";

    // variable declaration
    int a,b;

    //taking input from the command line (user)
    cout << "Enter the first number : ";
    cin >> a;

    cout << "Enter the second number : ";
    cin >> b;

    cout << "\n\nValues Before Swapping:  \n"<<endl;
    cout << "First Number = " << a <<endl;
    cout << "Second Number = " << b <<endl;

    // Logic for swapping the two numbers 
    // without using any extra variable
    a = a + b;
    b = a - b;
    a = a - b;

    cout << "\n\nValues After Swapping:  \n"<<endl;

    cout << "First Number = " << a <<endl;
    cout << "Second Number = " << b <<endl;
    cout << "\n\n\n";

    return 0;
}

Output:

C++ swapping without using a temp variable program

Now let's see what we have done in the above program.

Program Explained:

Let's break down the parts of the code for better understanding.

//Logic for swapping the two numbers without using any extra variable
a = a + b;
b = a - b;
a = a - b;

The logic involved here is that, similar to every other programming language, the variables in C++ stores the most recent value stored into it.

To understand the above logic, let's use some dummy values.

Initially, a = 30, b=55,

Then we do, a = a + b, so new value stored in a is:

a = 30 + 55

Then, b = a - b, here the a would be the most recently stored value.

So, b = (30 + 55) - 55 = 30

i.e. b = 30 (the initial value of a)

Finally we do, a = a - b,

So, a = (30 + 55) - 30 = 55

i.e. a = 55 (the initial value of b)

So as you can see, we have swapped the initial values of a and b into each other.

Keep Learning : )