Consider the following recursive C function.
void get(int n)
{
if (n<1) return;
get (n-1);
get (n-3);
printf("%d", n);
}
If function is being called in then how many times will the function be invoked before returning to the ?
View worked solution
Answer: B
To find the total number of times the function get() is invoked, we can define a recurrence relation. Let denote the total number of times get() is called (including the initial call) for an input .
1. Base Cases
When , the condition if (n < 1) is satisfied, and the function returns immediately. This still counts as invocation.
2. Recurrence Relation
For , the function is invoked once, and then it recursively calls get(n-1) and get(n-3). Therefore, the recurrence relation is:
3. Step-by-Step Computation
Using the recurrence relation, we compute for to :
- For :
- For :
- For :
- For :
- For :
- For :
Thus, the get() function is invoked a total of times before returning to main().
Free practice · Your answers on this page are not saved.
