How to Code an Iterative Fibonacci Sequence

A Fibonacci Sequence is a sequence of numbers in which the first and second numbers in the sequence are 0 and 1 respectively, and additional numbers in the sequence are calculated by adding the previous two.

The first few numbers in the Fibonacci Sequence look like this:
0, 1, 1, 2, 3, 5, 8, 13, 21...

Often in technical interviews a person will be asked to “create a function that returns the nth value in a Fibonacci Sequence”. This can be done in a few simple steps as shown in the example below.

1. Create variables to hold the current values of the last two numbers. The first and second numbers in the sequence will always be 0 and 1 respectively. In this example we are assuming that n=0 represents the first number in the series. If 0 or 1 is passed to our function, then no calculation is needed. Simply return the value of n.

2. If n is greater than 1, then create a loop starting at 1 that will increment until reaching the value of n. During each iteration, calculate a new Fibonacci number by adding the values of the previous two numbers. Once this calculation is complete, update the previous two numbers to their new values. The first number should now be set to equal the second (more recent) number, and the second number should be set to the value of the newly calculated Fibonacci number (before the next iteration). Once the loop exits, return the calculated Fibonacci number.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">