Fibonacci sequence using iterative and recursive method
I am to produce the fibonacci sequence using one parameter, then two parameters. I am also supposed to do it with an iterative and recursive method, I know im close by using the general formula for fibonacci: f(x)=f(x-1)+f(x-2)
But im having trouble with the base case:
Code:
public class Lab21_7 {
public static void init(long[] arr) {
// Initialize all the entries of the array to 0
for (int i = 0; i < arr.length; i++) {
arr[i] = 0;
}
}
public static long fib(int max) {
// sumAll basic version
System.out.println("Called Fibonacci(" + max + ")");
long result;
if (max <= 1) //<----this part messes me up
result = 1;
else
result = fib(max-2)+fib(max-1);
System.out.println("Return Fibonacci(" + max + ") = " + result);
return result;
public static long fib(long[] arr, int max) {
// Simple Recursion with array
System.out.println("Called Fibonacci(" + max + ")");
if (max <= 1)
arr[max] = 1;
else if (arr[max] == 0)
arr[max] = fib(max-2) + fib( arr,max - 1);
System.out.println("Return Fibonacci(" + max + ") = " + arr[max]);
return arr[max];
}