jae-l
6/25/2017 - 3:45 PM

Example of how to calculate a Fibonacci sequence using recursion.

Example of how to calculate a Fibonacci sequence using recursion.

static void Main()
{
  Console.Write("Enter the number of terms for the Fibonacci sequence: ");
  int num = int.Parse(Console.ReadLine());

  Console.Write("The Fibonacci sequence is: ");

  for (int i = 0; i < num; i++)
  {
    if (i == (num - 1))
    {
      Console.Write(Fibonacci(i));
    }
    else
    {
      Console.Write(Fibonacci(i) + ", ");
    }
  }
  Console.WriteLine();
}

static long Fibonacci(int num)
{
  if (num == 0)
  {
    return 0;
  }
  if (num == 1)
  {
    return 1;
  }
  else 
  {
    return Fibonacci(num - 1) + Fibonacci(num - 2);
  }
}

//  Enter the number of terms for the Fibonacci sequence: 8
//  The Fibonacci sequence is: 0, 1, 1, 2, 3, 5, 8, 13