WAP to take 2 numbers as input and interchange the values.
Eg:if a=3,b=2 Output will be a=2,b=3 ( JAVA PROGRAMMING ) pls help me out !
Answers
Required Answer:-
Question:
- Write a program in Java to take 2 numbers as input and interchange their values.
Solution:
Here is the code.
import java.util.*;
public class Swap {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int a, b, c;
System.out.print("Enter a: ");
a=sc.nextInt();
System.out.print("Enter b: ");
b=sc.nextInt();
System.out.println("Before Swapping, ");
System.out.println("a: "+a);
System.out.println("b: "+b);
c=a;
a=b;
b=c;
System.out.println("After Swapping, ");
System.out.println("a: "+a);
System.out.println("b: "+b);
sc.close();
}
}
Explanation:
Interchanging values means to interchange values of two variables. For example, if a = 2 and b = 3, after interchanging, it will be a = 3 and b = 2 i.e., their values gets swapped.
Logic to interchange.
The values of the variables can be interchanged easily if we use a third variable.
If we do this,
a = b;
b = a;
Then the code will not work.
Consider a = 2 and b = 3
a = b = 3
a becomes 3
b = a = 3
b becomes 3 because a is 3.
So, to interchange, we will use another variable named c which stores the value of a.
If we do this,
c = a;
a = b;
b = c;
Then c becomes 2 first (a = 2)
a becomes 3 (as b = 3)
b becomes 2 as c is 2.
In this way, we can swap two values.
Output is attached.
Code:
import java.util.Scanner;
public class SwapNumbers {
public static void main(String[ ] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter two numbers - ");
int numOne = sc.nextInt( ),
numTwo = sc.nextInt( );
System.out.printf("Before Swapping - \n" +
" a - %d\n" +
" b - %d\n", numOne, numTwo);
// Swapping the numbers
int temp = numOne;
numOne = numTwo;
numTwo = temp;
System.out.printf("After Swapping - \n" +
" a - %d\n" +
" b - %d\n", numOne, numTwo);
}
}
Sample I/O:
Enter two numbers -
12 21
Before Swapping -
a - 12
b - 21
After Swapping -
a - 21
b - 12