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:
Post a Comment