Write a menu-driven program to perform the following (Use switch-case statement):
0, 3, 8, 15, 24 ... n terms (value of n is to be an input by the user).S = 1/2 + 3/4 + 5/6 + 7/8 ... 19/20
import java.io.*;
public class Menu {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int choice, n;
double s = 0;
System.out.println("Enter 1. To Print the Series");
System.out.println("Enter 2. To Print the Sum of Series");
System.out.println("Enter Your Choice");
choice = Integer.parseInt(br.readLine());
switch (choice) {
case 1:
System.out.println("Enter the number of terms:");
n = Integer.parseInt(br.readLine());
System.out.print("Series: ");
for (int i = 1; i <= n; i++) {
int term = i * i - 1;
System.out.print(term + " ");
}
System.out.println();
break;
case 2:
for (int i = 1; i <= 19; i += 2) {
s += (double) i / (i + 1);
}
System.out.println("Sum of series: " + s);
break;
default:
System.out.println("Wrong Choice");
break;
}
}
}
| Name | Type | Description |
|---|---|---|
| choice | int | Stores the user's choice from the menu options. |
| n | int | Stores the number of terms for the series in Task 1. |
| s | double | Accumulates the sum of the series fractions in Task 2. |
| i | int | Loop counter used in both series and sum calculations. |
| term | int | Temporary variable used to store the computed term in the series for Task 1. |
| br | BufferedReader | Reads input from the user. |
The program uses a menu-driven approach with a switch-case statement to perform two tasks based on user input.
The first option in the menu allows the user to print a series of numbers. The series is defined as 0, 3, 8, 15, 24, ... and the pattern is i * i - 1, where i is the term index. The user is prompted to enter the number of terms n, and the program then calculates each term using the formula and prints the series.
The second option calculates the sum of a series where each term is of the form i / (i + 1), for i ranging from 1 to 19 with an increment of 2. The sum is computed by iterating through the terms and adding them up. The result is then printed out.
BufferedReader class is used to read user input from the console.switch statement determines which task to execute based on the user's choice.for loop generates and prints each term.for loop calculates the sum of fractions.default case handles invalid choices by displaying an error message.First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.
After understanding this example, try to rewrite the same program without looking at the code. Then change some values or logic and run it again. This helps improve confidence and keeps learners engaged on the page for longer.