jloga4
6/28/2017 - 4:00 PM

Example of an iterative solution for finding the Fibonacci sequence. From Fundamentals of Computer Programming with C# http://www.introprogr

Example of an iterative solution for finding the Fibonacci sequence. From Fundamentals of Computer Programming with C# http://www.introprogramming.info/wp-content/uploads/2013/07/Books/CSharpEn/Fundamentals-of-Computer-Programming-with-CSharp-Nakov-eBook-v2013.pdf

static void Main()
{
  Console.Write("n = ");
  int n = int.Parse(Console.ReadLine());
  
  long result = Fib(n);
  Console.WriteLine("fib({0}) = {1}", n, result);
}

static long Fib(int n)
{
  long fn = 0;
  long fnMinus1 = 1;
  long fnMinus2 = 1;
  
  for (int i = 2; i < n; i++)
  {
    fn = fnMinus1 + fnMinus2;
    fnMinus2 = fnMinus1;
    fnMinus1 = fn;
  }
  
  return fn;
}

//  n = 6
//  fib(6) = 8