Introduction
In this blog, we will discuss how to write a program to swap two numbers.
We are given 2 numbers and we need to swap the value.
Example:
Sample Input:
a=5
b=6
Sample Output:
a=6
b=5
We will be discussing the following approaches to swap two numbers
- Using temporary variable.
- Without using a temporary variable.
- Using XOR operation
Swapping two numbers using a temporary variable
The naive approach to swap two numbers would be to declare a temporary variable. Store the value of the first variable in a temporary variable, move the value of the second variable to the first variable and then move the value of the temporary variable to the second variable.
Time Complexity for writing a program to swap two numbers = O(1).
It takes constant time.
Till now, I assume you must have got the basic idea of what has been asked in the problem statement. So, I strongly recommend you first give it a try.
Pseudo Code
Algorithm
___________________________________________________________________
procedure swapping():
___________________________________________________________________
1. Declare a, b, temp
2. temp=a
3. a=b
4. b=temp
5. Display the value of a and b
end procedure
___________________________________________________________________
Implementation in C++
#include <iostream>
using namespace std;
int main() {
int a, b, temp;
cin>>a>>b;
cout<<"before swapping"<<endl;
cout<<"a:"<<a<<endl;
cout<<"b:"<<b<<endl;
//swapping
temp = a;
a = b;
b = temp;
//displaying
cout<<"after swapping"<<endl;
cout<<"a:"<<a<<endl;
cout<<"b:"<<b<<endl;
return 0;
}
Output:
Sample Input:
5
6
Sample Output:
before swapping
a:5
b:6
after swapping
a:6
b:5
Complexity Analysis
Time Complexity: O(1), Since no extra operation, constant time is taken.
Space complexity: O(1), no extra variable used.