basics · beginner · ~15 min
Iterate a C string until the null terminator.
Count how many times a given character appears in a string.
Implement int count_char(const char *s, char c) that returns the number of occurrences of c in the NUL-terminated string s. No main — the grader calls it.
s: a NUL-terminated string (may be empty).c: the character to count.The number of times c appears in s, as an int.
count_char("banana", c) where c='a' -> 3
count_char("banana", c) where c='n' -> 2
count_char("hello", c) where c='z' -> 0
0.0.Counting how many times a character appears in a string is the simplest 'iterate and accumulate' pattern. It's the unit of building histograms, frequency tables, and search counts.
A NUL-terminated string s and a character c.
The count of c in s, as an int.
int count_char(const char *s, char c) {
/* TODO */
return 0;
}
Iterating past the NUL (no need — strings end there). Returning int when count could exceed INT_MAX (use size_t). Forgetting case sensitivity if the test cares.
Empty string returns 0. Character is the NUL byte — return 0 by convention (don't count the terminator).
O(n).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.