Java program to swap two variables without using third variable
This program explains about how you can swap values within a variable without using the third variable.
Algorithm:
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import java.util.Scanner; class Swaping { public static void main(String args[]) { System.out.println("\n \n *** www.programmingposts.com *** \n \n"); System.out.println("<< JAVA Program to Swap Two Integers >> \n \n"); Scanner scanner = new Scanner(System.in); System.out.println("Enter first number to swap:"); int num1 = scanner.nextInt(); System.out.println("Enter second number to swap:"); int num2 = scanner.nextInt(); System.out.println("Values before swap are num1 = " + num1 + " num2 = " +num2); num1 = num1 + num2; num2 = num1 - num2; num1 = num1 - num2; System.out.println("Values After swap are num1 = " + num1 + " num2 = " +num2); } } |
Explanation:
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.
Output:
C:\Users\santo\Desktop\new>javac Swaping.java
C:\Users\santo\Desktop\new>java Swaping
*** www.programmingposts.com ***
<< JAVA program to swap two integers without using the third variable >>
Enter first number to swap:
10
Enter second number to swap:
9
Values before swap are num1 = 10 num2 = 9
Values After swap are num1 = 9 num2 = 10