Chapter 16 Loops

Table of Contents
16.1 For Loops
16.2 Foreach Loops
16.3 While Loops

16.1 For Loops

16.1.1 Synopsis

for (expr1; expr2; expr3)
  statement;

16.1.2 Description

First, expr1 is executed, then statement is executed until expr2 is true; after each iteration expr3 is executed.

You can also execute more than one statement inside the loop: simply enclose them between braces:

for (expr1; expr2; expr3) {
  statement1;
  statement2;
}

16.1.3 Example

for (i=0; i<5; i++)
  echo (i + ", ");

Cows first sets i=0, then repeat the echo (i + ", "); statement until i is lower than 5. After each iteration (i.e. after displaying each value) i is incremented by 1. This is Cows' output:

0, 1, 2, 3, 4,

The comma after the last number is ugly, so let's work around it:

limit = 5;
for (i=0; i<limit; i++) {
  echo (i);
  if (i <  limit - 1) {
    echo (", ");
  }
}

This is Cows' output:

0, 1, 2, 3, 4

This manual can be downloaded from http://www.g-cows.org/.