Your output is wrong - instead of writing:
F(n) = F(n - 1) + F(n - 2)
you're writing:
F(n) = F(F(n) - 1) + F(F(n) - 2)
You should also cache the result of
F(i)
, since you're using such an inefficient way to calculate it.
Consider using
string.Format
to make your code more readable.
int result = F(i);
if (result > 0)
{
txtOutput.Text = txtOutput.Text + string.Format("F(n) = F({0}-1) + F({0}-2) = {1}", i, result) + Environment.NewLine;
}
EDIT:
Based on your deleted comment, you're looking for something like this:
int length;
if (!int.TryParse(txtLengthOfSeries.Text, out length))
{
MessageBox.Show("Please enter a valid length!");
txtLengthOfSeries.Focus();
return;
}
int term1, term2 = 1, fib = 0;
for (int i = 0; i < length; i++)
{
term1 = term2;
term2 = fib;
fib = term1 + fib;
if (i < 2)
{
txtOutput.Text += string.Format("F({0}) = {1}\n", i, fib);
}
else
{
txtOutput.Text += string.Format("F({0}) = F({1}) + F({2}) = {3}\n", i, i - 1, i - 2, fib);
}
}