Create a free account on Computer Sir Ki Class and unlock access to valuable learning resources.
Exam Paper Downloads: After registering and logging in, you can download exam question papers in PDF format to practice and prepare for your exams.
Student Support: Get assistance with your doubts, queries, and questions related to your studies. Our support is here to help you understand topics and resolve your learning difficulties.
Register today and make your exam preparation easier and more effective!
Using switch statement, write a menu driven program for the following:
(i) To find and display the sum of the series given below:
..=..1…2+..3…4+..5…………….. . ..20
(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.
Answer:
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
C. Sir| Created: 15-Apr-2019 | Updated: 15-Apr-2019|ICSE2017