Use an iterator to return a sequence of Fibonacci numbers in C#

using System;
using System;
 
class FibTest
{
  static void Main ()
  {
    foreach (int fib in Fibs (6))
      Console.Write (fib + "");
  }
 
  static IEnumerable <int> Fibs (int fibCount)
  {
    for (int i = 0, prevFib = 1, curFib = 1; i <fibCount; i++)
    {
      yield return prevFib;
      int = newFib prevFib curFib +;
      prevFib = curFib;
      curFib = newFib;
    }
  }
}

Output: 1 1 2 3 5 8

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.