The blog has moved to a new address. The blog is now located at http://devintelligence.com

Thursday, May 18, 2006

Compute Fibonacci numbers using yield statement

A program to compute Fibonacci numbers using yield statement.

class YieldUsageExample

{

static void Main(string[] args)

{

int n = 8;

foreach (int i in Fibonacci(n))

{

Console.Write("{0} ", i);

}


Console.ReadLine();

}



public static IEnumerable Fibonacci(int n)

{

int previous = -1;

int result = 1;

for (int i = 0; i <= n; ++i)

{

int sum = result + previous;

previous = result;

result = sum;

yield return result;

}

}

}



No comments: