Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Fibonacci Sequence program  RSS feed

 
Konrad Cetes
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Junilu Lacar
Sheriff
Posts: 11144
160
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Konrad Cetes
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Would i need to create multiple variables or just use one and add to it?
 
Junilu Lacar
Sheriff
Posts: 11144
160
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Programming is as much about experimentation as it is about problem solving. Try it out yourself. What's the worst that could happen?
 
Konrad Cetes
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
good point!
 
Junilu Lacar
Sheriff
Posts: 11144
160
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!