Thursday, January 20, 2011

Fibonacci sereis in C# [ Recursive and non Recursive]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FibonacciSereis
{
class Program
{
///
/// Get the number of sequequce required from the user
/// and prints the sereis.
///
///
static void Main ( string [ ] args )
{
//Fibonacci Sereis : 0, 1 , 1, 2 , 3, 5, 8, 13....
Console.WriteLine ( "Enter the number of Fibonacci sequence required : " );
int inum = Convert.ToInt32(Console.ReadLine ( ));

Console.WriteLine ( "****************" );

for ( int icount = 0; icount <>
{
Console.Write ( CalculateFibonacci ( icount ) +" " );
}

Console.WriteLine ( "\n***************************************************" );

CalFib ( inum );

//to hold the console to see the output.
Console.ReadLine ( );
}

///
/// Recursive function to calculate nth fibnacci number.
///
///
///
public static int CalculateFibonacci ( int n )
{
if ( n == 0 ) return 0;
if ( n == 1 ) return 1;
return CalculateFibonacci ( n - 1 ) + CalculateFibonacci ( n - 2 );
}

///
/// Non recursive function to find fibonacci sereis.
///
///
public static void CalFib ( int n )
{
//these are the seeds of fibonacci.
int ifirstNum = 0;
int iNextNum = 1;
int iResult = 0;

Console.Write ( ifirstNum + " " + iNextNum + " " );
for ( int icount = 2; icount <>
{
iResult = ifirstNum + iNextNum;

Console.Write ( iResult + " " );

ifirstNum = iNextNum;
iNextNum = iResult;
}

}

}
}

No comments:

Post a Comment