Tuesday 17 December 2013

SWAP VARIABLES WITHOUT USING THIRD VARIABLE EXAMPLE USING JAVA

public class Main {

    /**
     * @param args the command line arguments
     */
   public static void main(String[] args) {

                int num1 = 20;
                int num2 = 40;

                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("After Swapping");
                System.out.println("Value of num1 is :" + num1);
                System.out.println("Value of num2 is :" +num2);
        }


}

output:
Before Swapping
Value of num1 is :20
Value of num2 is :40
After Swapping
Value of num1 is :40
Value of num2 is :20


No comments:

Post a Comment

Comment