for ... loop

The for loop has to be the most flexible and simplest mechanism for performing iterations in C# and many other languages. In C# there are several forms to this loop

 

Basic structure

for( statement-1; statement-2; statement-3 )

Each statement is optional and serves a very specific purpose

Statement

Intent

Statement

Intent

statement-1

This is the initialiser. It should set up the parameters for the loop condition.

It could be written outside of and before the for loop

int x = 0;

It is usual that the first statement simply sets up some initial values for the loop. Any variables declared at this point only exist withn the scope of the for loop.

statement-2

The is the condition statement. It should perform a test to determine if the loop should continue.

It could be writen in the code block of the for loop. If no longer true a forced exit from the loop can be triggered.

x < 10;

Whilst the condition is true, the code block below the for statement will be executed

statement-3

This is the iterator statement. It should increment/decrement the variables that are used in the conidition statement.

It could be written in at the end of the code block.

x++;

At the end of the execution of the code block, statement-3 (in this case x++) will be executed, statement-2 will then be tested .

Code samples

This simple code sample will print out the ASCII character and its code

Example

Result

Example

Result

const int MAX_CHAR = 256; for (int charIndex = 0; charIndex < MAX_CHAR; charIndex++) { char c = (char)charIndex; Console.WriteLine($"{c} ASCII code {charIndex}"); }

Upper limit of the ASCII table

Specify the loop conditions, starting at 0, character index not greater than 255, and increment the index by 1

For each integer value convert it into a character

Display the character and it’s integer value

Â