Table of contents
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.
Frequently Asked Questions
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: Sep 1, 2024
Easy

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

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

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. 

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

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.

Implementation in C++

  • 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;
}
You can also try this code with Online C++ Compiler
Run Code

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.

Implementation in C++

  • 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;
}
You can also try this code with Online C++ Compiler
Run Code

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.

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.

Implementation in C++

  • 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;
}
You can also try this code with Online C++ Compiler
Run Code

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);

Implementation in C++

  • 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;
}
You can also try this code with Online C++ Compiler
Run Code

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
Also readDecimal to Binary c++

Frequently Asked Questions

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

You can refer to our Guided Path to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingSystem Design, and many more!

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

Live masterclass