Question 5
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......... upto n terms
2. S=1/1!-2/2!+3/3!.......upto 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 x 2 x 3 x 4 x 5.
(use switch-case).
[15
Answers
refer above attachment
Series Sum - Java
We start by displaying the menu and taking the user input through Scanner class.
Then, we choose the corresponding block of code to execute with the switch-case structure.
Series 1
Clearly, the term is and we have to sum through it from i = 1 to i = n.
Series 2
Here, the term is .
We also create a function to return the value of .
It is a recursive function which works on the following basis:
So, the factorial function looks like:
If it feels too complex, just simply run a loop from 1 to n and return the product as follows:
static int factorial(int n) {
int product = 1;
for(int i = 1; i <= n; i++) {
product = product * i;
}
return product;
}
Now, we come to the actual code.
SeriesSum.java
import java.util.Scanner;
public class SeriesSum {
static int factorial(int n) { //Factorial Function
//This is a recursive function
//Return n * (n-1) * (n-2) * ... * 1
// n! = n * (n-1)!
// with end condition as 1! = 1
if(n == 1) {
return 1;
}
else {
return n*factorial(n-1);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//Menu
System.out.println("---Series Sum Menu---");
System.out.println("1. S = 1/4 + 1/8 + 1/12... upto n terms");
System.out.println("2. S = 1/1! - 2/2! + 3/3!... upto n terms");
//Take user input of choice
System.out.print("\nEnter 1 or 2: ");
String choice = sc.next();
int n; //Number of terms
double Sum = 0; //Initialize Sum to 0
switch(choice) {
case "1":
System.out.print("Enter value of n: ");
n = sc.nextInt();
for(double i = 1; i <= n; i++) {
Sum += 1 / (4*i);
}
System.out.println("Sum = "+Sum);
break;
case "2":
System.out.print("Enter value of n: ");
n = sc.nextInt();
Sum = 0;
for(int i = 1; i <= n; i++) {
Sum += Math.pow(-1, i+1) * (i / (double)factorial(i));
}
System.out.println("Sum = "+Sum);
break;
default:
System.out.println("Invalid choice");
}
}
}