Fibonacci Series Code in C#

Fibonacci series is a series of numbers where the next number is the sum of the previous two numbers behind it. It has the starting two numbers predefined as 0 & 1. The series goes on like this:
0,1,1,2,3,5,8,13,21,34,55,89,144,233,377……..

Here we illustrate two techniques for the creation of the Fibonacci Series to n terms. The For Loop method & the Recursive Technique. Check them below.


The For Loop technique requires that we create some variables and keep track of the latest two terms('First' & 'Second'). Then we calculate the next term by adding these two terms & setting a new set of two new terms. These terms are the 'Second' & 'Newest'.



using System; using System.Text; using System.Threading.Tasks;

namespace Fibonacci_series_Using_For_Loop
{
    class Program
    {
        static void Main(string[] args)
        {
            int n, first = 0, second = 1, next, c;
            Console.WriteLine("Enter the number of terms");
            n = Convert.ToInt16(Console.ReadLine());
            Console.WriteLine("First "+ n +" terms of Fibonacci series are:");
            for (c = 0; c < n; c++)
            {
                if (c <= 1)
                    next = c;
                else
                {
                    next = first + second;
                    first = second;
                    second = next;
                }
                Console.WriteLine(next);
            }
            Console.ReadKey();
        }
    }
}

The recursive technique to a Fibonacci series requires the creation of a function that returns an integer sum of two new numbers. The numbers are one & two less than the number supplied. In this way final output value has each number added twice excluding 0 & 1. Check the program below.

using System; Using System.Text; using System.Threading.Tasks;

namespace Fibonacci_Series_Recursion
{
    class Program
    {
        static void Main(string[] args)
        {
            int n, i = 0, c;
            Console.WriteLine("Enter the number of terms");
            n=Convert.ToInt16(Console.ReadLine());
            Console.WriteLine("First 5 terms of Fibonacci series are");
            for ( c = 1 ; c <= n ; c++ )
            {
                Console.WriteLine(Fibonacci(i));
                i++;
            }
            Console.ReadKey();
        }
        static int Fibonacci(int n)
        {
            if (n == 0)
                return 0;
            else if (n == 1)
                return 1;
            else
                return (Fibonacci(n - 1) + Fibonacci(n - 2));
        }
    }
}