BlackWaspTM
C# Programming
.NET 1.1+

C# Program Flow Control: The For Loop (2)

The twenty-ninth part of the C# Fundamentals tutorial starts a multi-part examination of the program flow control commands available to the C# developer. This first article examines the for loop structure that allows the repeated execution of code.

Using a Code Block for a Loop's Command

The example described above permits the repeated execution of a single command. As mentioned in the first article in the tutorial, a code block groups several commands and permits them to be used as a single entity. To create a loop that contains more than one command, a code block should be used by surrounding the group of statements with brace characters, { and }. The following example uses a code block to fill a new array with a series of square numbers:

int[] squares = new int[11];
int i;

for (i = 0; i <= 10; i++)
{
    int squareValue = i * i;
    squares[i] = squareValue;
}

Note that the integer value 'squareValue' is declared inside the loop. Any variable declared within the code block of a loop exists for one iteration. When the loop restarts, the variable is destroyed and must be recreated. This means that the variable is not available outside the code block. If the variable is needed outside of the loop or must persist between iterations, declare it before the for statement.

Declaring the Loop Control Variable in the Initialisation

In the previous example, the loop control variable is declared before the loop executes. On completion of the loop the variable still exists. The variable will contain the value eleven at this time as this is the value that causes the loop condition to be false. Often the loop control variable is required only for the duration of the loop's execution. Where this is the case, it may be declared within the initialisation section of the for statement. On completion of the loop, the variable is no longer accessible.

int[] squares = new int[11];

for (int i = 0; i <= 10; i++)
{
    int squareValue = i * i;
    squares[i] = squareValue;
}

Multiple Loop Control Variables

The for loop may include more than one control variable, each with independent initialisation and iteration information. A combination of the variables may be included within the condition section of the for loop. The following example uses two loop control variables. Note that the initialisation and iteration sections are comma-separated.

for (int i = 0, j = 5; i <= j; i += 2, j++)
{
    Console.WriteLine("i = {0}, j = {1}", i, j);
}

/* OUTPUT

i = 0, j = 5
i = 2, j = 6
i = 4, j = 7
i = 6, j = 8
i = 8, j = 9
i = 10, j = 10

*/
26 January 2007