C · Course navigation

C strings and null terminators

Traverse characters without reading beyond the string.

On this page
Before you start

Arrays, char, and loops.

  • Traverse characters without reading beyond the string.
  • Predict the sample output and explain the state changes.
  • Complete the practice task and check the boundary cases.

The concept

A C string ends with a zero-valued character, written '\0'. A string literal used to initialize a char array supplies that terminator automatically.

The loop counts selected vowels until the terminator. This example uses lowercase ASCII text and counts a, e, and i to keep the condition visible.

Code example

C
#include <stdio.h>
#include <assert.h>
int main(void) {
    const char text[] = "learning";
    int count = 0;
    for (int i = 0; text[i] != '\0'; i++) {
        if (text[i] == 'a' || text[i] == 'e' || text[i] == 'i') {
            count++;
        }
    }
    printf("%d\n", count);
    assert(count == 3);
    return 0;
}
Output
3

Follow the code

Open the walkthrough to inspect the example one step at a time.

Show guided walkthrough
Guided walkthroughReady
1#include <stdio.h>
2#include <assert.h>
3int main(void) {
4 const char text[] = "learning";
5 int count = 0;
6 for (int i = 0; text[i] != '\0'; i++) {
7 if (text[i] == 'a' || text[i] == 'e' || text[i] == 'i') {
8 count++;
9 }
10 }
11 printf("%d\n", count);
12 assert(count == 3);
13 return 0;
14}

Follow the example

Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.

View the complete dry-run table
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput so far
Store eight letters followed by the terminator.text = l e a r n i n g \0
—
The e at index 1 matches.count = 1
—
The a at index 2 matches.count = 2
—
The i at index 5 matches.count = 3
—
Index 8 reaches the terminator and stops the loop.count = 3
3

Behind the scenes

How C processes this code

The C compiler produces a native program. Variables occupy memory, and execution enters main.

Cost and common mistakes

O(n) time and O(1) auxiliary space.

  • A char array without a terminator is not a valid C string.
  • Byte-wise character handling does not implement general Unicode text processing.

Try it yourself

Extend the condition to include o and u, and use 'education'.

Reveal answer and reasoning

The count is 5: e, u, a, i, o.

Further reading