Swap two number without using third variable

Write a program to swap two numbers without using a third variable.

Example:

Input:  x=20, y=30
Output: x=30, y=20

Approach

Java


import java.util.regex.*;

public class Main {
    public static void main(String[] args) {
        int x = 20, y = 30;
        
        //using + and -
        System.out.println("before swap x="+x+"  and y="+y);
        x = x + y
        y = x - y
        x = x - y;
        System.out.println("after swap x="+x+"  and y="+y);
        
        //using * and /
        System.out.println("before swap x="+x+"  and y="+y);
        x = x * y
        y = x / y
        x = x / y;
        System.out.println("after swap x="+x+"  and y="+y);
        
        
    }
}


No comments:

Post a Comment