Search

Calculate Fibonacci number

This C# code snippet calculates a Fibonacci number using recursion, i.e., the Fibonacci method calls itself when necessary.
using System;
static int Fibonacci (int x)
{
   Console.WriteLine ("x = {0}", x);
   if (x <= 1)
   {
      return x;
   }
   return Fibonacci (x-1) + Fibonacci (x-2);
}
  
static void Main( )
{
   Console.WriteLine ("Fibonacci no. = {0}", Fibonacci (5));
   Console.ReadKey();
}