1.
Introduction
1.1.
Problem Statement
2.
Approach 1: Swap two numbers by using arithmetic operators.
2.1.
Algorithm
2.2.
Implementation in C++
2.3.
C++
2.4.
Implementation in C++
2.5.
C++
2.5.1.
Complexity Analysis
3.
Approach 2: Swap numbers by using Bitwise XOR operator
3.1.
Implementation in C++
3.2.
C++
3.2.1.
Complexity Analysis
4.
Approach 3: Swap numbers by using single line expressions
4.1.
Implementation in C++
4.2.
C++
4.2.1.
Complexity Analysis
5.
5.1.
What are the 3 methods to swap two numbers?
5.2.
What is swapping?
5.3.
What is the process of swapping?
5.4.
What is required for swapping?
5.5.
What do you mean by XOR Operations?
5.6.
What is the Swap() function?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

# Write a Program to Swap two numbers without using any third variable

Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

## Introduction

We all started our coding journey by writing the famous â€śHello World!â€ť program and some basic ones like swapping two numbers. Developing good coding skills need practice. You simply can't go to the coding interview and try to solve the coding tasks in a short time. That's one of the most frequent reasons coding job interviews fail.

In a telephonic round, the interviewer may ask slightly simpler code problems, such as how to swap two numbers without using third variable.

This article discusses how to write code to swap two numbers without using third variable. So letâ€™s start.

### Problem Statement

Ninja Coder gave you two numbers; your task is to swap two numbers without using third variable.

Before jumping to the solution directly, we recommend solving the question in Coding Ninjas Studio Problems Section.

## Approach 1: Swap two numbers by using arithmetic operators.

Our first approach to swap two numbers without using third variable is by using Arithmetic Operators. We can solve this problem in two ways:

1. Using Addition and Subtraction Operators.
2. Using Multiplication and Division Operators.

### Algorithm

For using the first method to swap two numbers without using third variable, follow the given steps:

đź§© Step 1: Find the Sum of the given two numbers and store it in one of the two given numbers.

đź§© Step 2:  We can use the sum and subtraction from the sum to swap two numbers without using third variable.

• C++

### C++

``#include <bits/stdc++.h>using namespace std;int main(){    double a,b;    cout<<"Enter the value of number a = ";    cin >>a;        cout<<"Enter the value of number b = ";    cin >>b;       // Using + and - operators to swap two numbers without using third variable     a = a + b; // May cause overflow.    b = a - b;      a = a - b;          cout << "After Swapping two numbers: a =" << a << ", b=" << b;}``

Output

``````Enter the value of number a = 23
Enter the value of number b = 3
After Swapping two numbers: a = 3, b= 23``````

Similarly, for using the second method to swap two numbers without using third variable, follow the given steps:

đź§© Step 1:  Find the product of the given two numbers and store it in one of the two given numbers.

đź§© Step 2: We can use the product and division of the product to swap two numbers without using third variable.

• C++

### C++

``#include <bits/stdc++.h>using namespace std; int main(){    double a,b;    cout<<"Enter the value of number a = ";    cin >>a;        cout<<"Enter the value of number b = ";    cin >>b;         // Using * and / operators to swap two numbers without using third variable     a = a * b; //fails if any of the numbers is zero.    b = a / b;     a = a / b;         cout << "After Swapping two numbers: a =" << a << ", b=" << b;}``

Output

``````Enter the value of number a = 23
Enter the value of number b = 3
After Swapping two numbers: a = 3, b= 23``````

Try and compile with online c++ compiler.

#### Complexity Analysis

Time Complexity: O(1); since we are using arithmetic operators, these operators take constant time. So, the time complexity is constant.

Space Complexity: O(1); since we are not using any extra space to store the numbers, the space complexity is also constant.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

## Approach 2: Swap numbers by using Bitwise XOR operator

We can swap two numbers without using third variable using Bitwise XOR Operator.

Letâ€™s first see an example of an XOR operation on two binary numbers.

a = 3 => 0011 in binary.

b = 5 => 0101 in binary.

XOR of a and b is 0110.

• C++

### C++

``#include <iostream>using namespace std; void swap(int &a, int &b){    if (a != b)    {        a = a ^ b;        b = a ^ b;        a = a ^ b;    } } int main(){    int a = 3, b = 5;    swap(a, b);     cout << "After Swapping two numbers: a =" << a << ", b=" << b;     return 0;}``

Output

``After Swapping two numbers: a = 5, b= 3``

#### Complexity Analysis

Time Complexity: O(1); since we are using bitwise XOR operation, these operations take constant time. So, the time complexity is constant.

Space Complexity: O(1); since we are not using any extra space to store the numbers, the space complexity is also constant.

## Approach 3: Swap numbers by using single line expressions

In our third approach, we will use Single Line Expressions to swap two numbers without using third variable.

We can also use any of the given Single Line Expressions to swap two numbers in a single line:

â†’ x = x ^ y ^ (y = x);

â†’ x = x + y â€“ (y = x);

â†’ x = (x Ă— y) / (y = x);

• C++

### C++

``#include <iostream>using namespace std; void swap(int &a, int &b){    // a = a ^ b ^ (b = a);    // a = a + b - (b = a);    a = (a * b) / (b = a);} int main(){    int a = 3, b = 23;    swap(a, b);     cout << "After Swapping two numbers: a =" << a << ", b=" << b;     return 0;}``

Output

``After Swapping two numbers: a = 23, b= 3``

#### Complexity Analysis

Time Complexity: O(1); these single-line operations take constant time. So, the time complexity is constant.

Space Complexity: O(1); since we are not using any extra space to store the numbers, the space complexity is also constant.

Check out this problem - XOR Queries On Tree

### What are the 3 methods to swap two numbers?

Three common methods to swap two numbers are using a third variable, using arithmetic operations, and using bitwise XOR.

### What is swapping?

Swapping is the process of interchanging the values of two variables, effectively exchanging their contents.

### What is the process of swapping?

The process of swapping involves temporarily storing the value of one variable, assigning the value of the second variable to the first, and then assigning the stored value to the second variable.

### What is required for swapping?

Swapping requires two variables that you want to exchange their values and a temporary storage location (variable) to hold one of the values during the exchange process.

### What do you mean by XOR Operations?

XOR operation is a basic boolean logic operation. Two input bits are compared via XOR, which produces one output bit. The Logic of the XOR operation is very simple. When the bits match, the outcome is 0. When the bits vary, the outcome is 1.

### What is the Swap() function?

The Swap() is a built-in function in C++ STL. The function accepts two required parameters, x and y, which must be swapped. The function simply swaps the values of the two variables and doesn't return anything. We can use any data type for the parameters. The syntax is swap(x,y).

## Conclusion

We ran through three approaches to swap two numbers without using third variable. We started using the arithmetic operators to swap two numbers. Further, we discussed programs using bitwise XOR operators and Single-line Expressions to swap two numbers without using third variable.

We hope this blog helped you to explain how to write a program to swap two numbers without using third variable. We recommend you visit our articles related to swapping two numbers, such as

If you liked our article, do upvote our article and help other ninjas grow.  You can refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingSystem Design, and many more!

Head over to our practice platform Coding Ninjas Studio to practice top problems, attempt mock tests, read interview experiences and interview bundles, follow guided paths for placement preparations, and much more!!

We wish you Good Luck! Keep coding and keep reading Ninja!!

Live masterclass