Wednesday, May 28, 2014

Swapping Numbers without using 3rd variable

import java.util.Scanner;

public class Swapping{
    public static void main(String[] args){
        Scanner in = new Scanner(;
        System.out.println("Enter the 1st number: ");
        int x = in.nextInt();
        System.out.println("Enter the 2nd number: ");
        int y = in.nextInt();
        System.out.println("Initial value of x: "+x+" and y: "+y);

        x = x+y;
        y = x-y;
        x = x-y;

        System.out.println("After swapping value of x: "+x+" and y: "+y);


Enter the 1st number:
Enter the 2nd number:
Initial value of x: 43 and y: 56
After swapping value of x: 56 and y: 43

No comments:

Post a Comment