wap to enter three numbers and exchange them with the fourth variable in java
No Scaming
Answers
The given code is written in Java.
import java.util.*;
public class SwapValues{
public static void main(String s[]){
int a,b,c,d;
Scanner sc=new Scanner(System.in);
System.out.print("Enter first number: ");
a=sc.nextInt();
System.out.print("Enter second number: ");
b=sc.nextInt();
System.out.print("Enter third number: ");
c=sc.nextInt();
sc.close();
System.out.println("\nBefore Swapping: ");
System.out.println("a = "+a);
System.out.println("b = "+b);
System.out.println("c = "+c);
d=a;
a=c;
c=b;
b=d;
System.out.println("\nAfter Swapping: ");
System.out.println("a = "+a);
System.out.println("b = "+b);
System.out.println("c = "+c);
}
}
- Here, we have to swap values of three variables a,b and c. After swapping, b stores the value of a, c stores the value of b and a stores the value of c.
- To solve this, we have to use fourth variable.
- At first, we have to store value of a in d so as to access it later.
- Now, a stores the value of c, c stores the value of b.
- Now, we have to store the value of a in b. But a is overwritten. So now, we will store the value of d in b. Hence, the values are swapped.
See the attachment for output.