programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Fibonacci numbers

Ranch Hand
Posts: 55
Hi all!
I need help again. Thanks to those who replied on my recursion question. But now I've got bigger fish to fry.
I have to write a nonrecursive method that computes Fibonacci numbers.
The person is suppose to input an index and the application is suppose to compute what Fibonacci number is at that index. The algorithm my text gives me is a follows:
public static long fib(long q) { //I've added this line

f0 = 0;
f1 = 1;

for (int r = 2; r <= q; r++) {
currentFib = f0 + f1;
f0 = f1;
f1 = currentFib;
I've got everything set up accept for the acutal formula to compute. I don't know if I should be using a return statement, if statement or what. I'm still unclear as to exactly how this calculation works. Can somebody please help I'm dying here!
Thanks
Stacey

Ranch Hand
Posts: 522
Stacey, welcome to the ranch.
Your question made me think, i haven't implement the fibonacci alg. since i graduated (2 years ago). it was a good question to get me back in shape.
My advice try to do it yourself, trust me on this. I am not trying to be rude here but it is for your own good. Incase you couldn't do it see this code.

Ranch Hand
Posts: 399
Hi Stacey ...
Your code is almost there; here is the completed method:

The code in bold represents my additions. As you can see, you were almost there: you just needed to declare the variable types and return the result (stored in "f1").
Inside the loop you are taking the sum of the two previous numbers (f0 and f1) and then re-assigning the value of the two previous numbers so you'll be ready for the next loop. The last sum calculated will end up in "f1", so that's what you should return.
There are several ways of composing the loop, but it's always best for you to do your own code so you understand how it works. It's the only way to learn.

 I've got no option but to sell you all for scientific experiments. Or a tiny ad: The WEB SERVICES and JAX-RS Course https://coderanch.com/t/690789/WEB-SERVICES-JAX-RS