Count words in C: solved exercise

Count words in C: solved exercise

If you are looking for count words in c: solved exercise, here is a practical, compilable example focused on the reusable idea behind the exercise.

Problem statement

Count how many words are in C en rigle dev, ignoring repeated spaces.

C solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <ctype.h>
#include <stdio.h>

int contar_palabras(const char *s) {
    int total = 0;
    int en_palabra = 0;

    for (int i = 0; s[i] != '\0'; i++) {
        if (!isspace((unsigned char)s[i]) && !en_palabra) {
            total++;
            en_palabra = 1;
        } else if (isspace((unsigned char)s[i])) {
            en_palabra = 0;
        }
    }
    return total;
}

int main(void) {
    printf("%d\n", contar_palabras("C   en rigle dev"));
    return 0;
}

Expected output

1
4

Common mistakes

  • Not testing edge cases such as small or empty inputs.
  • Not validating indices, pointers, or limits carefully enough.
  • Copying the mechanics without understanding the general pattern.

Practical use

This pattern appears frequently in text handling, input validation, and buffer manipulation.

Guided practice and full book

If you want a complete path with progressive difficulty:

FAQ

Is this exercise useful in practice?

Yes. It is designed to teach a reusable C pattern rather than a one-off toy example.

How should I practice it better?

Change the input data, add edge cases, and rewrite it from scratch without looking at the solution.

How should I practice this exercise type to improve faster?

Start with small inputs, run edge cases (empty, one item, max capacity), then rewrite the solution from scratch without copying.