Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

swap
variable
third
numbers

How to swap two numbers without using a third variable

Educative Answers Team

There are many ways to swap two numbers without using a third variable.

1. Using arithmetic operators

svg viewer
Swapping two variables without using a third variable.

The arithmetic operators for addition and subtraction can be used to perform the swap without using a third variable.

#include <iostream>
using namespace std; 
  
int main() 
{ 
  int x = 10, y = 50; 

  x = x + y; // x = 60
  y = x - y; // y = 10
  x = x - y; // x = 50
  cout << "After Swapping: x = " << x << ", y = " << y; 
} 
  

Similarly, multiplication and division can be used to perform the swap without using the third variable.

#include <iostream>
using namespace std; 
  
int main() 
{ 
  int x = 10, y = 50; 

  x = x * y; // x = 500
  y = x / y; // y = 10
  x = x / y; // x = 50
  cout << "After Swapping: x = " << x << ", y = " << y; 
} 
  

2. Using Bitwise XOR

The result of the bitwise XOR operator is 11 if the corresponding bits of two operands are opposite. It is denoted by ^.

#include <iostream>
using namespace std; 
  
int main()
{
  int x = 10, y = 50;
 
  x = x ^ y;
  y = x ^ y;
  x = x ^ y;
 
  cout << "After Swapping: x = " << x << ", y = " << y; 
}
  

RELATED TAGS

swap
variable
third
numbers
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring