Consider the following program
#include <stdio.h>
int foo(int x, int y, int q)
{
if ((x<=0) && (y<=0))
return q;
if (x<=0)
return foo(x, y-q, q);
if (y<=0)
return foo(x-q, y, q);
return foo(x, y-q, q) + foo(x-q, y, q);
}
int main( )
{
int r = foo(15, 15, 10);
printf(“%d”, r);
return 0;
}
The output of the program upon execution is _________
View worked solution
Answer: 60 : 60
We need to find the value returned by the call foo(15, 15, 10). Throughout the execution, the parameter remains constant. Let us denote the function as for simplicity.
The base cases and recursive steps are defined as follows:
- If and , then .
- If and , then . Since remains , this eventually reduces to where . Thus, for any .
- Similarly, if and , then for any .
- If and , then .
Now, we compute the values bottom-up for positive arguments in steps of :
- For :
- For and :
- For :
Thus, the output of the program is 60.
Free practice · Your answers on this page are not saved.
