A series is a mathematical expression that represents the sum of a set of terms. In Java, we can write a program to find the sum of a series like 1/1! + 2/2! + 3/3! + 4/4! +…….+ n/n!. To write this program, we will use a for loop to iterate through each term of the series and add the result to a total sum.
The first step in writing this program is to calculate the factorial of each number. A factorial is the product of all positive integers up to that number. For example, the factorial of 4 is 4! = 4 x 3 x 2 x 1 = 24. To calculate the factorial in Java, we can write a separate method that takes an integer input and returns the factorial value. This method can be called inside the for loop to calculate the factorial of each term.
Next, we need to calculate the numerator and denominator of each term. The numerator is simply the current iteration of the loop, while the denominator is the factorial of that number. To calculate the fraction of each term, we can divide the numerator by the denominator.
Finally, we need to add the result of each term to a total sum. This can be done by initializing a variable to 0 and adding the result of each term to that variable.
Here is the complete Java code to find the sum of the series 1/1! + 2/2! + 3/3! + 4/4! +…….+ n/n!:
public static void main(String[] args) { int n = 5; double sum = 0; for (int i = 1; i <= n; i++) { sum += (double) i / factorial(i); } System.out.println("The sum of the series 1/1! + 2/2! + 3/3! + 4/4! +…….+ " + n + "/" + n + "! is " + sum); } public static int factorial(int num) { int result = 1; for (int i = 1; i <= num; i++) { result *= i; } return result; }
The output of this program is:
The sum of the series 1/1! + 2/2! + 3/3! + 4/4! +…….+ 5/5! is 2.283333333333333
we can find the sum of a series in Java by using a for loop, a factorial method, and a variable to keep track of the total sum.
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.