Skip to content
Official PYQ · 2010

GATE CS 2010 Q35 — Algorithm Design: Dynamic Programming

Explain with AI

What is the value printed by the following C program?

#include<stdio.h>

int f(int *a, int n)
{
    if (n <= 0) return 0;
    else if (*a % 2 == 0) return *a+f(a+1, n-1);
    else return *a - f(a+1, n-1);
}

int main()
{
    int a[] = {12, 7, 13, 4, 11, 6};
    printf("%d", f(a, 6));
    return 0;
}
Choose one option
View worked solution

Answer: C

We can trace the recursive calls of the function f(a, n) starting from the base case where n≤0n \le 0:

  • f(a+6,0)=0f(a+6, 0) = 0 (since n≤0n \le 0)
  • f(a+5,1)=6+f(a+6,0)=6+0=6f(a+5, 1) = 6 + f(a+6, 0) = 6 + 0 = 6 (since 66 is even)
  • f(a+4,2)=11−f(a+5,1)=11−6=5f(a+4, 2) = 11 - f(a+5, 1) = 11 - 6 = 5 (since 1111 is odd)
  • f(a+3,3)=4+f(a+4,2)=4+5=9f(a+3, 3) = 4 + f(a+4, 2) = 4 + 5 = 9 (since 44 is even)
  • f(a+2,4)=13−f(a+3,3)=13−9=4f(a+2, 4) = 13 - f(a+3, 3) = 13 - 9 = 4 (since 1313 is odd)
  • f(a+1,5)=7−f(a+2,4)=7−4=3f(a+1, 5) = 7 - f(a+2, 4) = 7 - 4 = 3 (since 77 is odd)
  • f(a,6)=12+f(a+1,5)=12+3=15f(a, 6) = 12 + f(a+1, 5) = 12 + 3 = 15 (since 1212 is even)

Therefore, the value printed by the program is 15.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Algorithm Design: Dynamic Programming questions