How to swap two number without using third number in java
import java.util.*;
public class SwapNumber
{
public static void main(String args[])
{
int a,b;
Scanner sc=new Scanner(System.in);
System.out.println("Enter any two Number..");
a=sc.nextInt();
b=sc.nextInt();
a=a+b;
b=a-b;
a=a-b;
System.out.println("A="+a+",B="+b);
}
}
output:
Enter any two number..
5
10
A=10, B=5
Explain..
here we are add both number first
a=a+b=5+10=15 then
b=a-5=15-5=5 then
a=a-b=15-5=10
so finally...
A=10, B=5.
import java.util.*;
public class SwapNumber
{
public static void main(String args[])
{
int a,b;
Scanner sc=new Scanner(System.in);
System.out.println("Enter any two Number..");
a=sc.nextInt();
b=sc.nextInt();
a=a+b;
b=a-b;
a=a-b;
System.out.println("A="+a+",B="+b);
}
}
output:
Enter any two number..
5
10
A=10, B=5
Explain..
here we are add both number first
a=a+b=5+10=15 then
b=a-5=15-5=5 then
a=a-b=15-5=10
so finally...
A=10, B=5.
No comments:
Post a Comment