Monday, June 4, 2012

How to generate Fibonacci series in c#

Open a console application project in c# language in your editor and just paste the following code in your class's brackets -

static void Main(string[] args)
{
     int previous = -1; int next = 1;
     int position;
    Console.WriteLine("Enter the position");
    position = int.Parse(Console.ReadLine());
   for (int i = 0; i < position; i++)
   {
        int sum = next + previous; previous = next;
        next = sum;
       Console.WriteLine(next);
   }
   Console.ReadLine();
}


Tip: One problem with the implementation in this article is that the int types will overflow past the 47th Fibonacci number. To solve this problem, you can use the double type. Change Fibonacci() to return double. Additionally, change previous , next , and position to be of type double.


Output
0
1
1
2
3
5
8
13
21
34
55
89
144
233
377

No comments:

Post a Comment