Categories: C++

Swap Two Numbers Without Using Third Variable

By using the + and – operators, we can swap two numbers without using a third variable.

Main logic:

//Logic for swapping eg a=10, b=5
a = a + b; // a=15
b = a - b; // b=10
a = a - b; //a=5

Program code:

#include <iostream>
using namespace std;

int main()
{
    int a,b;
    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;
    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:
Enter the first number : 45
Enter the second number : 34
Values Before Swapping:  

First Number = 45
Second Number = 34


Values After Swapping:  

First Number = 34
Second Number = 45

Note: also read about Check for palindrome number

Follow Me

Please follow me to read my latest post on programming and technology if you like my post.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Share
Published by
Rabecca Fatima

Recent Posts

Find Intersection of Two Singly Linked Lists

You are given two singly linked lists that intersect at some node. Your task is…

3 months ago

Minimum Cost to Paint Houses with K Colors

A builder plans to construct N houses in a row, where each house can be…

3 months ago

Longest Absolute Path in File System Representation

Find the length of the longest absolute path to a file within the abstracted file…

3 months ago

Efficient Order Log Storage

You manage an e-commerce website and need to keep track of the last N order…

4 months ago

Select a Random Element from a Stream

You are given a stream of elements that is too large to fit into memory.…

4 months ago

Estimate π Using Monte Carlo Method

The formula for the area of a circle is given by πr². Use the Monte…

5 months ago