Fibonacci

Algorithm for printing a Fibonacci sequence is quite interesting to learn the basics of programming and its logic. So let’s start.

First, we will discuss bit of Fibonacci numbers. Fibonacci number is sum of previous two numbers. For example if we start sequence from 0, it will look like this:
0 1 1 2 3 5 8 13 21 34 55…nth. Each next number found by is by adding two previous numbers.

F(n) = F(n-1) + F(n-2)

Now let’s check few of algorithms to write the Fibonacci sequence.  It doesn’t matter what programming language we use. Here we write in C#.

 Nth 0 1 2 3 4 5 6 7 8 9 10 Fibonacci 0 1 1 2 3 5 8 13 21 34 55
using System;

namespace Fibonacci

{
class Program
{
static void Main(string[] args)
{

// Fibonacci number by usual method:
Console.WriteLine(\$”Fibonacci number for 6: {FibonacciNumber(6)}”);
// Fibonacci number by recursive method 1:
Console.WriteLine(\$”Fibonacci number for 7: {FibonacciByRecursive1(7)}”);
// Fibonacci Sequence between 0 to 10.
Console.WriteLine(“\nFibonacci Sequence: “);
for(int i=0; i<=10; i++)
{
Console.Write(\$”{FibonacciNumber(i)} “);
}

Console.WriteLine(“Fibonacci sequence by recursive method 2:”);
FibonacciByRecursive2(0,1,1,7);

}
// Returns the Fibonacci nth number.
static long Fibonacci Number(long n)
{
long firstNumber=0, secondNumber=1, result=0;
if(n==0) return0;
if(n==1) return1;
for(int i=2; i<=n; i++)
{
result=firstNumber+secondNumber;
firstNumber=secondNumber;
secondNumber=result;
}
return result;
}
// Explaination:
// Recursive method 1:
static long FibonacciByRecursive1(long n)
{
if (n==0) return 0; //To return the first Fibonacci number
if (n==1) return 1; //To return the second Fibonacci number
return FibonacciByRecursive(n-1) +FibonacciByRecursive(n-2);
}
//Explanation:

// Recursive method 2:
static void FibonacciByRecursive2 (int firstnumber, int secondnumber,
int counter, int length)
{
if (counter<=length)
{
Console.Write(“{0} “, firstnumber);
FibonacciByRecursive2(secondnumber, firstnumber+secondnumber, counter+1, length);
}
}
}
}