Swapping 2 numbers without 3rd variable in JAVA

Description


Here actually, what we are doing is just swapping(interchanging) the 2 numbers, stored in 2 different variables(say a & b). Please keep in mind, here we are not using the third variable.

For Ex (O/P) : If the input is a=56 & b=25, then

The output should be a=25 & b=56.

The logic we are using here is, If the number is inputted a & b. Here we will use an if loop because the condition is different in different cases (i.e. a can be greater than b OR b can be greater than a).

LOGIC (loop) Example : First when a>b, then the value of a(say 56) & b(say 25) will be… a=a+b (a=56+25=81) then b=a-b (b=81-25=56) then a=a-b (a=81-56=25). So, at last a=25 & b= 56.

SOURCE CODE
OUTPUT

Author Description

humanz

Our mission is to bring the affordable Technology education to people everywhere, in order to help them achieve their dreams and change the world. - Follow @program_guide

No comments yet.

Join the Conversation