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.