write a java program to print the following series
Answers
Series Summation in Java
We are given a series involving factorials. We must define a factorial function for it.
We would take user input for value of n and run a loop to add each term to a variable for sum.
Factorial of a number n means product of numbers from 1 till n.
E.g.: 4! = = 24
So for factorial function we would run a loop to multiply the numbers.
Here is the Java program:
import java.util.Scanner;
public class Series
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the value of n: ");
int n = sc.nextInt(); //Taking User Input
double sum = 0; //Initialising sum to 0
for(int i=1;i<=n;i++)
{
sum += 1/factorial(i); //Adding successive terms to sum
}
System.out.println("Series Sum = "+sum);
}
static double factorial(int n) //Factorial Function
{
int fact=1;
for(int i=2;i<=n;i++) //We multiply fact with i from 2 till n
{
fact = fact*i;
}
return fact; //Returning the factorial
}
}