data-structures · beginner · ~15 min

Recursive character count

Count a character by walking the string.

Challenge

Implement:

int count_char(const char *s, char c);

Return how many times c occurs in s, computed recursively.

Input format

A string and a character.

Output format

Occurrence count.

Constraints

One character per call.

Starter code

#include <stddef.h>
/* Count occurrences of character c in string s, computed recursively. */
int count_char(const char *s,char c){ (void)s;(void)c; return 0; }

Common mistakes

Forgetting the NUL base case; not advancing the pointer.

Edge cases to handle

Empty string returns 0.

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.