Using the switch statement, write a menu-driven program for the following: (i) To find and display the sum of the series given below: S = x^1 - x^2 + x^3 - x^4 + x^5 ... - x^20 (where x = 2) (ii) To display the following series: 1 11 111 1111 11111 For an incorrect choice, an appropriate error message should be displayed.
Topic: Menu-driven program — alternating series and pattern
Answer
import java.util.Scanner;
class MenuSeries { public static void main(String args[]) { Scanner sc = new Scanner(System.in);
System.out.println("1. Sum of the series"); System.out.println("2. Display the number series"); System.out.print("Enter your choice (1 or 2) : "); int ch = sc.nextInt();
switch(ch) { case 1: int x = 2; double sum = 0.0; for(int i = 1; i <= 20; i++) { if(i % 2 == 1) sum = sum + Math.pow(x, i); else sum = sum - Math.pow(x, i); } System.out.println("Sum of the series = " + sum); break;
case 2: int n = 0; for(int i = 1; i <= 5; i++) { n = n * 10 + 1; System.out.print(n + " "); } System.out.println(); break;
default: System.out.println("Invalid choice"); } } }
Two techniques in one question.
The alternating series: the signs go +, -, +, - ..., which means odd terms are added and even terms subtracted. Test i % 2 to decide. Handling alternating signs by an if on the term number is the standard method, and it is far clearer than multiplying by (-1) raised to a power. The sum is declared double because Math.pow() returns a double, and because 2^20 is over a million.
The number series is the elegant part: 1, 11, 111 ... is generated by n = n * 10 + 1, starting from 0. Each pass shifts the digits one place left and drops a new 1 into the units position. This is the same technique used to reverse a number, and it is worth recognising as a building block.
The question asks specifically for switch, so use it, and include the default branch — the error message carries marks.
ch int - the menu choice entered by the user x int - the base of the series, fixed at 2 i int - loop variable, the term number sum double - running total of the alternating series n int - the number being built up as 1, 11, 111 ... sc Scanner - object used to read input