9.4. The for Loop

The for loop executes a statement or a block of statements repeatedly until a specified expression evaluates to false. It takes the following form:

for ([initializers]; [expression]; [iterators]) statement

where

  • initializers is a comma-separated list of expressions or assignment statements to initialize the loop counters.

  • expression is an expression that can be implicitly converted to bool or a type that contains overloading of the true and false operators. The expression is used to test the loop-termination criteria.

  • iterators are expression statements to increment or decrement the loop counters.

  • statement is the embedded statement(s) to be executed.

The for statement executes the statement repeatedly as follows:

  1. The initializers are evaluated.

  2. While the expression evaluates to true, the statement(s) are executed and the iterators are evaluated.

  3. When the expression becomes false, control is transferred outside the loop.

Because the test of expression takes place before the execution of the loop, a for statement executes zero or more times. All the expressions of the for statement are optional. Listing 9.5 shows the C# for loop in action.

Listing 9.5. C# for Loops
using System;

public class Test {
  public static void Main(string[] args) {
    //Simple for loop
    for (int i = 0; i < 10; ++i) {
      Console.WriteLine("single");
    }
    //For loop with two indices
    for (int i = 10, j = 1; (i > 0 || j < 12); --i, ++j) {
      Console.WriteLine("multiple");
    }
  }
}

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.76.89