for loop

for loop#

for loop

a structured control flow statement that repeatedly runs a section of code until a condition is satisfied.

        flowchart LR
s( ) --> init --> condition{ } --> body --> update
update --> condition -->e( )
    

A for can be rewritten to a while and vice-versa. The difference: for can declare throwaway variables in its init field, which can be used to iterate (i.e., navigate) over a data structure:

for iterates over an array
#include <stdio.h>

char arr[3] = {'a', 'b', 'c'};

int main() {
  for (size_t i = 0; i < _Countof(arr); ++i)
    putc(arr[i], stdout);
  // `i` is not available anymore
}
while imitates a for loop
#include <stdio.h>

char arr[3] = {'a', 'b', 'c'};

int main() {
  { // Create new scope to imitate `for`
    size_t i = 0;
    while (i < _Countof(arr)) {
      putc(arr[i], stdout);
      ++i;
    }
    // `i` is still available
  }
  // `i` not available anymore
}

For example, both code describe the same behavior, but in the right code,