C strings and null terminators
Traverse characters without reading beyond the string.
On this page
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
#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;
}3
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
#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;}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
| Step / line | What happens | State after step | Output 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.