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 Sequence program

Greenhorn
Posts: 28
I'm trying to make a program that output the first 20 numbers of the fibonacci sequence. Any ideas on how to create loop for this and what variables to assign.
The basic the formula is:
A=1
B=1
C=A+B=1+1=2

Sheriff
Posts: 11629
187
Walk through it and see what the pattern is. This type of problem relies on you seeing a pattern repeating itself. The thing that repeats is what you put inside a loop. Since you are asked to do the first 20 numbers, it's won't take long for you to actually list it out. Continue this:

F(1) -> 1
F(2) -> 1
F(3) -> F(1) + F(2) -> 1 + 1 -> 2
F(4) -> F(2) + F(3) -> 1 + 2 -> 3
F(5) -> F(3) + F(4) -> 2 + 3 -> 5
F(6) -> ...

By the time you add a few more lines, you should be seeing a definite pattern emerge.

Greenhorn
Posts: 28
Would i need to create multiple variables or just use one and add to it?

Junilu Lacar
Sheriff
Posts: 11629
187
• 1
Programming is as much about experimentation as it is about problem solving. Try it out yourself. What's the worst that could happen?

Greenhorn
Posts: 28
good point!

Junilu Lacar
Sheriff
Posts: 11629
187
When you see a pattern, try to generalize the formula.

F(N) -> F(?) + F(?) -> ...

When you figure out what to use in place of those two question marks, you'll have an idea of how many variables you need.

 It will give me the powers of the gods. Not bad for a tiny ad: The WEB SERVICES and JAX-RS Course https://coderanch.com/t/690789/WEB-SERVICES-JAX-RS