# What is Fibonacci Series, How to Generate Fibonacci series, Sum of Series and finding n'th number of series

 Category: Data Structure And Algorithms Tags:

## Introduction

A series of integers where each number is drawn from addition of two immediate numbers. Generally we take two initial numbers like 0, 1 or 1, 1 to create series like
0, 1, 1, 2, 3, 5, 8, 13, 21, 34 …..
1, 1, 2, 3, 5, 8, 13, 21, 34, 55 …..
So you can say any sequence number n is addition of sequences n-1 and n-2. Means Fn = Fn-1 + Fn-2 therefore F0 = 0, F1=1

## Implementation

We can produce Fibonacci Series as well some of basic operations will be:
Generating n'th number of series:

```public static int GetFIB(int n)
{
if (n <= 1)
return n;
return GetFIB(n - 1) + GetFIB(n - 2);
}
```

Executing above function in Main method:

```int n = 5;
Console.WriteLine("{0}th number of Fibbonacci Series is {1}", n, GetFIB(5));
```

Output will be:
5th number of Fibbonacci Series is 5

Generating Series:
We can use GetFIB method and call it from Main method in a loop:

```int n = 5;
for (int i = 1; i <= n; i++)
Console.WriteLine(GetFIB(i));
```

But above method has more running time complexity so we have another method below
We can use a loop only to generate series for that in Main method:

```int n = 5;
int n1 = 0, n2 = 1;
for (int i = 0; i < n; i++)
{
int temp = n1;
n1 = n2;
n2 = temp + n2;
Console.WriteLine(n1);
}
```

Above method has only O(n) complexity.
Recursive method:

```static void FIBRecursive(int i, int j, int n)
{
if (n > 0)
{
Console.WriteLine(j);
FIBRecursive(j, i + j, --n);
}
}
```

and execute above code from Main method:

```int n = 5;
FIBRecursive(0, 1, n); // here 0, 1 are initial numbers and up to 5 numbers we have to print
```

All above three methods will generate same output:
1
1
2
3
5

Generating Sum of initial n numbers

```static int SumFIB(int n)
{
if (n <= 1)
return n;    return SumFIB(n - 1) + SumFIB(n - 2) + 1;
}
```

Executing above code in Main method:

```int n = 5;
Console.WriteLine("Sum of initial {0} numbers of Fibonacci Series is: {1}", n, SumFIB(n));
```

And output will be:
Sum of initial 5 numbers of Fibonacci Series is: 12

 Like 1 Person Nikhil Joshi Ceo & Founder at Dotnetlovers Atricles: 133 Questions: 9 Given Best Solutions: 9 * void Main()
{
// Print the 20 first Fibonacci numbers
foreach (var fb in Fibonacci().Take(20))
{
Console.WriteLine(fb);
}
}

// The Fibonacci sequence
public static IEnumerable<int> Fibonacci()
{
int a = 0;
int b = 1;

while (true)
{
yield return a;
a = b;
yield return b;
b = a;
}
}
Like 0 People on 5 January 2018

Login via:   x 