πŸ’©

programierds

strings / traversal / words

Traverse a C string and count words

The key is not memorizing code: it is detecting when the traversal enters a word. The loop reads each char until \0, updates state, and prints the result at the end.

1) ProgramActive line: 1
1#include <stdio.h>
2int main() {
3  char frase[] = "Hola mundo en C";
4  int i = 0;
5  int palabras = 0;
6  int dentro = 0;
7  while (frase[i] != '\0') {
8    if (frase[i] != ' ' && dentro == 0) {
9      palabras = palabras + 1;
10      dentro = 1;
11    }
12    if (frase[i] == ' ') {
13      dentro = 0;
14    }
15    i = i + 1;
16  }
17  printf("Palabras: %d\n", palabras);
18  return 0;
19}
Step 1: The program includes stdio.h to use printf.
Step 1 / 1
2) Variables
frase[i]-
i-
palabras-
dentro-
condicion while-
accion-
3) String being read"Hola mundo en C"
The traversal has not started yet.
4) Console
./contar-palabrasstdout