Write a Program to Swap Two Numbers without Third Variable Using in Java Programming
Swapping is the Method where one extra temporary variable used for swapping,But in Mathematical Way we Swap numbers.
Example A = 15 , B = 10
——————
A = A – B
A = 15 – 10 = 5
——————
B = B – A
B = 10 + 5 = 15
——————
A = B – A
A = 15 – 5 = 10
——————
A = 10,B = 15
Program :
public class Swapping_Example { public static void main(String[] args) { int number1 = 15; int number2 = 10; System.out.println("Before Swapping Number1: " + number1); System.out.println("Before Swapping Number2: " + number2); number1 = number1 - number2; number2 = number2 + number1; number1 = number2 - number1; System.out.println("---------------------------"); System.out.println("After Swapping Number1: " + number1); System.out.println("After Swapping Number2: " + number2); } }
(Visited 79 times, 1 visits today)
Written by: