'How to get fibonacci in 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;
        }


    }


Solution 1:[1]

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] };
}

Solution 2:[2]

for (int i = 3; i <= input; i++)

means you'll run loop input - 3 + 1 times; if input is 21, you'll run this loop from 3 to 21 including 3, and 21.

Recursive:

static int Fib(int n) {
    return (n < 2)? n : Fib(n - 1) + Fib(n - 2);
}

Iterative:

static int Fib(int x) {
    if (x == 0) return 0;

    int prev = 0;
    int next = 1;
    for (int i = 1; i < x; i++)
    {
        int sum = prev + next;
        prev = next;
        next = sum;
    }
    return next;
}

Separate your fibonacci logic from application logic.

Running Example:

http://ideone.com/cNLntC

using System;

public class Test
{
    static int Fib(int n) {
        return (n < 2)? n : Fib(n - 1) + Fib(n - 2);
    }
    public static void Main()
    {
        Console.Write(Fib(10));
    }
}

Solution 3:[3]

Using Binet's Formula:

public static void Main()
{
    double root5 = Math.Sqrt(5);
    double phi = (1 + root5) / 2;

    int input;
    Console.Write("Enter a number : ");
    input = Convert.ToInt32(Console.ReadLine());

    Console.Write("Fibonacci numbers to {0}: ", input);

    int n=0;
    int  Fn;
    do
    {
        Fn = (int)((Math.Pow(phi,n) - Math.Pow(-phi, -n)) / (2 * phi - 1 ));
        Console.Write("{0} ", Fn);
        ++n;
    } while(Fn < input);
}

Code Running in IDEOne


Doing it all in a single expression using Enumerables and Lambdas.

    static void Main(string[] args)
    {
        double root5 = Math.Sqrt(5);
        double phi = (1 + root5) / 2;

        int input;
        Console.Write("Enter a number : ");
        input = Convert.ToInt32(Console.ReadLine());

        Console.Write("Fibonacci numbers to {0}: ", input);

        Enumerable.Range(0, 80).All(n => {
            int f = (int)((Math.Pow(phi, n) - Math.Pow(-phi, -n)) / (2 * phi - 1));
            Console.Write(" " + ((f<input)?f.ToString():""));
            return f < input;
        });

Solution 4:[4]

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

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

You only need either n or input

Solution 5:[5]

This question is fairly old already, but it may be useful to programmers for interviews, so here goes:

As mentioned by some of the other answers, you have too many variables. Also, you want to separate the business logic from the GUI - which will score you points in your interview.

Refer the following code:

static void Main(string[] args)
{
  Console.Write("Enter a maximum number for the Fibonacci sequence: ");
  Console.WriteLine(Fibonacci(Convert.ToInt32(Console.ReadLine())));
  Console.WriteLine("Press any key to quit.");
  Console.ReadKey();
}

static string Fibonacci(int max)
{
  int i = 0;
  StringBuilder result = new StringBuilder();

  for (int j = 1; j <= max; j += i)
  {
    result.Append(string.Format("{0} {1} ", i, j));
    i += j;
  }

  if (i <= max)
    result.Append(i);

  return result.ToString();
}

In the Main method, we handle all UI logic and in the Fibonacci method, we handle the generation of the output string to the calling code. The following is the result of the code with a maximum of 21 (or 33):

Fibonacci Result

If we examine the code, you will notice that Maximum is an argument for the Fibonacci method and we declare only 2 variables - i for the first number and j for the second number.

Furthermore, the loop is a normal for loop instead of a while loop, as there are enough other examples of while loops. The reason for this is simple - to show that you can also use external variables with your control variables to control the loop.

From there, it is quite simple. The first number is instantiated as 0 and the second as 1. Inside of the loop, we will add the second number to the first number and the loop will use this number to increment the second number.

Finally, the last number is added to the results, as the loop will exit as soon as the second number is greater than the maximum.

To better visualize this during the interview, draw a table as follows, and populate the values through the different iterations:

Manual interview debug

If you want to take this further and test yourself a bit, you can use this example and convert it to a recursive method.

Solution 6:[6]

Most of the people here have correctly pointed out your mistake within your code. I'll just show the most elegant approach I could come up with:

Console.Write("Enter a number: ");
var input = int.Parse(Console.ReadLine());
Console.Write($"Fibonacci numbers up to {input}: ");
var (first, second) = (0, 1);
while (first <= input)
{
    Console.Write($"{first}, ");
    (first, second) = (second, first + second);
}

Solution 7:[7]

What i did is;

public int Fibonacci(int nth)
            {
                if (nth < 0) return 0;
                if (nth < 2) return nth;
    
                int Next = 0;
                int Current = 1;
                int Previous = 0;
    
                for (int i = 1; i < nth; i++)
                {
                    Next = Current + Previous;
                    Previous = Current;
                    Current = Next;
                }
                return Next;
            }

Solution 8:[8]

Fibonacci numbers with caches for better time complexity

        Dictionary<int, int> _cacheDict = new Dictionary<int, int>() { { 0, 0 }, { 1, 1 } };
    private int Fib(int number)
    {
        if (_cacheDict.ContainsKey(number))
            return _cacheDict[number];

        int sum = Fib(number - 1) + Fib(number - 2);
        _cacheDict[number] = sum;

        return sum;
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3
Solution 4 AD.Net
Solution 5 RooiWillie
Solution 6
Solution 7 Ali CAKIL
Solution 8 Rajendar Manda