C# Program to find Fibonacci Sequence for the given number.


In this post today we are going to first take a look on what is Fibonacci Series and then try to implement C# program for finding the Fibonacci Sequence for a number.We will try to make implement this program without recursion and without recursion.

Fibonacci Sequence :

Fibonacci Sequence is name behind a Italian mathematician Fibonacci.The logic behind it so simple and it is quite easy to understand.In  Fibonacci Sequence every third number is sum of the first two number. The starting point for the series may be 1 and 1 or 0 and 1 depending on  the selection of the starting point further series is calculated.

One interesting thing about Fibonacci is that if we start making  squares corresponding to the number in the calculated Fibonacci Series and join the opposite angles, then you will get a spiral curve as show in below image.
Image From https://www.mathsisfun.com 
  1. Series starting with 0: 0,1,1,2,3,5,8,13,21...........
  2. Series starting with 1: 1,1,2,3,5,8,13,21,........
If you are interested to know more about Fibonacci Sequence Follow:  Wikipedia    |  Mathsisfun

Now let us move towards making our Fibonacci Series generator console app. I guess that you are familiar of creating a new C# console application in visual studio.In our first app we are going to make a simple application which can find Fibonacci for the number entered by the user.

Let us first build the logic as we know we are going to add first two number in order to get the third one.Let's take three variables a,b,c.

c=a+b;
Here c = Sum of two number,
a = First Number,
b = Second Number.

But now the question is what will be the value of  a and b.Here a and b will become our starting point we have to initialize them with 0 and 1 or 1 and 1 depending on our choice of starting point.Now to complete our logic we have to pass value of b to a and value of c to b and iterating it within the for loop.So our final logic will look like this.


1.Fibonacci Program without recursion


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            int a=0, b=1, c=0,no=0;
            Console.WriteLine("Enter number to print Fibonacci for:");
            no = Convert.ToInt16(Console.ReadLine());
            for (int i = 0; i <=no; i++)
            {
                Console.WriteLine(a);
                c = a + b;
                a = b;
                b = c;
                
            
            }

        }
    }
}

So in this post we have created Fibonacci Series program using simple for loop. In our next post we will implement this program using recursion.

Comments