ProgrammingHardTCS NQT · Accenture

How many times does the letter a occur in "panda"? The program counts with recursion.

How many times does the letter a occur in "panda"? The program counts with recursion.
#include <stdio.h>
int cnt(const char *s) {
    if (*s == '\0') return 0;
    return (*s == 'a') + cnt(s + 1);
}
int main(void) {
    printf("%d", cnt("panda"));
}
  1. A. 3
  2. B. 2
  3. C. 4
  4. D. 1

Correct answer: B. 2

The recursion adds 1 for each a it meets and recurses on the rest of the string, and panda has two a's, so it prints 2.

More C Programming questions

Exams that ask this topic