TubieNek
TubieNek

Reputation: 23

Returning Fibonacci series c#

I need to make a method that returns the nth integer in the fibonacci series, the code that I wrote (edited) did not work, could anyone guide me in my for loop section. I need to use a webform and return the fibonacci series to a specific point.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

{
    public partial class Default : System.Web.UI.Page
    {
        int i, temp;

        public void Page_Load(object sender, EventArgs e)
        {

        }

        public int Fibonacci(int x)
        {
            if (x == 0)
            {
                return 1;
            }
            if (x == 1)
            {
                return 1;
            }
            else
            {
                return (Fibonacci(x - 2) + Fibonacci(x - 1));
            }

        }

        public void btSubmit_Click(object sender, EventArgs e)
        {
            // getting input from user
            int num = Convert.ToInt32(txtInput.Text);

            // logic for fibonacci series
            for (i = 0; i < num; i++)
            {
                lblResult.Text = Fibonacci(i).ToString();
            }

        }
    }

}

Upvotes: 0

Views: 2096

Answers (4)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186793

First of all, we, usually, assume

   F(0) = 0,
   F(1) = 1,
   ...
   F(N) = F(N - 1) + F(N - 2)   

See https://oeis.org/A000045

If you want a serie, let's implement a serie (with a help of IEnumerable<T> and yield return):

  using System.Linq;

  ... 

  //TODO: do you really want int as a return type? BigInteger seems to be a better choice 
  public static IEnumerable<int> Fibonacci() {
    int n_2 = 1; // your rules; or start Fibonacci from 1st, not 0th item
    int n_1 = 1;

    yield return n_2;             
    yield return n_1;

    while (true) {
      int n = n_2 + n_1;

      yield return n;

      n_2 = n_1;
      n_1 = n;
    }
  }

Having a generator we can easily take num first Fiboncacci numbers (Linq Take):

  lblResult.Text = string.Join(", ", Fibonacci().Take(num));        

In case num == 7 we'll get

  1, 1, 2, 3, 5, 8, 13

If you want an individual item - ElementAt (index is zero based):

  // 8
  lblResult.Text = Fibonacci().ElementAt(5).ToString();

Upvotes: 3

PWND
PWND

Reputation: 439

Use the method for Fibonacci:

    public int Fibonacci(int n)
    {
        int a = 0;
        int b = 1;

        for (int i = 0; i < n; i++)
        {
            int temp = a;
            a = b;
            b = temp + b;
        }
        return a;
    }

And replace:

lblResult.Text = Fibonacci(i).ToString();

To:

lblResult.Text += Fibonacci(i).ToString();

Upvotes: 0

Christopher
Christopher

Reputation: 9814

Your mistake is that you overwrite the Text, rather then add to it. Change it to lblResult.Text += Fibonacci(i).ToString() to append.

Do however note that appending a lot of text from a Loop to a GUI Element is a problematic opreation. You incur a massive overhead reading and writing GUI Elemetns. It does not mater if you only do it once per user Triggered event, but from a loop you will notice it quickly.

It might be better to build the sequence in the code behind, then dispaly it in one go. I even wrote a example code to showcase that issues:

using System;
using System.Windows.Forms;

namespace UIWriteOverhead
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        int[] getNumbers(int upperLimit)
        {
            int[] ReturnValue = new int[upperLimit];

            for (int i = 0; i < ReturnValue.Length; i++)
                ReturnValue[i] = i;

            return ReturnValue;
        }

        void printWithBuffer(int[] Values)
        {
            textBox1.Text = "";
            string buffer = "";

            foreach (int Number in Values)
                buffer += Number.ToString() + Environment.NewLine;
            textBox1.Text = buffer;
        }

        void printDirectly(int[] Values){
            textBox1.Text = "";

            foreach (int Number in Values)
                textBox1.Text += Number.ToString() + Environment.NewLine;
        }

        private void btnPrintBuffer_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Generating Numbers");
            int[] temp = getNumbers(10000);
            MessageBox.Show("Printing with buffer");
            printWithBuffer(temp);
            MessageBox.Show("Printing done");
        }

        private void btnPrintDirect_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Generating Numbers");
            int[] temp = getNumbers(1000);
            MessageBox.Show("Printing directly");
            printDirectly(temp);
            MessageBox.Show("Printing done");
        }
    }
}

As another commenter mentioned, you may want to go to some form of Multitasking too. Indeed my first Multitasking learnign experience was a Fibbonacci/Prime Number checker. They are good learning examples for that.

Upvotes: 0

Sorena Gh
Sorena Gh

Reputation: 32

You can use an integer array to keep the Fibonacci numbers until n and returning the nth Fibonacci number:

public int GetNthFibonacci_Ite(int n)  
{  
    int number = n - 1; //Need to decrement by 1 since we are starting from 0  
    int[] Fib = new int[number + 1];  
    Fib[0]= 0;  
    Fib[1]= 1;  
    for (int i = 2; i <= number;i++)  
    {  
        Fib[i] = Fib[i - 2] + Fib[i - 1];  
    }  
    return Fib[number];  
}

and then you can call it like this:

GetNthFibonacci_Ite(7);

and it retuns 7th fibonacci number

Upvotes: 0

Related Questions