Problem:
Exchange the values of a, b and c as follows:
import java.util.Scanner;
public class ExchangeThreeValues {
static int a,b,c,t;
public static void main(String[] args) {
getTheValues();
System.out.println("Before exchange the values are " + a + " " + b + " " + c);
exchangeValues();
System.out.println("After exchange the values are " + a + " " + b + " " + c);
}
private static void getTheValues(){
Scanner s = new Scanner(System.in);
System.out.println("Enter the value of a: ");
a = s.nextInt();
System.out.println("Enter the value of b: ");
b = s.nextInt();
System.out.println("Enter the value of c: ");
c = s.nextInt();
}
private static void exchangeValues(){
t = b;
b = a;
a = c;
c = t;
}
output:
Enter the value of a:
3
Enter the value of b:
30
Enter the value of c:
300
Before exchange the values are 3 30 300
After exchange the values are 300 3 30
Exchange the values of a, b and c as follows:
- Exchange the value of a to b.
- Exchange the value of b to c.
- Exchange the value of c to a.
- Get the values of a, b and c.
- Assign the value of b to temporary variable
- Assign the value of a to b.
- Assign the value of c to a.
- Assign the value of temporary variable to c.
- Print the result
import java.util.Scanner;
public class ExchangeThreeValues {
static int a,b,c,t;
public static void main(String[] args) {
getTheValues();
System.out.println("Before exchange the values are " + a + " " + b + " " + c);
exchangeValues();
System.out.println("After exchange the values are " + a + " " + b + " " + c);
}
private static void getTheValues(){
Scanner s = new Scanner(System.in);
System.out.println("Enter the value of a: ");
a = s.nextInt();
System.out.println("Enter the value of b: ");
b = s.nextInt();
System.out.println("Enter the value of c: ");
c = s.nextInt();
}
private static void exchangeValues(){
t = b;
b = a;
a = c;
c = t;
}
output:
Enter the value of a:
3
Enter the value of b:
30
Enter the value of c:
300
Before exchange the values are 3 30 300
After exchange the values are 300 3 30
No comments:
Post a Comment