# Thread: Fibonacci sequence using iterative and recursive method

1. Member
Join Date
Jan 2011
Posts
24
Rep Power
0

## 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:

Java 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];
}```

2. What does your code do instead? You might consider posting an SSCCE that we can run.

3. Take a look here for help with fibonacci numbers.

4. Member
Join Date
Jan 2011
Posts
24
Rep Power
0
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.....

5. 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.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•