Create Fibonacci using Switch statement - CSharp Language Basics

CSharp examples for Language Basics:switch

Description

Create Fibonacci using Switch statement

Demo Code

using System;//from  w  ww .  j av  a  2 s .c  o  m
using System.ComponentModel;
class FibonacciSwitch
{
   static void Main()
   {
      for (int i = 0; i < 10; i++)
      {
         Console.WriteLine($"Fib({i}) = {Fib(i)}");
      }
   }
   static int Fib(int n)
   {
      switch (n)
      {
         case 0: return 0;
         case 1: return 1;
         case var _ when n > 1: return Fib(n - 2) + Fib(n - 1);
         default: throw new ArgumentOutOfRangeException(nameof(n), "Input must be non-negative");
      }
   }
}

Result


Related Tutorials