How to swap two number with out using third variable

 You can swap two numbers in Java without using a third variable by using arithmetic operations like addition and subtraction. Here's a description of how to do it and a conclusion:


Description:

1. Initialize two variables, say `a` and `b`, with the numbers you want to swap.

2. Use addition and subtraction to perform the swap:

   - Assign the sum of `a` and `b` to `a` (a = a + b).

   - Subtract the original value of `b` (which is now stored in `a`) from the sum to get the original value of `a` and assign it to `b` (b = a - b).

   - Finally, subtract the original value of `b` (now in `a`) from `b` to get the original value of `b` and assign it to `a` (a = a - b).


Here's a Java code example for swapping two numbers without a third variable:


```java

public class SwapNumbers {

    public static void main(String[] args) {

        int a = 5;

        int b = 10;


        System.out.println("Before swapping: a = " + a + ", b = " + b);


        a = a + b;

        b = a - b;

        a = a - b;


        System.out.println("After swapping: a = " + a + ", b = " + b);

    }

}

```


Conclusion:

This technique allows you to swap two numbers without the need for a third variable. It leverages basic arithmetic operations to achieve the swap, making the code concise and efficient. However, be cautious when using this method with large numbers, as it may lead to integer overflow if the sum of `a` and `b` exceeds the maximum value an integer can hold.

 

Thanks for being here 

Happy Coding 😁

No comments:

Post a Comment