4.6. Iterating Over Arrays

We can iterate over arrays by taking indexing and sizing.


  string *colors = ({ "red", "blue", "green", "yellow" });
  int lastindex = sizeof(colors) - 1;
  int i;

  // for each element in the array from index 0 through the last index,
  // we write out the contents of that element.
  for (i = 0; i <= lastindex; i++) {
    write(colors[i] + "\n");
  }

Slightly more concise, the above code is functionally the same as this:

Example 4-10. Iterating over arrays


  string *colors = ({ "red", "blue", "green", "yellow" });
  int i;

  // for each element in the array starting with 0 whose index is less
  // than the size of the array we write out the contents of that element.
  for (i = 0; i < sizeof(colors); i++) {
    write(colors[i] + "\n");
  }

We can do this with while loops--since a for loop is just a glorified while loop:


  string *colors = ({ "red", "blue", "green", "yellow" });
  int i;

  // for each element in the array starting with 0 whose index is less
  // than the size of the array we write out the contents of that element.
  i = 0;
  while (i < sizeof(colors)) {
    write(colors[i] + "\n");
    i = i + 1;
  }