# Fibonacci sequence using iterative and recursive method

• 03-01-2011, 08:11 PM
baumboards
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];     }```
• 03-01-2011, 08:38 PM
KevinWorkman
What does your code do instead? You might consider posting an SSCCE that we can run.
• 03-01-2011, 08:47 PM
Shoss
Take a look here for help with fibonacci numbers.
• 03-02-2011, 06:25 AM
baumboards
My current code prints out the incorrect fibonacci sequence, I implemented the fibonacci code from the wikipedia website and it returned the correct sequence, except there were gaps in the sequence. i.e. 1,1,2,3,5,0,0,8.....
• 03-02-2011, 02:32 PM
KevinWorkman
Like I said, you might want to post an SSCCE that shows us what you're actually doing. We can't see how you're calling these methods to produce that output, so we can't really guess at what your problem is.
• 03-02-2011, 07:57 PM
Fubarable
Hijack post deleted. Poster warned not to hijack in another's thread to start their own thread.