This program explains about how you can  swap  values within a variable without using the third variable.


Step 1 : START

Step 2 : Declare two variables, say a,b.

Step 3 : Add a and b and store to a.

Step 4 : Subtract b from a and store to b.

Step 5 : Subtract b from a and store to a.

Step 6 : STOP.

Source code:


The user is asked to enter the value for two variables. Now, the trick for swapping two variable’s values without using the temporary variable is that

num1 = num1 + num2;

num2 = num1 – num2;

num1 = num1 – num2;

first variable is first added to the second variable and stored in first variable. Then the second variable is subtracted from first variable and stored in second variable. Lastly, the value of 2nd variable is subtracted from 1st and stored in first variable.



C:\Users\santo\Desktop\new>java Swaping

*** ***

<< JAVA program to swap two integers without using the third variable >>

Enter first number to swap:
Enter second number to swap:
Values before swap are num1 = 10 num2 = 9
Values After swap are num1 = 9 num2 = 10


Screenshot of output:

Screenshot of output