Given two numbers, we have to swap the value of two numbers. Let A and B be the two input numbers, we have to interchange their values as follows:
Input A = 5, B = 2 Output A = 2, B = 5
Java program to swap two numbers without using third variable.
Algorithm to swap two numbers without using temporary variable
-
Let A and B be the numbers we want to swap.
- Add A and B and store the result in A(A = A + B).
- Subtract B from A and store the result in B(B = A - B).
- Subtract B from A again and store the result in A(A = A - B).
ALERT
The sum of the two integers may be more than the range of integer data type. In this case, you will get wrong result.
The sum of the two integers may be more than the range of integer data type. In this case, you will get wrong result.
package com.tcc.java.programs; import java.util.*; public class SwapTwoNumbers { public static void main(String args[]) { int A, B; Scanner in = new Scanner(System.in); System.out.println("Enter First Integer(A)"); A = in.nextInt(); System.out.println("Enter Second Integer(B)"); B = in.nextInt(); // Swapping A and B without using third variable A = A + B; B = A - B; A = A - B; System.out.println("After Swapping"); System.out.println("A = " + A + "\nB = " + B); } }Output
Enter First Integer(A) 4 Enter Second Integer(B) 6 After Swapping A = 6 B = 4
Java program to swap two variables using third temporary variable
In this program, we are using a temporary variable to avoid integer range overflow problem as described above.
package com.tcc.java.programs; import java.util.*; public class SwapTwoNumbersThirdVariable { public static void main(String args[]) { int A, B, temp; Scanner in = new Scanner(System.in); System.out.println("Enter First Integer(A)"); A = in.nextInt(); System.out.println("Enter Second Integer(B)"); B = in.nextInt(); // Swapping A and B using a temporary variable temp = A; A = B; B = temp; System.out.println("After Swapping"); System.out.println("A = " + A + "\nB = " + B); } }Output
Enter First Integer(A) 2 Enter Second Integer(B) 8 After Swapping A = 8 B = 2
Recommended Posts