Lesson goal: Computing the Fibonacci Sequence of Numbers

Previous: Is a number prime? | Home | Next: The Factorial

Fibonacci numbers are a sequence of numbers that are made by taking 0 and 1, and adding them together to get 1, so you have 0, 1, and 1. Then,take the 1 and 1, and add them together to get 2, so you now have 0, 1, 1, and 2. Next add the 2 and 1 to get 3, giving you 0, 1, 1, 2, and 3.

Using concise mathematical notation, if $F_n$ is the $n^{th}$ Fibonacci number, given that $F_0=0$ and $F_1=1$, then $F_n=F_{n-1}+F_{n-2}$.

This sequence is a good lesson-base for writing a function, so let's do that here.

Let's write a function that will print the sequence of Fibonacci numbers. We'll call the function fib(n), where n is a number we pass the function, telling it how many Fibonacci numbers we want it to print. So we'd call it by programming fib(10) to see the first 10 Fibonacci numbers (past the initial 0 and 1, etc.).

Now you try. Fix the first =, second = and next = lines according to the description of the Fibonacci sequence described above.

Type your code here:

See your results here:

This code will not run! Given that the first two Fibonacci numbers are 0 and 1, what do you think you should put in the first = and second = lines? After this, the next Fibonacci number is 3, which is the sum of first and second. So, what should you put in for the next = line?

Your code is working with it displays this sequence of numbers: 0, 1, 2, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144 ...

Not the logic: the old second number becomes the new first number. And the current number becomes the new second number, so the next time through the loop, the next number can be found buy adding the first and second once again. Dismiss.

Show a friend, family member, or teacher what you've done!

Here is a share link to your code:

Does your code work? Want to run it on your iPhone?

Here's your code:

  1. Use [Control]-[C] (Windows) or [⌘]-[C] (MacOS) to copy your code.

  2. Paste it using [Control]-[V] (Windows) or [⌘]-[V] (MacOS) into this page

  3. Then click the "Use on iPhone" button that you'll see.