Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

# Thread: Fibonacci Sequence Code in Java

1. ## Fibonacci Sequence Code in Java

I am really struggling with recursive methods and was wondering if anyone could offer some guidance on this practice problem. Any help would be greatly appreciated.

Write a recursive method that calculates the Nth number in the Fibonacci sequence. The first and second numbers in the sequence (the base cases) are both 1. After that, each subsequent number is the sum of the previous two. Stated a bit more formally:

fib(n)={1fib(n−1)+fib(n−2)n<2otherwise

For example, here is the first few numbers in the sequence:

1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

Your fib method should be part of a class named Fibonacci. In addition to the fib method, the Fibonacci class should have a main method that calls fib(9). If the result doesn't equal 34, you should print an error message. Otherwise, it should print out a message saying that it was successful.

After writing your Fibonacci class, answer the following question: How many times is the fibonacci method called when calculating the 5th number in the sequence?

2. ## Re: Fibonacci Sequence Code in Java

Could you show us all of the codes you've written already and the errors/exceptions you discovered. This is so we don't spoon-feed you