How to Swap Two numbers without using third variable ?
Previous | Home | Next |
In this program we are swapping two numbers .
Here we are swapping two numbers without using third variable.
a=a+b; assign the sum of value of two variable to the first one
b=a-b; to get the swap value of second variable subtract the value of second variable from the new value of first variable.
a=a-b; to get the swap value of first variable subtract the value of swap new value of b from the new value of a.
Here we take two variable a, b .
first we define the variables a , b and assign value to them as 25 and 30 respectively.
After that we print the numbers before the swapping .
Then assign the sum of the two variables to the first number.
As a= a+b (i.e.25+30=55)
then subtract the value of second variable from the first. to get new swap second variable value.
variable a is now 55 i.e 55-30=25 so the second variable b is 25 now.
to get the value of variable a . a=a-b i.e 55-25=30;
package R4R soft tech;
public class Swap {
public static void main(String[] args) {
int a =25;
int b = 30;
System.out.println("Numbers before swapping are:");
System.out.println("The first number before swapping is: " +a );
System.out.println("The second number before swapping is: " + b);
a = a + b ;
b = a - b ;
a = a- b ;
System.out.println(" Numbers after swapping are:");
System.out.println("The first number after swaping is: "+ a);
System.out.println("The second number after swapping is: " + b);
}
Numbers before swapping are :
The first number before swapping is 25.
The second number before swapping is 30.
Numbers after swapping are:
The first number after swapping is 30
The second number after swapping is 25.
Previous | Home | Next |