About Me

header ads

How to swap two numbers without using any variables


import java.io.*;
class Swapping_Method2
    {
        public static void main(String args[])throws IOException
        {
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            int a,b;
            System.out.print("Enter the 1st no: ");
            a=Integer.parseInt(br.readLine());
            System.out.print("Enter the 2nd no: ");
            b=Integer.parseInt(br.readLine());
            System.out.println("-------------------------------");
            System.out.println("The numbers before swapping are");
            System.out.println("a = "+a);
            System.out.println("b = "+b);
            //Beginning of Swapping
            a=a+b;
            b=a-b;
            a=a-b;
            //End of Swapping
            System.out.println("-------------------------------");
            System.out.println("The numbers after swapping are");
            System.out.println("a = "+a);
            System.out.println("b = "+b);
        }
    }

Output:


Enter the 1st no: 25
Enter the 2nd no: 13
——————————-
The numbers before swapping are
a = 25
b = 13
——————————-
The numbers after swapping are
a = 13
b = 25
Working:

Initially a=25 and b=13,
Step 1: a=a+b gives a=25+13
i.e. a=38
Step 2: b=a-b gives, b=38-13
i.e. b=25
Step 3: a=a-b gives, a=38-25
i.e. a=13

Post a Comment

0 Comments