for loop

Definition

A for loop is a programming construct that is used to repeat the execution of a statement or bunch of statements. For loops are a good loop choice when traversing arrays and/or when you know exactly the amount of times you want the loop to run.

Code

for ( i = 0 ; i < 10 ; i++ )
    statement;

A for loop has three parts which are separated by semicolons:

  1. initialization
  2. condition
  3. update

Rules

  • All three parts may be empty (An empty condition is evaluated as being true).
  • Parts 1 and 3 can contain a list of expressions (separated by commas).
    • Although part 2 can only contain one condition it can be a complex condition.

Execution

The loop will be executed in the following order:

  1. initialization(s)
  2. condition check (if false the loop is over)
  3. loop body
  4. update(s)
  5. go to step 2

Visual For Loop

forloop2.png

Tips

See the tips on the loops page.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License