Sasha Sydoruk

Building a better mousetrap with XHTML, AJAX and RSS

Fun with C#’s yield and Fibonnaci numbers

   1:  using System;
   2:  using System.Collections;
   3:   
   4:  namespace TestConsoleApplication
   5:  {
   6:      internal class Program
   7:      {
   8:          private static void Main(string[] args)
   9:          {
  10:              foreach (int x in GetFibonacciNumbers(20))
  11:              {
  12:                  Console.WriteLine(x);
  13:              }
  14:   
  15:              Console.ReadKey();
  16:          }
  17:   
  18:   
  19:          public static IEnumerable GetFibonacciNumbers(int n)
  20:          {
  21:              int p1 = 1;
  22:              int p2 = 0;
  23:   
  24:              yield return 0;
  25:              yield return 1;
  26:   
  27:              for (int i = 0; i < n; i++)
  28:              {
  29:                  int sum = p1 + p2;
  30:                  yield return sum;
  31:                  p2 = p1;
  32:                  p1 = sum;
  33:              }
  34:          }
  35:      }
  36:  }

No comments yet. Be the first.

Leave a reply