Write a program swapping without temporary (third variable) variable ?

This java program swaps two numbers without using extra variable code below.


								
import java.util.Scanner;

/**
 *
 * @author Mindclues
 */

public class SwapNumbersWithoutThirdVariable {
	{
		      int a, b;
		      System.out.println("Enter a and b");
		      Scanner in = new Scanner(System.in);
		 
		      a = in.nextInt();
		      b = in.nextInt();
		 
		      System.out.println("Before Swapping\na = "+a+"\nb = "+b);
		 
		      a = a + b;
		      b = a - b;
		      a = a - b;
		 
		      System.out.println("After Swapping\na = "+a+"\nb = "+b);
		   }
		}
							

								
Enter two numbers a and b :
5
3
Before Swapping numbers value : 
a = 5
b = 3
After Swapping numbers value : 
a = 3
b = 5

							

Related Articles

post a comment