C Sharp

The for Statement

By far, the most common iteration statement that you'll see and use is the for statement. The for statement is made up of three parts. One part is used to perform initialization at the beginning of the loop-this part is carried out only once. The second part is the conditional test that determines whether the loop is to be run again. And the last part, called "stepping," is typically (but not necessarily) used to increment the counter that controls the loop's continuation-this counter is what is usually tested in the second part. The for statement takes the following form: -

    for (initialization; Boolean-expression; step)
         embedded-statement

Note that any of the three parts (initialization, Boolean-expression, step) can be empty. When Boolean-expression evaluates to false, control is passed from the top of the loop to the next line following the embedded-statement. Therefore, the for statement works just like a while statement except that it gives you the additional two parts (initialization and step). Here's an example of a for statement that displays the printable ASCII characters: -

using System;
class ForTestApp
{
    const int StartChar = 33;
    const int EndChar = 125;
    static public void Main()
    {
        for (int i = StartChar; i <= EndChar; i++)
        {
            Console.WriteLine("{0}={1}", i, (char)i);
        }
    }
}

The order of events for this for loop is as follows: -

  1. A value-typevariable (i) is allocated on the stack and initialized to 33. Note that this variable will be out of scope once the for loop concludes.
  2. The embedded statement will execute while the variable i has a value less than 126. In this example, I used a compound statement. However, because this for loop consists of a single line statement, you could also write this code without the braces and get the same results.
  3. After each iteration through the loop, the i variable will be incremented by 1.