C Programs Tutorials | IT Developer
IT Developer

Java Programs



Share with a Friend

Menu driven - Sum of Series Program - Java Programs

Write a menu-driven program to find the sum of the following series depending on the user choosing 1 or 2:
1. s = 1/4 + 1/8 + 1/12 + … up to N terms.
2. s = 1/1! – 2/2! + 3/3! – … up to N terms.

where ! stands for factorial of the number and the factorial value of a number is the product of all integers from 1 to that number, e.g. 5! = 1 × 2 × 3 × 4 × 5 = 120. Use switch-case.

import java.io.*; class Menu{ public static void main(String args[])throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("1. 1/4 + 1/8 + 1/12 + ... N terms"); System.out.println("2. 1/1! - 2/2! + 3/3! - ... N terms"); System.out.print("Enter your choice: "); int choice = Integer.parseInt(br.readLine()); switch(choice){ case 1: System.out.print("N = "); int n = Integer.parseInt(br.readLine()); double sum = 0.0; for(int i = 1; i <= n; i++) sum += 1.0 / (4 * i); System.out.println("Sum = " + sum); break; case 2: System.out.print("N = "); n = Integer.parseInt(br.readLine()); sum = 0.0; int sign = 1; for(int i = 1; i <= n; i++){ int f = 1; for(int j = 1; j <= i; j++) f *= j; sum += sign * (double)i / f; if(sign == 1) sign = -1; else sign = 1; } System.out.println("Sum = " + sum); break; default: System.out.println("Invalid choice!"); } } }

Output

 
 OUTPUT 1: 
1. 1/4 + 1/8 + 1/12 + ... N terms
2. 1/1! - 2/2! + 3/3! - ... N terms
Enter your choice: 1
N = 10
Sum = 0.7322420634920634 

 OUTPUT 2: 
1. 1/4 + 1/8 + 1/12 + ... N terms
2. 1/1! - 2/2! + 3/3! - ... N terms
Enter your choice: 2
N = 10
Sum = 0.3678791887125221