I pasted your code on https://tio.run/#c-gcc, and here’s the result:
main
prototype
.code.tio.c:3:7: warning: ‘main’ takes only zero or two arguments [-Wmain]
int main(int fib) {
^~~~
the main
function prototype is int main(void)
or int main(int argc, char *argv[])
Since you want user to input a number, you can choose the first form.
count
type
.code.tio.c: In function ‘main’:
.code.tio.c:7:5: error: ‘count’ undeclared (first use in this function)
count = 0; // counts the number of times the function is called
^~~~~
You must give a type to count
variable, like
int count = 0;
fib_rec
declaration
.code.tio.c:8:12: warning: implicit declaration of function ‘fib_rec’ [-Wimplicit-function-declaration]
return fib_rec(n, &count);
^~~~~~~
You have not declared the function before using it.
You can declare it this way: int fib_rec(int n, int *count)
for instance before the main
definition.
printf
usage
.code.tio.c: In function ‘fib_rec’:
.code.tio.c:21:15: warning: passing argument 1 of ‘printf’ from incompatible pointer type [-Wincompatible-pointer-types]
printf (count);
^~~~~
The printf
function ask for some formatting. If you want to display a integer value, use %d
:
printf("count value is: %d\n", count);
incompatible pointer type
.code.tio.c:22:27: warning: passing argument 2 of ‘fib_rec’ makes pointer from integer without a cast [-Wint-conversion]
return fib_rec(n-1, *count)+ fib_rec(n-2, *count);
^~~~~~
Here count
is already a pointer on integer, *
is unnecessary:
return fib_rec(n-1, count)+ fib_rec(n-2, count);
display of computed value
Your code return the computed value, but doesn’t display it.
To do so, replace return fib_rec(n, &count);
with
printf("fib_rec(%d) = %d\n", n, fib_rec(n, &count));
return 0;
So the corrected code could be:
#include <stdio.h>
int fib_rec(int n, int *count);
int main(void) {
int n;
printf("enter n\n");
scanf("%d",&n);
int count = 0; // counts the number of times the function is called
printf("fib_rec(%d) = %d\n", n, fib_rec(n, &count));
return 0;
}
int fib_rec(int n, int *count)
{
int b=0,c=1;
*count = *count +1;
if(n<=1)
{
return n;
}
else
{
printf ("count: %d\n", *count);
return fib_rec(n-1, count)+ fib_rec(n-2, count);
}
}
0
solved Recursive implementation of Fibonacci function