Sunday, July 21, 2013

How to Swap Two Members Without using Temp Variable

package com.crunchify.tutorials;
 
/**
* @author Crunchify.com
*/
 
public class CrunchifySwapVariables {
 
    public static void main(String[] args) {
        int a = 20;
        int b = 30;
        int c = 3;
        int d = 4;
 
        CrunchifySwapVariables.SwapVairablesMethod1(a, b);
        CrunchifySwapVariables.SwapVairablesMethod2(c, d);
 
    }
 
    public static void SwapVairablesMethod1(int a, int b){
        System.out.println("value of a and b before swapping, a: " + a +" b: " + b);
 
        //swapping value of two numbers without using temp variable
        a = a + b; //now a is 50 and b is 20
        b = a - b; //now a is 50 but b is 20 (original value of a)
        a = a - b; //now a is 30 and b is 20, numbers are swapped
 
        System.out.println("Result Method1 => a: " + a +" b: " + b);
 
    }
 
    public static void SwapVairablesMethod2(int c, int d){
        System.out.println("\nvalue of c and d before swapping, c: " + c +" d: " + d);
 
        //swapping value of two numbers without using temp variable using multiplication and division
        c = c*d;
        d = c/d;
        c = c/d;
 
        System.out.println("Result Method2 => c: " + c +" d: " + d);
 
    }
}
 
 
Output:
1
2
3
4
5
value of a and b before swapping, a: 20 b: 30
Result Method1 => a: 30 b: 20
 
value of c and d before swapping, c: 3 d: 4
Result Method2 => c: 4 d: 3
 

No comments:

Post a Comment