Knowee
Questions
Features
Study Tools

write a program in java to display the number after swapping without using third variable

Question

Write a program in Java to display the number after swapping without using third variable

🧐 Not the exact question you are looking for?Go ask a question

Solution

To swap two numbers without using a third variable in Java, you can follow these steps:

  1. Declare and initialize two variables, let's say a and b, with the numbers you want to swap.
  2. Print the original values of a and b for reference.
  3. Perform the swap using the following steps:
    • Assign the sum of a and b to a.
    • Assign the difference between the new value of a and the original value of b to b.
    • Assign the difference between the original value of a and the new value of b to a.
  4. Print the swapped values of a and b.

Here's the code that implements the above steps:

public class SwapNumbers {
    public static void main(String[] args) {
        int a = 10;
        int b = 20;

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

        // Swapping without using a third variable
        a = a + b;
        b = a - b;
        a = a - b;

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

When you run this program, it will display the numbers after swapping without using a third variable.

This problem has been solved

Similar Questions

Using pointers write a program to swap two numbers using a user definedfunction(Call by reference)

18. int value = 453;19. int d1 = value % 10;20. int d2 = (value / 10) % 10;21. int d3 = (value / 100) % 10;22. System.out.println("" + d1 + d2 + d3);23. }24. }

What needs to go into <condition> for the code to output:234for(int num = 2; <condition>; num++) { System.out.println(num);}num <= 4num > 4num < 4num == 4

Write a Python code snippet to swap the values of two variables without using a temporary variable

Create a program in Java that will accept two integers. If the sum of the integers is odd, display the higher integer, else, display the lower integer.

1/1

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.