The Fibonacci Sequence
Below is an example of how to create the recursive version of the Fibonacci sequence. But first of all, what is it?
* This tutorial assumes you understand the following:
Fibonacci is a well known number sequence that models the growth of a rabbit population amongst other things found in nature.
Below is the Fibonacci numbers computed up to the 11th term.
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 |
| 0 | 1 | 1 | 2 | 3 | 5 | 8 | 13 | 21 | 34 | 55 | 89 |
Iterative version of Fibonacci
Before we create the recursive version of Fibonacci, let’s look at how to create the iterative version by looking at the formula.
Fibonacci Formula
Fibonacci(0) = 0;
Fibonacci(1) = 1;
Fibonacci(n) = Fibonacci(n-1) + Fibonacci(n-2);
So how would we do an iterative version? I’ll walk you through the code.
int fibonacci(int n) {
//Our two initial values
int fib1 = 0;
int fib2 = 1;
//Our running value
int fib = fib1;
// Computing the nth value of Fibonacci //
return fib;
So how would we compute the value of the nth value of the Fibonacci sequence? We can do it with a for loop, to add UP to the value we are looking for. In other words, if we were doing it by hand, we’d do it as following:
Read more »







