Swap Two Numbers Without Third Variable in C++
Last Updated :
14 Feb, 2024
In C++, swapping two numbers means we need to exchange the value of two numbers. In this article, we will learn how to swap two numbers without using the third variable in C++.
Example
Input:
a=10
b=20
Output:
After swapping:
a=20
b=10
Swap Two Numbers Without Using a Third Variable
In C++ we can swap two numbers without using a temporary variable by using simple addition and subtraction arithmetic trick as shown.
C++ Program to Swap Two Numbers Without Using Temporary Variable
The below program shows how we can swap two numbers without using a temporary variable.
C++
#include <iostream>
using namespace std;
int main()
{
int a = 5, b = 10;
int x = 50, y = 100;
cout << "Before swapping: x = " << x << ", y = " << y
<< endl;
x = x + y;
y = x - y;
x = x - y;
cout << "After swapping: x = " << x << ", y = " << y
<< endl
<< endl;
return 0;
}
|
Output
Before swapping: x = 50, y = 100
After swapping: x = 100, y = 50
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...