Fibonacci Sequence in C#

The Fibonacci sequence is a set of numbers that starts with a one or a zero, followed by a one, and proceeds based on the rule that each number (called a Fibonacci number) is equal to the sum of the preceding two numbers. If the Fibonacci sequence is denoted F ( n ), where n is the first term in the sequence, the following equation obtains for n = 0, where the first two terms are defined as 0 and 1 by convention:

F (0) = 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ...

Let's see an example in C# language for first 10 items.

using System;

namespace FactorialExample

{

    class Program

    {

        static void Main(string[] args)

        {

            FibonacciSeries();                      

            Console.ReadKey();

        }

        private static void FibonacciSeries()

        {

            int previousValue = 1;

            int nextValue = 0;

            int secondPreviousValue = 0;

            Console.Write(secondPreviousValue + ",");

            Console.Write(previousValue + ",");

            for (int i = 1; i <= 10; i++)

            {

                nextValue = previousValue + secondPreviousValue;

                secondPreviousValue = previousValue;

                previousValue = nextValue;

                Console.Write(nextValue + ",");

            }

        }

    }

}

Ebook Download
View all
Learn
View all