ProgrammingHardTCS NQT · Infosys pattern

What is printed? (recursion with a pointer parameter used only for read, not accumulation)

What is printed? (recursion with a pointer parameter used only for read, not accumulation)
int maxOf(int a[], int n) {
    if (n == 1) return a[0];
    int rest = maxOf(a + 1, n - 1);
    return a[0] > rest ? a[0] : rest;
}
int main(void) {
    int a[] = {3, 7, 2, 9, 4};
    printf("%d", maxOf(a, 5));
}
  1. A. 7
  2. B. 4
  3. C. 3
  4. D. 9

Correct answer: D. 9

Each call advances the pointer by one and shrinks n by one, recursing down to a single element, then bubbling back up the maximum seen so far. The largest value in {3,7,2,9,4} is 9.

More C Programming questions

Exams that ask this topic