ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
int sumDigits(int n) {
    if (n == 0) return 0;
    return (n % 10) + sumDigits(n / 10);
}
int main(void) {
    printf("%d", sumDigits(12345));
}
  1. A. 51
  2. B. 15
  3. C. 12345
  4. D. 5

Correct answer: B. 15

Each call peels off the last digit (n%10) and recurses on n/10: 5+4+3+2+1 = 15.

More C Programming questions

Exams that ask this topic