Consider the following program: int f(int *p, int n) { if (n Note: max(x, y) returns the maximum of x and y. The value printed by this program is …
Topic-wise GATE CS PYQs with verified steps
GATE CSE 2016 Set 2 · Q37
Time
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 _______.Your answerNumerical answer
Solution
Official answer: 3
Programming in CWe can trace the recursive calls of f(p, n) for the array $a = \{3, 5, 2, 6, 4\}$:
f(a, 5): evaluates
f(a+1, 4): evaluates
f(a+2, 3): evaluates
f(a+3, 2): evaluates
f(a+4, 1): since , the base case triggers and returns .
Unwinding the recursion:
f(a+3, 2)
f(a+2, 3)
f(a+1, 4)
f(a, 5)
Hence, the value printed is 3.
Try the question first, then check your work.
Examiner trap
Trace the recursion until the base condition returns , then propagate the values backward by computing the maximum of the recursive call and the difference between consecutive array elements.
This Programming in C previous year question is Q37 of the GATE CSE 2016 Set 2 paper. Find more GATE CSE PYQs on Programming in C in Programming and Data Structures, or browse all GATE CSE PYQs.
Free diagnostic
Take the 20-minute diagnostic: the 3 topics that cost you the most marks, and a rank range. Or sit 5 related Programming in C PYQs now with no account.
An official question by email at 7 AM IST, with a link to its verified solution. Unsubscribe in one click.
Programming in C has 74 GATE CSE PYQs across 25 papers from 2011 to 2026. 17 of them are 2-mark NAT questions like this one, and GATE CSE 2016 Set 2 has 3.
How GATE tests Programming in CIndependent practice explanation verified by the GateAI team. GATE is conducted by the IITs; question text follows the official paper.