Tsallaka zuwa abun ciki
Justice Tech School

Practice: Word Counter

Count words in a string with a loop and a state flag.

Example
#include <stdio.h>

int main(void) {
  const char *s = "the quick  brown fox";
  int words = 0, in = 0;
  for (int i = 0; s[i]; i++) {
    if (s[i] != ' ' && !in) { words++; in = 1; }
    else if (s[i] == ' ') in = 0;
  }
  printf("%d\n", words);
  return 0;
}

Result

4

Exercise

State flag.

in = ;

Quiz Test

What does the flag track?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.