BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

C# Programming
.NET 1.1+

C# Program Flow Control: The For Loop

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.

Excluding the Loop Control Variable from the Condition

There is no requirement for the loop control variable to be included in a for loop's condition. The following example shows a simple Boolean variable being used as a condition. The loop ends when either the array is full or one of the square values is greater than fifty:

int[] squares = new int[11];
bool finished = false;

for (int i = 0; !finished; i++)
{
    int squareValue = i * i;
    squares[i] = squareValue;
    
    finished = (i == 10) || (squareValue > 50); 
}

Using Incomplete For Loop Definitions

As described above, the for loop includes four sections including the command(s) to be executed. In some cases it is useful to omit one or more sections. Any combination of sections may be left empty, although not providing any of the four items serves no purpose.

The first type of incomplete loop definition is the uninitialised loop. When using an existing variable as the loop control variable, there is no need to initialise first. This is when the initial value may vary due to user input or other conditions. To create the uninitialised loop, leave the first section blank.

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

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

The condition section may be omitted to create an conditionless loop or infinite loop. As there is no predicate, the loop will continue to execute until explicitly stopped or until an exception occurs. This is useful when the number of iterations required is not known or if the conditions that halt the loop are complex. The loop is stopped using the break statement, which is described later in this article.

for (int i=0; ; i++)
{
    Console.WriteLine("Looping, iteration #{0}",i);
}

The previous example creates a loop with a loop control variable acting as a counter. If the loop control variable is not required, an infinite loop can be created using no initialisation, condition or iteration section as shown here:

for (;;)
{
    Console.WriteLine("Looping...");
}

A loop definition does not require an iteration section. Any changes to the loop control variable can be controlled within the loop's command. This is useful where the changes are complex, or when it is difficult or untidy to represent the iteration within the for statement. The following example is simplistic to demonstrate the syntax of such a loop.

int[] squares = new int[11];

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

The final type of incomplete loop is the bodyless loop. In this type of loop, all of the desired functionality is defined within the for statement; no commands are required within the body of the loop. Instead of adding a command or code block, the statement is closed using a semicolon. The following example uses a bodyless loop to calculate the total of the integer values between one and ten. Note that the iteration section increments a counter and increases the running total.

int total = 0;

for (int i = 1; i <= 10; total += i++);

Console.WriteLine("Total = {0}", total);        // Outputs "Total = 55"

Nested Loops

Loops can be nested to create loops within loops. Each time the outer loop iterates, the inner loop is executed in full. The following example uses nested loops to populate the values of a two-dimensional array. Note the inner loop indented to make it easier to identify.

int[,] table = new int[13,13];

// Outer loop
for (int row = 0; row <= 12; row++)
{
    // Inner loop
    for (int col = 0; col <= 12; col++)
    {
        table[row,col] = row * col;
    }
}

Breaking Out of a Loop

During the execution of a for loop (or any other loop structure in C#), it may be necessary to exit immediately. This is always the case for an infinite loop but can be equally useful to end a loop early once its purpose is served. To force the exiting from a loop immediately, the break statement is used.

A good example of the efficient use of the break statement is when searching through a series of data for a specific value. The following example iterates through an array until a string is found. At this point, there is no need to continue processing the loop. The if statement performs the comparison; this conditional processing command will be described in full later in the tutorial.

string[] items = new string[] {"A", "B", "C", "D", "E", "F", "G", "H"};
int pos;

for (pos = 0; pos <= items.Length; pos++)
{
    if (items[pos] == "C")
    {
        break;
    }
}

Console.WriteLine("C is at position {0}", pos); // Outputs "C is at position 2"

The break statement should be used with care as, if overused, it can de-structure your code making it difficult to read. Before using break, consider alternative loop structures. It is important to note that the break statement only exits from the current loop. When using nested loops, a break in the inner loop returns control to the outer loop, which will continue executing as normal.

Completing a Loop Iteration Early

The break statement described above exits a loop completely. Sometimes it is useful to stop the current iteration and continue with the next. This can be achieved using the continue statement. As with the break statement, care should be taken not to de-structure the code by overusing this command.

The following example outputs the odd numbers between zero and one hundred. It achieves this by performing a modulus within an if statement. If the modulus of the loop control variable and the value two is zero the loop control variable is even and is not outputted.

for (int i = 0; i <= 100; i++)
{
    if ((i % 2) == 0) continue;
    
    Console.WriteLine(i);
}
26 January 2007