C Programs Tutorials | IT Developer
IT Developer

Java Programs



Share with a Friend

Menu Driven Program - Series Program - Java Programs

 

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)

(ii) To display the following series:


1 11 111 1111 11111

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

import java.util.Scanner; class Menu{ public static void main(String[] args){ Scanner in = new Scanner(System.in); System.out.println("1. S = x^1 - x^2 + x^3 ... - x^20"); System.out.println("2. 1 11 111 1111 11111"); System.out.print("Enter your choice: "); int choice = Integer.parseInt(in.nextLine()); switch(choice){ case 1: int x = 2; double sum = 0.0; for(int i = 1; i <= 20; i++){ if(i % 2 == 1) sum += Math.pow(x, i); else sum -= Math.pow(x, i); } System.out.println("Sum = " + 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!"); } } }

Output

 
 OUTPUT 1: 
1. S = x^1 - x^2 + x^3 ... - x^20
2. 1 11 111 1111 11111
Enter your choice: 1
Sum = -699050.0 

 OUTPUT 2: 
1. S = x^1 - x^2 + x^3 ... - x^20
2. 1 11 111 1111 11111
Enter your choice: 2
1 11 111 1111 11111