17 Haz

Print Fibonacci Sequence With Recursive And Iteratively In C#

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

Usage:

            Console.WriteLine("Iterative:");
            for (int i = 0; i < 15; i++)
            {
                Console.Write(CalculateFibonacciNumberIteratively(i) + " ");
            }

            Console.WriteLine();
            Console.WriteLine("Recursive:");
            for (int i = 0; i < 15; i++)
            {
                Console.Write(CalculateFibonacciNumberRecursively(i) + " ");
            }

            //Output window is like follow.

            //Iterative:
            //0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
            //Recursive:
            //0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

Iterative Method:

        private int CalculateFibonacciNumberIteratively(int n)
        {
            int result = 0;
            int previous = 1;

            for (int i = 0; i < n; i++)
            {
                int temp = result;
                result = previous;
                previous = temp + previous;
            }
            return result;
        }

Recursive Method:

        private int CalculateFibonacciNumberRecursively(int n)
        {
            if (n == 0)
                return 0;
            else if (n == 1)
                return 1;
            else
                return CalculateFibonacciNumberRecursively(n - 2) + CalculateFibonacciNumberRecursively(n - 1);
        }