InterviewSolution
Saved Bookmarks
| 1. |
Write a JAVA program to input two unequal numbers. Display the numbers after swapping their values in the variables without using a third variable. |
|
Answer» port 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 + bThen b = a - b= > b = a + b - b [ from above ]= > b = a then a = a - b= > a = a - ( a - b )= > a = a - a + b= > a = bThat is the way they are swapped ! |
|