Fibonacci Sequence into an Array in C#

The Fibonacci sequence, if you don’t already know, is built up by adding the two previous numbers to create the next in the sequence:

I.e.

0, 1, 1, 2, 3, 5, 8, 13… etc

As the sequence goes on indefinitely we need some kind of limit.  The example below uses limit to set how many numbers in the sequence you would like to return.

E.g. setting limit to 6 would return 0, 1, 1, 2, 3, 5

Firstly the Array is set to the size of limit.  Then the first two numbers are set to 0 and 1.  It’s then a simple case of looping from 2 (as 0 and 1 are already filled) to limit, with each new value being created by adding the previous value (i – 1) to the one before that (i – 2).  Lastly we return the array to the calling procedure.


public static int[] fibonacci(int limit)
{
    int[] series = new int[1];
    Array.Resize(ref series, limit);

    series[0] = 0;
    series[1] = 1;

    for (int i = 2; i < limit; i++)
         series[i] = series[i - 1] + series[i - 2];

    return series;
}

to test the code you could use something like:

foreach(int i in fibonacci(10))
    MessageBox.Show(i.ToString());

Be First to Comment

Leave a Reply