Fibonacci Series in C#



To find Fibonaccli series, firsty set the first two number in the series as 0 and 1.

int val1 = 0, val2 = 1, v

Now loop through 2 to n and find the fibonai series. Every number in the series is the sum of the last 2 elements −

for(i=2;i<n;++i) {
   val3 = val1 + val2;
   Console.Write(val3+" ");
   val1 = val2;
   val2 = val3;
}

The following is the complete code to display Fibonacci series in C# −

Example

 Live Demo

using System;
public class Demo {
   public static void Main(string[] args) {
      int val1 = 0, val2 = 1, val3, i, n;
      n = 7;
      Console.WriteLine("Fibonacci series:");
      Console.Write(val1+" "+val2+" ");
      for(i=2;i<n;++i) {
         val3 = val1 + val2;
         Console.Write(val3+" ");
         val1 = val2;
         val2 = val3;
      }
   }
}

Output

Fibonacci series:
0 1 1 2 3 5 8

Advertisements