Thursday, 11 February 2016

Swapping of two numbers without using temporary variable

Swapping of two numbers without using temporary variable:
===============================================
1st way:
=======
package files;

public class SwapProgDemo {

public static void main(String[] args) {

int x = 10;

        int y = 20;
        
        System.out.println("Before swap:");
        System.out.println("x value: "+x);
        System.out.println("y value: "+y);
        
        x = x+y;
        y = x-y;
        x = x-y;
        
        System.out.println("After swap:");
        System.out.println("x value: "+x);
        System.out.println("y value: "+y);

}

}

OUTPUT:
--------------
Before swap:
x value: 10
y value: 20
After swap:
x value: 20
y value: 10


2nd way:
========

package files;

public class SwappROGdEMO {
public static void main(String[] args) {
int x = 10;
        int y = 20;
        
        System.out.println("Before swap:");
        System.out.println("x value: "+x);
        System.out.println("y value: "+y);
        
        x = x*y;
        y = x/y;
        x = x/y;
        
        
        System.out.println("After swap:");
        System.out.println("x value: "+x);
        System.out.println("y value: "+y);
}
}

OUTPUT:
--------------
Before swap:
x value: 10
y value: 20
After swap:
x value: 20
y value: 10



No comments:

Post a Comment