How to swap two number without third variable





This  is  simple  but  some  time  make you  brain teaser  at interview .  Just  simple  and try
 yourself




public class SwapNumber {

public static void main(String[] args) {
// TODO Auto-generated method stub
int num1 = 20;
int num2 = 90;
System.out.println("Before Swapping");
System.out.println("Value of num1 is :" + num1);
System.out.println("Value of num2 is :" +num2);
//add both the numbers and assign it to first
num1 = num1 + num2;
num2 = num1 - num2;
num1 = num1 - num2;
System.out.println("Before Swapping");
System.out.println("Value of num1 is :" + num1);
System.out.println("Value of num2 is :" +num2);
    }

}

    

This  is  out put  of code.



Before Swapping
Value of num1 is :20
Value of num2 is :90
Before Swapping
Value of num1 is :90

Value of num2 is :20
How to swap two number without third variable How to swap two number without third variable Reviewed by Mukesh Jha on 9:14 AM Rating: 5

No comments:

Add your comment

All Right Reserved To Mukesh Jha.. Theme images by Jason Morrow. Powered by Blogger.