Home Java Programming Language / Programs / Using switch statement, write a menu driven program for the following: To find and display the sum of the series given below:S = x1 - x2 + x3 - x4 + x5 .......... - x20(where x = 2) To display the following series:1 11 111 1111 11111 For an incorrect option, an appropriate error message should be displayed.
🚀 Programming Example

Using switch statement, write a menu driven program for the following:

  1. To find and display the sum of the series given below:
    S = x1 - x2 + x3 - x4 + x5 .......... - x20
    (where x = 2)
  2. To display the following series:
    1 11 111 1111 11111

For an incorrect option, an appropriate error message should be displayed.

👁 164 Views
💻 Practical Program
📘 Step Learning
Learn this program step-by-step with algorithm, source code, output and detailed explanation.

📌 Information & Algorithm

Given Input:


Expected Output:


💻 Program Code

import java.util.Scanner;

public class RAnsariSeriesMenu
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.println("1. Sum of the series");
        System.out.println("2. Display series");
        System.out.print("Enter your choice: ");
        int choice = in.nextInt();

        switch (choice) {
            case 1:
            int sum = 0;
            for (int i = 1; i <= 20; i++) {
                int x = 2;
                int term = (int)Math.pow(x, i);
                if (i % 2 == 0)
                    sum -= term;
                else
                    sum += term;
            }
            System.out.println("Sum=" + sum);
            break;

            case 2:
            int term = 1;
            for (int i = 1; i <= 5; i++) {
                System.out.print(term + " ");
                term = term * 10 + 1;
            }
            break;

            default:
            System.out.println("Incorrect Choice");
            break;
        }
    }
}
                        

🖥 Program Output

1. Sum of the series
2. Display series
Enter your choice: 1
Sum=-699050
Press any key to continue . . .


1. Sum of the series
2. Display series
Enter your choice: 2
1 11 111 1111 11111 Press any key to continue . . .
                            
📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.