How to define a recursive function in C/C++:
int foo(int n) {
int result = 0;
const int first_value = 1;
if (0 == n)
result = first_value;
else {
int previous_result = foo(n-1);
result = n*previous_result;
}
return result;
}
Notes:
- step 0 may require more than one value if your recursion requires more than 1 value to calculate the next one.
- step 1 may require multiple checks if you have multiple starting values
- bonus hint: you should add an additional check ( e. g.
if (n < 0)
) to make sure you have a valid argument and won't accidentally run into an endless loop.
Read and understand the notes to adapt this example code for the fibonacci sequence. I won't do that for you since it smells of homework, and I can't help you learn if I do it for you.