Using switch statement, write a menu driven program for the following:
(i) To find and display the sum of the series given below:
S = x1 – x2 + x3 – x4 + x5 … – x20, where x = 2.
(where x = 2)
(ii) To display the following series:
1 11 111 1111 11111
For an incorrect option, an appropriate error message should be displayed.
Solution
TC++ #7260
import java.util.Scanner;
public class Menu {
public static void main(String[] args) {
System.out.println("1. Sum of series");
System.out.println("2. Display Series");
System.out.print("Enter your choice: ");
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
switch (choice) {
case 1:
double sum = 0;
for (int i = 1; i <= 20; i++) {
if (i % 2 == 1) {
sum = sum + Math.pow(2, i);
} else {
sum = sum - Math.pow(2, i);
}
}
System.out.println("Sum = " + sum);
break;
case 2:
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("1");
}
System.out.print(" ");
}
break;
default:
System.out.println("Invalid choice");
break;
}
}
}
Sample Output
1. Sum of series
2. Display Series
Enter your choice: 1
Sum = -699050.0