Monday, May 12, 2014

How to swap the two numbers without using 3rd variable.

import java.util.Scanner;

public class Swapping{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        System.out.println("enter 1st number a: ");
        int a = in.nextInt();
        System.out.println("enter 2nd number b: ");
        int b = in.nextInt();
       
        System.out.println("before swapping a="+a+" and b= "+b);
        a = a+b;
        b = a-b;
        a = a-b;
        System.out.println("after swapping a="+a+" and b= "+b);
    }
}

No comments:

Post a Comment