Write a JAVA program to input two unequal numbers. Display the numbers after swapping their values in the variables without using a third variable.
Answers
CODE:
import java.util.*;
class Swapping
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter 2 numbers");
int a=sc.nextInt();
int b=sc.nextInt();
a=a+b;
b=a-b;
a=a-b;
System.out.println("Swapped value of a :"+b);
System.out.println("Swapped value of b :"+a);
}
}
LOGIC:
First note the step :
a = a + b
Then b = a - b
= > b = a + b - b [ from above ]
= > b = a
then a = a - b
= > a = a - ( a - b )
= > a = a - a + b
= > a = b
That is the way they are swapped !
package com.company;
/* Write a program to input two unequal numbers. Display the numbers after swapping their values in the variables without using a third variable.
Sample Input: a=23, b=56
Sample Output: a=56, b=23
*/
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println("Enter Number a:");
int a = sc.nextInt();
System.out.println("Enter Number b:");
int b = sc.nextInt();
if (a!=b){
a = a+b;
b = a-b;
a = a-b;
}
System.out.println("a = "+a+" b = "+b);
}
}