-
Novice C'er Needs Help
I cannot figure out what the problem is with this program, i just started learning C and i need some help, what are the bugs in here if any, and what can i do to fix them?
Thanks,
Geoff
/* prints out the first n fibonacci numbers */
void fibonacci (int n)
{
if (n == 0) return;
printf("\n1");
if (n == 1) return;
printf(",1");
fiborecurse(1,1,n-2);
printf("\n");
}
/* helper function for fibonacci */
void fiborecurse (int n1,int n2,int n)
{
int n3=n1+n2;
if(n==0) return;
else {
fiborecurse(n1,n2,n);
printf(",%d", n3);
}
}
-
any clue as to the problem which is happening, ie constant loops?
what printouts. from just quickly looking, the following function looks weird:
[code]
void fiborecurse (int n1,int n2,int n)
{
int n3=n1+n2;
if(n==0)
return;
else
{
fiborecurse(n1,n2,n);
printf(",%d", n3);
}
}
the value n, which is the last number passed decides when to stop the loops, however nowhere in this function does the value of n change, i think where you have:
Code:
fiborecurse(n1,n2,n);
it should be something like
Code:
fiborecurse(n1,n2,n-1);
-
This is probably one of the most terrible recursive functions you can write because it branches out exponentially. Translation: it is horribly, horribly inefficient. Notice where the function is recursively called twice:
Code:
int f ( int i )
{
if ( i < 1 ) return 0;
if ( i == 1 ) return 1;
return f ( i - 1 ) + f ( i - 2 );
}
This is something you want to avoid, so the fibonacci program is better written iteratively than recursively. But if you must, there is a way to give the recursive function a linear running time by placing the values in an array so that you don't recalculate:
Code:
int fImproved ( int i )
{
static a[BUFSIZ] = {0};
if ( i == 0 || i == 1 )
return a[i] = i;
if ( a[i] == 0 )
return a[i] = fImproved ( i - 1 ) + fImproved( i - 2 );
return a[i];
}
-Prelude