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 |
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. |
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 |
Code samples
This simple code sample will print out the ASCII character and its code
Example | Result | ||
---|---|---|---|
| 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 |