Translate

Sunday, October 13, 2013

C# Fibonacci Series

By definition, the first two numbers in the Fibonacci sequence are 0 and 1, and each subsequent number is the sum of the previous two.

0,1,1,2,3,5,8,13...

A C# program that prints out first 6 fibonacci numbers

using System;

namespace ConsoleApplication4
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            int[] fibonacci = GetFibonacci(6);

            for (int i = 0; i < fibonacci.Length; i++)
            {
                Console.WriteLine(fibonacci[i]);// 0 1 1 2 3 5
            }
        }

        private static int[] GetFibonacci(int i)
        {
            var fibonacciSeries = new int[i];

            //Initialize first two values
            fibonacciSeries[0] = 0;
            fibonacciSeries[1] = 1;

            for (int x = 2; x < i; x++)
            {
                fibonacciSeries[x] = fibonacciSeries[(x - 1)] + fibonacciSeries[(x - 2)];
            }

            return fibonacciSeries;
        }
    }
}



A C# program that prints out first 6 fibonacci numbers using an Iterator


using System;
using System.Collections.Generic;

namespace ConsoleApplication4
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            IEnumerable<int> fibonacci = GetFibonacci(6);
            foreach (int f in fibonacci)
            {
                Console.WriteLine(f); // 0 1 1 2 3 5
            }
        }

        private static IEnumerable<int> GetFibonacci(int i)
        {
            var fibonacciSeries = new int[i];

            for (int x = 0; x < i; x++)
            {
                switch (x)
                {
                    case 0:
                        fibonacciSeries[0] = 0;
                        yield return fibonacciSeries[0];
                        break;
                    case 1:
                        fibonacciSeries[1] = 1;
                        yield return fibonacciSeries[1];
                        break;
                    default:
                        fibonacciSeries[x] = fibonacciSeries[(x - 1)] + fibonacciSeries[(x - 2)];
                        yield return fibonacciSeries[x];
                        break;
                }
            }
        }
    }
}


No comments:

Post a Comment

Comments will appear once they have been approved by the moderator