Swap value of two numbers with using third variable.

Write a java program to swap value of two numbers with help of third variable.

import java.util.*;
public class swap1 
{
    public static void main(String args[])
    {
        Scanner s=new Scanner(System.in);
        int t,a,b;
        System.out.println("enter a");
        a=s.nextInt();
        System.out.println("enter b");
        b=s.nextInt();
        System.out.println("a before swap"+a);
        System.out.println("b before swap"+b);
        /*t=a;
        a=b;
        b=t;*/
        //or
        t=a+b;
        b=t-b;
        a=t-b;
        System.out.println("a after swap"+a);
        System.out.println("b after swap"+b);
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *