Fibonacci Series in c#

By | March 9, 2018

The Fibonacci Series is a series where the next term is the sum of previous two terms. The first two terms of the Fibonacci Series is 0 followed by 1.

The Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21.

Example:

using System;

namespace ConsoleApp1
{
class Program
{
static int FibonacciSeries(int n)
{
int firstnumber = 0, secondnumber = 1, result = 0;

if (n == 0) return 0; //To return the first Fibonacci number
if (n == 1) return 1; //To return the second Fibonacci number

for (int i = 2; i <= n; i++)
{
result = firstnumber + secondnumber;
firstnumber = secondnumber;
secondnumber = result;
}
return result;
}
static void Main(string[] args)
{
Console.Write("Enter the length of the Fibonacci Series: ");
int length = Convert.ToInt32(Console.ReadLine());

for (int i = 0; i < length; i++)
{
Console.Write("{0} ", FibonacciSeries(i));
}
Console.ReadKey();
}
}
}

Output:

Like it? Share it