Skip to content
Official PYQ · 2016

GATE CS 2016 Set 2 Q37 — Programming in C

Explain with AI

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 ________.

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:

  1. Call 1: f(a, 5) where p points to {3, 5, 2, 6, 4}
    • Here, p[0] - p[1] = 3 - 5 = -2.
    • Returns: max(f(a+1, 4), -2)
  2. Call 2: f(a+1, 4) where p points to {5, 2, 6, 4}
    • Here, p[0] - p[1] = 5 - 2 = 3.
    • Returns: max(f(a+2, 3), 3)
  3. Call 3: f(a+2, 3) where p points to {2, 6, 4}
    • Here, p[0] - p[1] = 2 - 6 = -4.
    • Returns: max(f(a+3, 2), -4)
  4. Call 4: f(a+3, 2) where p points to {6, 4}
    • Here, p[0] - p[1] = 6 - 4 = 2.
    • Returns: max(f(a+4, 1), 2)
  5. Call 5 (Base Case): f(a+4, 1) where p points to {4}
    • Since n <= 1, it returns 0.

Now, we propagate the values back up the recursion tree:

  • f(a+3, 2) = max(0, 2) = 2
  • f(a+2, 3) = max(2, -4) = 2
  • f(a+1, 4) = max(2, 3) = 3
  • f(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.

Published
Report a correction
Keep exploringMore Programming in C questions