cpp program swap two numbers by bitwise,multiple and addition

 cpp program swap two numbers 


Swapping the two number is a tricky task in cpp programming language,In this example,swap two numbers with the help of bitwise operators, addition and subtraction, and multiplication. 

Swap two number by addition and subtraction


#include<iostream>
using namespace std;
int main()
{
    int a,b;
    a=10,b=20;
    a=a+b;
    b=a-b;
    a=a-b;
    cout<<"a ="<<a<<endl<<"b ="<<b;
    return 0;
}

Output:
a=20
b=10

in the above example,a+b is equal to 30 and store in the a variable then a-b is assigned to the variable due to 30-20 is equal to 10 then a-b is assign to the a due to 30-10 is equal to 20.

Swap two number by multiplication and division

#include<iostream>
using namespace std;
int main()
{
    int a,b;
    a=10,b=20;
    a=a*b;
    b=a/b;
    a=a/b;
    cout<<"a ="<<a<<endl<<"b ="<<b;
    return 0;
}

Ouptut:
a=20
b=10

swap two number by bitwise operators

#include<iostream>
using namespace std;
int main()
{
    int var1,var2;
    var1=10;
    var2=20;
    var1=var1^var2;
    var2=var1^var2;
    var1=var1^var2;
    cout<<"var1 ="<<var1<<" var2="<<var2;
    return 0;
}

Output:
var1 =20 var2=10

Comments

Popular posts from this blog

Diferrence between flutter and react native

Flutter Widgets

Flutter layout