'WAP to compute the sum of the first n terms of the following series [duplicate]
S = 1 + 1/2! + 1/3! + 1/4!.....
Here is my code:
import java.util.Scanner;
public class question{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n =sc.nextInt();
int[] fact= new int[n];
fact[0] =fact[1] =1;
for(int i=2;i<=n;i++)
{
fact[i]= fact[i-1]*i;
}
double sum=0;
for(int i=1;i<=n;i++){
sum+=1/fact[i];
}
System.out.println(sum);
}
}
This code is giving error
input:3
Exception in thread "main" java.lang.ArrayIndexOutOfBoindsException: Index 33 out of bounds for length 3 at question.main(question.java.12)
What is the reason for this error? How to resolve it?
Solution 1:[1]
The array is one element too small, it should be
int[] fact = new int[n+1];
Also note that sum+=1/fact[i] will be an integer division. You can use
sum += 1.0/ fact[i]
to get a floating point division.
Solution 2:[2]
Also you do not need to store the factorials in an array as the purpose is just to sum. You could do the following:
int fact = 1;
double sum = 0;
int n = 15;
for(int i = 1; i<=n; i++){
sum += 1.0/fact;
fact *= i;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Michel K |
| Solution 2 | onyambu |
