GateAI
Programming in C

GATE CSE 2016 Set 2 · Q37

NAT2 marksMedium

Time

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: max⁡(x,y)\max(x, y) returns the maximum of xx and yy. The value printed by this program is _______.

Your answerNumerical answer

Enter a value to check

Solution

Step-by-step verified solution

Official answer: 3

Programming in C

We can trace the recursive calls of f(p, n) for the array $a = \{3, 5, 2, 6, 4\}$:

  1. f(a, 5): evaluates max⁡(f(a+1,4),a[0]−a[1])=max⁡(f(a+1,4),3−5)=max⁡(f(a+1,4),−2)\max(f(a+1, 4), a[0] - a[1]) = \max(f(a+1, 4), 3 - 5) = \max(f(a+1, 4), -2)

  2. f(a+1, 4): evaluates max⁡(f(a+2,3),a[1]−a[2])=max⁡(f(a+2,3),5−2)=max⁡(f(a+2,3),3)\max(f(a+2, 3), a[1] - a[2]) = \max(f(a+2, 3), 5 - 2) = \max(f(a+2, 3), 3)

  3. f(a+2, 3): evaluates max⁡(f(a+3,2),a[2]−a[3])=max⁡(f(a+3,2),2−6)=max⁡(f(a+3,2),−4)\max(f(a+3, 2), a[2] - a[3]) = \max(f(a+3, 2), 2 - 6) = \max(f(a+3, 2), -4)

  4. f(a+3, 2): evaluates max⁡(f(a+4,1),a[3]−a[4])=max⁡(f(a+4,1),6−4)=max⁡(f(a+4,1),2)\max(f(a+4, 1), a[3] - a[4]) = \max(f(a+4, 1), 6 - 4) = \max(f(a+4, 1), 2)

  5. f(a+4, 1): since n=1≤1n = 1 \le 1, the base case triggers and returns 00.

Unwinding the recursion:

  • f(a+3, 2)=max⁡(0,2)=2= \max(0, 2) = 2

  • f(a+2, 3)=max⁡(2,−4)=2= \max(2, -4) = 2

  • f(a+1, 4)=max⁡(2,3)=3= \max(2, 3) = 3

  • f(a, 5)=max⁡(3,−2)=3= \max(3, -2) = 3

Hence, the value printed is 3.

Try the question first, then check your work.

Think the official key or this write-up is wrong?

Report error or challenge

Examiner trap

The misconception this question tests

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

Where do you stand for GATE?

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.

One GATE CSE PYQ every morning

An official question by email at 7 AM IST, with a link to its verified solution. Unsubscribe in one click.

Programming in C in GATE CSE

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 C

More from GATE CSE 2016 Set 2

Share this solution

A plain-text card for WhatsApp or Telegram study groups.

GateAI solution cardGATE CSE 2016 Set 2 · Q37 · NAT

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

Independent practice explanation verified by the GateAI team. GATE is conducted by the IITs; question text follows the official paper.