basics · beginner · ~15 min

Count characters

Iterate a C string until the null terminator.

Challenge

Implement int count_char(const char *s, char c) returning how many times c appears in s.

Why this matters

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.

Starter code

int count_char(const char *s, char c) {
    /* TODO */
    return 0;
}

Common mistakes

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.

Edge cases to handle

Empty string returns 0. Character is the NUL byte — return 0 by convention (don't count the terminator).

Complexity

O(n).

Background lessons

Up next

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