# Thread: My Ansi C Fibonacci code stinks! obvious bug?

1. ## My Ansi C Fibonacci code stinks! obvious bug?

I know I have an obvious bug -- well, a calculation error somewhere. Doing a quick fibonacci code sample, only requirements is NOT to use arrays and NOT to do it recursively.

This is what I came up with, and its obviously wrong!

Code:
```int fibonacci(int userinput)

{

int result = 0;
int counter = 0;

if (userinput == 0) return result = 0;
else if (userinput == 1) return result = 1;
else
for (counter = userinput; counter > 1; counter--)
{
result += ((counter - 1) + (counter - 2));
}
return (result);
}```
I am sure the "bad guy" is the line result += (...) but what is wrong?

2. This version actually works, but how can I improve it?
Code:
```int fibonacci(int userinput)
{

if (userinput < 2)
return userinput;

else
{
int n1 = 1, n2 = 1, tmp = 0;

for (int i = 2; i < userinput; i++)
{
tmp = n2;
n2 = n1 + n2;
n1 = tmp;
}

return n2;
}
}```

3. Originally Posted by Hansie
This version actually works, but how can I improve it?
Code:
```int fibonacci(int userinput)
{

if (userinput < 2)
return userinput;

else
{
int n1 = 1, n2 = 1, tmp = 0;

for (int i = 2; i < userinput; i++)
{
tmp = n2;
n2 = n1 + n2;
n1 = tmp;
}

return n2;
}
}```

4. Fibonacci sequence - isn't that the sequence 1, 1, 2, 3, 5, 8, 13, 21, etc.? If so, then what you need are two numbers that form the starting point. For the next number, you add the previous 2 numbers. It continues like that. Study the pattern and write the program for it that follows the pattern. I can see that you apparently have this in your code, but comments and better variable names would be helpful. The output could be named "output", the previous number as "PrevNumber" and the one before it "Prev2Number" (use whatever, but something more clear than "n1" and "n2").

5. You should refer to the first 3 'elements' of the Fibonacci sequence as 'a', 'b' & 'c'. Since that makes sense, c = a + b, where a = 1 (first iteration) and b = 2 (first iteration).

Then on the Nth iteration, a = b, b = c, c = a+b

Such as, 1 (a), 2 (a,b), 3(a,b,c), 5 (a,b,c), 8 (a,b,c), etc

And there is a mathematical way to get the Nth element of the Fibonacci sequence using a formula, rather than using a bruteforce method.