Problem: Given two variables, a and b, exchange the values assigned to them.
Algorithm:
1.Get the values of a and b.
2.Save the original value of a to temporary variable.
3.Save the value of b in a.
4.Save the value of temporary variable in b.
5.Print the exchanged values of a and b.
Solution:
import java.util.Scanner;
public class ExchangeTwoValues {
static int a,b,t;
public static void main(String[] args) {
getTheValues();
System.out.println("Before exchange the values are " + a + " " + b);
exchangeValues();
System.out.println("After exchange the values are " + a + " " + b);
}
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();
}
private static void exchangeValues(){
t = a;
a = b;
b = t;
}
}
Output:
Enter the value of a:
3
Enter the value of b:
2
Before exchange the values are 3 2
After exchange the values are 2 3
No comments:
Post a Comment