Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get fibonacci in c#

Tags:

c#

Guys I have a question regarding on fibonacci..How do I get the fibonacci series that the number will also end on user input...example if I put 21 the output must be 0 1 1 2 3 5 8 13 21

This is my code

    static void Main(string[] args)
    {

        int input, first = 0, second = 1, third = 0;
        Console.Write("Enter a number : ");
        n = Convert.ToInt32(Console.ReadLine());
        Console.Write("First {0} Fibonacci numbers {1} {2} ", input, first, second);

        for (int i = 3; i <= input; i++)
        {
            third = first + second;
            Console.Write("{0} ", third);
            first = second;
            second = third;
        }


    }
like image 403
jhovyn Avatar asked Dec 23 '22 23:12

jhovyn


1 Answers

One of your error is in the looping logic.

If the user inputs 21, you want the fibonacci numbers up to 21. You don't want the first 21 fibonacci numbers.

Rather than

   for (int i = 3; i <= input; i++)
   {
      ////
   }

Do

   while(second <= input)
   {
       ////
   }

My answer almost certainly has an off-by-one error, but this should point you in the right direction.


Fibonacci sequences are often used for tech-interview question, because programmers struggle with a temporary variable, especially when under pressure. It's easier without it:

Don't have three variables (first, second and third). Instead, have one variable: an array containing the last two elements of the sequence:

int[] seq = new[] { 0, 1 };

Then, every time you wanted to move to the next number:

while(seq[1] <= input) 
{
   Console.Write("{0}", seq[1]);    
   seq = new[] { seq[1], seq[0] + seq[1] };
}
like image 156
Andrew Shepherd Avatar answered Jan 04 '23 22:01

Andrew Shepherd