Friday, March 26, 2010

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();
}

Output is -

5 comments:

  1. wrong, position 9 is 34. you are not showing position 9, position 8 = 21.

    ReplyDelete
    Replies
    1. shut-up man,,, do it your-self, dis program is fine...

      Delete
  2. it breaks at about 50. your program is similar to the one i made.


    namespace ConsoleApplication1
    {
    class Program
    {
    static void Main(string[] args)
    {
    Console.WriteLine("Sequence ending term?");

    int d = int.Parse(Console.ReadLine());

    int a = -1; int b = 1;

    for (int i = 0; i < d; i++)
    {
    int sum = b + a; a = b;
    b = sum;
    Console.WriteLine(b);
    }
    Console.WriteLine("Type and enter to close.");
    Console.ReadLine();
    }
    }
    }

    but for some reason it breaks at around 47.

    ReplyDelete
  3. If you change 'int' to 'double' you can avoid the error you encounter when you are around 47.

    ReplyDelete