-3

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?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197

2 Answers2

2

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.

Michel K
  • 411
  • 1
  • 7
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;
}
Onyambu
  • 67,392
  • 3
  • 24
  • 53