ProgrammingModerateTCS NQT · Infosys pattern

What is printed?

What is printed?
int a[] = {3, 1, 4, 1, 5};
int sum(int n) { return n == 0 ? 0 : a[n - 1] + sum(n - 1); }
int main(void) { printf("%d", sum(5)); }
  1. A. 14
  2. B. 9
  3. C. 15
  4. D. 13

Correct answer: A. 14

sum(n) adds the last of the first n elements and recurses: 5 + 1 + 4 + 1 + 3 = 14. Using a[n] instead of a[n − 1] would read past the end of the array.

More C Programming questions

Exams that ask this topic