Saturday, 31 October 2015

swapping two numbers without using third variable

import java.util.Scanner;
class Swap
{
void swap1(int a,int b)
{
a=a+b;
b=a-b;
a=a-b;
System.out.println("value of a is:"+a);
System.out.println("value of b is:"+b);
}
void swap2(int a,int b)
{
a=a^b;
b=a^b;
a=a^b;
System.out.println("value of a is:"+a);
System.out.println("value of b is:"+b);
}
void swap4(int a,int b)
{
a=a+b-(b=a);
System.out.println("value of a is:"+a);
System.out.println("value of b is:"+b);
}
void swap5(int a,int b)
{
a=b-~a-1;
b=a+~b+1;
a=a+~b+1;
System.out.println("value of a is:"+a);
System.out.println("value of b is:"+b);
}

}
class SwapTest
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
int b=sc.nextInt();
Swap s1=new Swap();
System.out.println("value of a is:"+a);
System.out.println("value of b is:"+b);
s1.swap1(a,b);
s1.swap2(a,b);
s1.swap5(a,b);
s1.swap4(a,b);
}
}

No comments:

Post a Comment