0

I have to find sum of n fibonacci numbers. what I did is first created a method to find nth fibonacci number. Then what i included in that method is to find the sum recursively. Its like finding factorial of a number recursively but difference is I added the numbers instead of multiplying them. I created an array of n values which represents the fibonacci series. Here is my code:-

import java.util.*;

public class FibonacciSumLastDigit {
    private static int getFibonaccisum(int n) {
        int[] f = new int[n];
        f[0] = 0;
        f[1] = 1;
        for (int i = 2; i < f.length; i++) {
            f[i] = f[i - 1] + f[i - 2];
        }
        int a = f[n];
        return a;
    }


    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int s = getFibonaccisum(n);
        System.out.println(s);
    }
}

but my error is java.lang.arrayindexoutofboundsexception: index 10 out of bounds for length 10. Please someone help. Also sorry if I did not write the code understandably. I am new to stackoverflow.

  • 3
    `f` is an array of length `n`, so `int a = f[n];` is causing your Exception. Recall that Java arrays are 0-indexed, so the last index of an array of length `n` is `n-1`. – ajc2000 Jul 30 '20 at 14:32
  • Arrays are zero-indexed. `int a = f[n-1];` – Unmitigated Jul 30 '20 at 14:32
  • As pointed out in comments already, the error in your code arise from the conflict between these two lines: `int[] f = new int[n];` and `int a = f[n];`. Here, `f` is an array of `n` cells, the first one being `f[0]` and the last one `f[n-1]`. Trying to access `f[n]` will result in an error. However, finding the sum of fibonacci numbers is actually quite easy. See this duplicate question: https://stackoverflow.com/questions/4357223/finding-the-sum-of-fibonacci-numbers and this excellent discussion: http://mathforum.org/library/drmath/view/52707.html – Stef Jul 30 '20 at 14:41
  • btw, your implementation is not at all recursive. – A. Ocannaille Jul 30 '20 at 16:07
  • @hev1 thankyou so much – Nirzar Bhatt Aug 05 '20 at 15:31
  • @ajc2000 Thankyou so much – Nirzar Bhatt Aug 05 '20 at 15:32
  • @Stef thankyou so much – Nirzar Bhatt Aug 05 '20 at 15:33
  • @A._Ocannaille thankyou so much – Nirzar Bhatt Aug 05 '20 at 15:33

0 Answers0