Consider the following program:
int f (int * p, int n)
{
if (n <= 1) return 0;
else return max (f (p+1, n-1), p[0] - p[1]);
}
int main ()
{
int a[] = {3, 5, 2, 6, 4};
printf(" %d", f(a, 5));
}
Note: returns the maximum of and .
The value printed by this program is ________.
View worked solution
Answer: 3
To find the value printed by the program, let's trace the execution of the recursive function f(p, n) starting with the call f(a, 5), where the array is a = {3, 5, 2, 6, 4}.
The function definition is:
int f (int * p, int n)
{
if (n <= 1) return 0;
else return max (f (p+1, n-1), p[0] - p[1]);
}
Let's trace the recursive calls step-by-step:
- Call 1:
f(a, 5)whereppoints to{3, 5, 2, 6, 4}- Here,
p[0] - p[1] = 3 - 5 = -2. - Returns:
max(f(a+1, 4), -2)
- Here,
- Call 2:
f(a+1, 4)whereppoints to{5, 2, 6, 4}- Here,
p[0] - p[1] = 5 - 2 = 3. - Returns:
max(f(a+2, 3), 3)
- Here,
- Call 3:
f(a+2, 3)whereppoints to{2, 6, 4}- Here,
p[0] - p[1] = 2 - 6 = -4. - Returns:
max(f(a+3, 2), -4)
- Here,
- Call 4:
f(a+3, 2)whereppoints to{6, 4}- Here,
p[0] - p[1] = 6 - 4 = 2. - Returns:
max(f(a+4, 1), 2)
- Here,
- Call 5 (Base Case):
f(a+4, 1)whereppoints to{4}- Since
n <= 1, it returns0.
- Since
Now, we propagate the values back up the recursion tree:
f(a+3, 2) = max(0, 2) = 2f(a+2, 3) = max(2, -4) = 2f(a+1, 4) = max(2, 3) = 3f(a, 5) = max(3, -2) = 3
Thus, the value printed by the program is 3.
Free practice · Your answers on this page are not saved.
