Saturday, December 4, 2021
HomeTop Coding QuestionWrite a program to swap two numbers with and without using third...

Write a program to swap two numbers with and without using third variable.

there are two appoach to swap two number one is by using third variable and another is without third variable

so what is swapping of number?.

swapping of number is just to swap the value of a to b and b to a.

example:

input: a=3 b=4
output:a=4 b=3

input:a=9 b=1
output:a=1 b=9

1st Approach:(Using third variable)

logic:

logic behind is just to create a temp variable.
assign value of a to temp.
b to a
then assign b=temp

#include<iostream>
using namespace std;
int main()
{
 int a,b;
 cin>>a>>b;
 cout<<"before swapping"<<endl;
 cout<<"a: "<<a<<endl;
 cout<<"b: "<<b<<endl;
 int temp;
 temp=a;
 a=b;
 b=temp;
 cout<<"after swapping"<<endl;
 cout<<"a: "<<a<<endl;
 cout<<"b: "<<b<<endl;

}

Output:

before swapping
a: 1
b: 4
after swapping
a: 4
b: 1

2nd Approach:(without third variable)

we can swap two number without using third variable by using xor operator.

Logic:

the xor of two number return the value which has all bits as 1.
#include<iostream>
using namespace std;
int main()
{
 int a,b;
 cin>>a>>b;
 cout<<"before swapping"<<endl;
 cout<<"a: "<<a<<endl;
 cout<<"b: "<<b<<endl;
 a=a^b;
 b=a^b;
 a=a^b;
 cout<<"after swapping"<<endl;
 cout<<"a: "<<a<<endl;
 cout<<"b: "<<b<<endl;

}
before swapping
a: 1
b: 4
after swapping
a: 4
b: 1

Time complexity:O(1)

Space Complexity:O(1)

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments