Problem:
Exchange the values of four variables as follows:
1. Exchange the value of b to a
2. Exchange the value of c to b
3. Exchange the value of d to c
4. Exchange the value of a to d.
Algorithm:
1. Get the values of a,b,c and d.
2. Assign the value of a to temporary variable.
3. Assign the value of b to a.
4. Assign the value of c to b.
5. Assign the value of d to c.
6. Assign the value of temporary variable to d.
Solution:
public class ExchangeFourValuesInReverseOrder {
static int a,b,c,d,t;
public static void main(String[] args) {
getTheValues();
System.out.println("Before exchange the values are " + a + " " + b + " " + c + " " + d);
exchangeValues();
System.out.println("After exchange the values are " + a + " " + b + " " + c + " " + d);
}
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();
System.out.println("Enter the value of d: ");
d = s.nextInt();
}
private static void exchangeValues(){
t = a;
a = b;
b = c;
c = d;
d = t;
}
}
output:
Enter the value of a:
3
Enter the value of b:
30
Enter the value of c:
300
Enter the value of d:
3000
Before exchange the values are 3 30 300 3000
After exchange the values are 30 300 3000 3
Exchange the values of four variables as follows:
1. Exchange the value of b to a
2. Exchange the value of c to b
3. Exchange the value of d to c
4. Exchange the value of a to d.
Algorithm:
1. Get the values of a,b,c and d.
2. Assign the value of a to temporary variable.
3. Assign the value of b to a.
4. Assign the value of c to b.
5. Assign the value of d to c.
6. Assign the value of temporary variable to d.
Solution:
public class ExchangeFourValuesInReverseOrder {
static int a,b,c,d,t;
public static void main(String[] args) {
getTheValues();
System.out.println("Before exchange the values are " + a + " " + b + " " + c + " " + d);
exchangeValues();
System.out.println("After exchange the values are " + a + " " + b + " " + c + " " + d);
}
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();
System.out.println("Enter the value of d: ");
d = s.nextInt();
}
private static void exchangeValues(){
t = a;
a = b;
b = c;
c = d;
d = t;
}
}
output:
Enter the value of a:
3
Enter the value of b:
30
Enter the value of c:
300
Enter the value of d:
3000
Before exchange the values are 3 30 300 3000
After exchange the values are 30 300 3000 3
Good post and its useful for coding
ReplyDeleteThanks Mr. Sarma
Delete