int fib(int n)We take in a number n, representing which Fibonacci number we want to calculate, and return the value of that number. Thus fib(6) would return 8. Let's look at two ways of writing this function:
// The iterative version
int fib(int n)
{
// Figure out the first two numbers
int fib1 = 1;
int fib2 = 1;
// If they asked for either of the first two numbers,
// we already know what the answer should be.
if (n <= 1) return 1;
// Otherwise, calculate
for (int i = 1; i < n; i++)
{
// Figure out the new number
int newNum = fib1 + fib2;
// Update
fib1 = fib2;
fib2 = newNum;
}
// Return the answer
return fib2;
}
Using the iterative approach, this is not too bad. There are a couple
of tricky bits here, like figuring to use a new variable when
calculating each new number in the series, and just how to do the
calculation, but overall it isn't too bad. Let us take a look at the
recursive solution.
// The recursive version
int fib(int n)
{
// If it is less than 2 then we know the initial case, return it
if (n <= 1) return 1;
// Otherwise, calculate the previous two and return the sum
return fib(n - 1) + fib(n - 2);
}
Admittedly, the recursive version is a little harder for some people
to understand. Still, it is a much more concise version that more
closely mimics the mathematical definition. Pretty neat, eh?© 2003 UC Riverside Department of Computer Science & Engineering. All rights reserved.