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
Solution
To swap two numbers without using a third variable in Java, you can follow these steps:
- Declare and initialize two variables, let's say
a
andb
, with the numbers you want to swap. - Print the original values of
a
andb
for reference. - Perform the swap using the following steps:
- Assign the sum of
a
andb
toa
. - Assign the difference between the new value of
a
and the original value ofb
tob
. - Assign the difference between the original value of
a
and the new value ofb
toa
.
- Assign the sum of
- Print the swapped values of
a
andb
.
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.
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.
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.