Q:

C++ Program To Swap Two Numbers Without Using Third Variable

0

Write A C++ Program To Swap Two Numbers Without Using Third Variable Using Functions .

Logic :- 

For This question We Have 3 Method to Swap Without Using third variable .

1. Plus/Minus
2. Multiply/Divide
3. Bitwise Operator 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Bitwise Operator

#include<iostream>
using namespace std;
void swpa(int ,int );

int main()
{

    int a,b;
    
 cout<<"Enter Two Number You Want To Swap :\n";
    cin>>a>>b;
    
 cout<<"\nAfter Swapping Numbers Are Given below\n\n";
    swap(a,b);
 
    cout<<a<<"\t"<<b<<" \n";
    return 0;
}
void swap(int x,int y)
{
 //without using third variable
 x=x^y;
 y=x^y;
 x=x^y;
}

 

Output:

Enter Two Number You Want To Swap :

10000

20000

After Swapping Numbers Are Given below

20000 10000 

need an explanation for this answer? contact us directly to get an explanation for this answer
need an explanation for this answer? contact us directly to get an explanation for this answer

Multiply/Divide

#include<iostream>
using namespace std;
void swpa(int ,int );

int main()
{
 
    int a,b;
    
 cout<<"Enter Two Number You Want To Swap :\n";
    cin>>a>>b;
    
 cout<<"\nAfter Swapping Numbers Are Given below\n\n";
    swap(a,b);
 
    cout<<a<<"\t"<<b<<" \n";
    return 0;
}
void swap(int x,int y)
{
 //without using third variable
 x=x*y;
 y=x/y;
 x=x/y;
}

 

Output:

Enter Two Number You Want To Swap :

1000 2000

After Swapping Numbers Are Given below

2000 1000 

need an explanation for this answer? contact us directly to get an explanation for this answer
need an explanation for this answer? contact us directly to get an explanation for this answer

 Plus/Minus

#include<iostream>
using namespace std;
void swpa(int ,int );

int main()
{
 
    int a,b;
    
 cout<<"Enter Two Number You Want To Swap :\n";
    cin>>a>>b;
    
 cout<<"\nAfter Swapping Numbers Are Given below\n\n";
    swap(a,b);
 
    cout<<a<<"\t"<<b<<" \n";
    return 0;
}
void swap(int x,int y)
{
 //without using third variable
 x=x+y;
 y=x-y;
 x=x-y;
}

 

Output:

Enter Two Number You Want To Swap :

100 200

After Swapping Numbers Are Given below

200 100 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (3)

C++ Program to Calculate Standard Deviation Using ... >>
<< Swapping of Two Numbers in C++ Using Functions | C...