Calculate Fibonacci Series in Various Ways Using C#


This is one of the most asked question in interviews, calculating and printing Fibonacci series. Let’s first try the iterative approach that is simple and prints all the Fibonacci series by passing the length as parameter.

Note :  We are starting the series from 0 (instead of 1).

public static void FibonacciIterative(int length)
{
	int a = 0, b = 1, c = 0;
	Console.Write("{0} {1}", a,b);
	for (int i = 2; i < length; i++)
	{
		c = a + b;
		Console.Write(" {0}", c);
		a = b;
		b = c;
	}
 }

Test Input : FibonacciIterative(10);

Output : 0 1 1 2 3 5 8 13 21 34

We can also use the recursive way to print the series against the length as shown below.

public static void FibonacciRecursive(int length)
{
	FibonacciecursiveTemp(0, 1, 1, length);
}

private static void FibonacciecursiveTemp(int a, int b, int counter, int length)
{
	if (counter <= length)
	{
	   Console.Write("{0} ", a);
	   FibonacciecursiveTemp(b, a + b, counter + 1, length);
	}
}

Here we have used two functions with length as an input parameter. In the second method 4 parameters are required since we need to continue changing the variable’s position (in other words a -> b and b -> a + b).

We also need to increment the counter in each recursion call and to compare it with the length and continue the loop until it exceeds the length parameter.

Test Input : FibonacciIterative(10);

Output : 0 1 1 2 3 5 8 13 21 34

Calculate nth Fibonacci Number :

Calculating the nth Fibonacci number is not difficult, we just need value with the correct index.

Here we are using an integer array to calculate the Fibonacci numbers until n and then function will return the nth Fibonacci number.

public static int GetNthFibonacciIterative(int n)
{
    int number = n;
    int[] Fib = new int[number + 1];
    Fib[0] = 0;
    Fib[1] = 1;
    for (int i = 2; i <= number; i++)
    {
        Fib[i] = Fib[i - 2] + Fib[i - 1];
    }
    return Fib[number];
}

Test Input : Console.Write(“{0}”, GetNthFibonacciIterative(4));

Output : 2

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s