Sunday, January 29, 2023

How to swap 2 Number without using 3rd variable Program in java with Explanation

Here are three different ways to swap two numbers without using a third variable in Java:

1) Using addition and subtraction:



Explanation: By adding a and b, we have the sum of both numbers stored in a. Then, we subtract b from a to get the original value of a stored in b. Finally, we subtract b from an again to get the original value of b stored in a.

2)Using XOR:


Explanation: The XOR operator ^ returns 1 if either of its operands is 1 but not both, and 0 if both operands are the same. By XORing a and b, we have the bitwise XOR of both numbers stored in a. Then, we XOR a and b again to get the original value of a stored in b. Finally, we XOR a and b one last time to get the original value of b stored in a.

3)Using a temporary variable:

Explanation: By using a temporary variable temp, we can store the original value of a before assigning the value of b to a. Then, we can assign the original value of a (stored in temp) to b, effectively swapping the values of a and b

0 comments:

If you have any doubts,please let me know