Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Java program to find the sum of a series 1/1! + 2/2! + 3/3! + 4/4! +…….+ n/n!
In this program, we'll compute the sum of the series 1/1! + 2/2! + 3/3! + ... + n/n! using Java. This involves calculating factorials and summing the results of each term divided by its factorial. We'll use Java's basic arithmetic, loop control, and built-in classes to achieve this.
Problem Statement
Write a Java program to calculate the sum of the series 1/1! + 2/2! + 3/3! + ... + n/n! and print the result.
Steps to find the sum of a series
Following are the steps to find the sum of a series ?
- Import necessary classes from java.io and java.lang package.
- Initialize variables for the sum and factorial calculation.
- To iterate we will implement a for loop.
- We will update factorial_val to calculate the factorial of the current integer and then add the result of i / i! to the sum.
- After the loop, return the computed sum.
- Print the result.
Java program to find the sum of a series
Below is the Java program to find the sum of a series 1/1! + 2/2! + 3/3! + 4/4! +??.+ n/n ?
import java.io.*;
import java.lang.*;
public class Demo{
public static double pattern_sum(double val){
double residual = 0, factorial_val = 1;
for (int i = 1; i <= val; i++){
factorial_val = factorial_val * i;
residual = residual + (i / factorial_val);
}
return (residual);
}
public static void main(String[] args){
double val = 6;
System.out.println("The sum of the series is : " + pattern_sum(val));
}
}
Output
The sum of the series is : 2.7166666666666663
Code Explanation
A class named Demo contains a function named ?pattern_sum?. This function takes a double-valued number as a parameter, and iterates through the value and calculates the series value of (1/1! + 2/2! + ..) and so on. In the main function, the value is defined and the function ?pattern_sum? is called by passing this value. The output is displayed on the console.
