Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

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 )

...

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

...