Jake
Jake

Reputation: 955

Fibonacci Sequence Error in C#

I've recently started learning C# (having learnt other languages) and I'm trying to create a function that generates the fibonacci sequence to the 'nth' term using a while loop and then returns the value of the 'nth' term. My current code is this:

    void fibonacci(int n)
    {
        int[] terms = { 0, 1 };
        int i = 2;

        while (i<=n)
        {
            terms.Concat( terms[i-1] + terms[i-2] );
            i += 1;
        }

        return terms[n];
    }

My understanding of C# is very poor as visual studio is telling me that I can't use 'Concat' with int[] - I'm trying to append the array with the new values. Any help would be great.

Upvotes: 0

Views: 2000

Answers (8)

Rezo Megrelidze
Rezo Megrelidze

Reputation: 3060

Here's a much more efficient way of finding fibonnaci numbers.

enter image description here

    public static IEnumerable<double> FibList(int n)
    {
        for (int i = 1; i <= n; i++)
        {
            yield return Math.Round(Fib(i));
        }
    }

    public static double Fib(double n)
    {
        double golden = 1.61803398875;

        return (n == 0 || n == 1) ? 1 : (Math.Pow(golden, n) - Math.Pow(-golden, -n))/Math.Sqrt(5);
    }

Upvotes: 0

MrHelper
MrHelper

Reputation: 1

I would do it as a recursion, and not as a loop.

private static int fibonacci(int fib)
    {
        if (fib == 2 || fib == 1)
        {
            return 1;
        }
        else
        {
            return fibonacci(fib - 1) + fibonacci(fib - 2);
        }
    }

Upvotes: 0

Chandan Kumar
Chandan Kumar

Reputation: 4638

Don't append values to an array. arrays have static size and you can't resize them after creation. use

 List<int> and its Add() method instead of array.

here is your solution for fibonacci series.

int fibonacci(int n)
{
    var terms = new List<int>{ 0, 1 };
    int i = 2;

    while (i<=n)
    {
        terms.Add( terms[i-1] + terms[i-2] );
        i += 1;
    }

    return terms[n];
}

also can be done like this :

class FibonacciSeries
{
    static void Main(string[] args)
    {
        Console.WriteLine("Enter a num till which you want fibonacci series : ");
        int val = Convert.ToInt32(Console.ReadLine());
        int num1, num2;
        num1 = num2 = 1;
        Console.WriteLine(num1);
        if (val > num2)
        {
            while (num2 < val)
            {
                Console.WriteLine(num2);
                num2 += num1;
                num1 = num2 - num1;
            }
        }

        Console.ReadLine();
    }
}

in your array format here is the solution

public int[] FibonacciSeriesArray(int num)
{
     int[] arr = new int[num+1];
     arr[0] = 0;
     arr[1] = 1;

     for (int startnum = 2; startnum  <= num; startnum++)
     {
        arr[startnum] = arr[startnum - 1] + arr[startnum - 2];
     }
     return arr;
 }

Upvotes: 0

Pragmateek
Pragmateek

Reputation: 13374

I'm surprised nobody mentioned fixing the array size.

Well, maybe I'm missing something, but you could do:

int[] FibonacciArray(int n)
{
    int[] F = new int[n+1];
    F[0] = 0;
    F[1] = 1;

    for (int i = 2; i <= n; ++i)
    {
        F[i] = F[i - 1] + F[i - 2];
    }

    return F;
}

It's in average 2.5x faster than the version using a list.

But as often there is no free-lunch: the drawback is that your memory consumption is not smoothed: you pay upfront for all the memory you'll need.

Upvotes: 0

Mateusz Rogulski
Mateusz Rogulski

Reputation: 7455

You can for example use list and change your code to:

    int fibonacci(int n)
    {
        List<int> terms = new List<int> { 0, 1 };
        int i = 2;

        while (i<=n)
        {
            terms.Add(terms[i-1] + terms[i-2]);
            i += 1;
        }

        return terms[n];
    }

Upvotes: 1

skjcyber
skjcyber

Reputation: 5957

You can't add items to an array as it has fixed length. Use List<int> instead of array

Upvotes: 0

Oded
Oded

Reputation: 499132

Arrays in C# are fixed length.

If you want to use a variable length collection, use a strongly typed List<T> instead, which has an Add method:

int fibonacci(int n)
{
    var terms = new List<int>{ 0, 1 };
    int i = 2;

    while (i<=n)
    {
        terms.Add( terms[i-1] + terms[i-2] );
        i += 1;
    }

    return terms[n];
}

Upvotes: 4

svick
svick

Reputation: 244908

You can't append to an array. In .Net, arrays have constant size and you can't resize them after creation.

Instead, you should use List<int> and its Add() method.

Upvotes: 1

Related Questions