by Dinesh Thakur Category: Control Structures

 Algorithm for Swap Variables in a Different Way:

step 1: Read a, b

step 2: a=(a+b)-(b=a)

step 3: Print a,b

step 4: Exit

Here is the Java Example for Swap Variables in a Different Way:

import java.util.Scanner;

public class SwapDifferentWay
{
            public static void main(String args[])
       {
            Scanner s=new Scanner(System.in);
            int a,b;
            System.out.println("Enter Two Numbers");
                 a=s.nextInt();
                 b=s.nextInt();
            System.out.println("Before Swap");
            System.out.println("value of a is "+a+" value of b is "+b);
                 a=(a+b)-(b=a);
           System.out.println("After swap") ;
           System.out.println("value of a is "+a+" value of b is "+b);
       }
}

Swap the Values of Two Variables in a Different Way Without Using Third Variables

About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.



Search Content







Popular Article