# 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;
}
}```