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: -
- 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.
- 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.
- After each iteration through the loop, the i variable will be incremented by 1.