Cloudbook: C

  1. Home
  2. Control
  3. Foreach
  4. § 1 exercise →
Foreach

A while loop is a very flexible construct, but it can be clumsy. It refers to a mechanism: a code block repeated until some condition drops from true to false. The Foreach statement is a shortcut looping construct which makes more sense for list and hash data types.

Often you would like to apply to each element of a list the sequence of instructions in a code block. For instance, to print out the element, or, to categorize the element and increment a count of the number of such elements on the list.

In principal you can set this up as a while loop. But the foreach statement does all the work and gives a nice, intuitive package.