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:


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))
This entry was posted in Programming and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s