BlackWasp
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.

What is Program Flow Control?

So far in the C# Fundamentals tutorial we have concentrated on data types, operators and simple functions. All of these were described with examples that were executed in a linear fashion. That is, execution began at the first line of code and progressed through line-by-line until the end of the example was reached. In the real world, this type of program is very rare for anything except the most basic tasks. For complex software program flow control statements are a necessity.

Program flow control statements can be divided into four categories:

  • Loops. Loops allow a defined section of code to be executed multiple times until a condition is met. A loop structure is the main focus of this article.
  • Conditional Processing. Conditional processing statements and structures permit code to be executed only when certain defined conditions are met. These statements will be the topic for a later article in the tutorial.
  • Jumps. Jump statements are simple commands that can be used to immediately transfer the control of a program to another statement. The break and continue jump statements are described in this article. The infamous goto statement will be considered later.
  • Exception Handling. When exceptions occur, rather than simply presenting the user with an error and stopping execution of the program, they should be handled. Exception handling statements provide this capability and will be described in a later article in this tutorial.

The For Loop

The first loop to examine is the for loop. This is a very powerful structure and is possibly the most utilised form of loop. In its most basic form, it provides a variable that simply counts the number of iterations that the loop should perform. Let us start with such an example:

int i;
string numbers = "";

for (i = 1; i <= 5; i++)
    numbers += i.ToString();
    
Console.WriteLine(numbers);                     // Outputs: "12345"

To fully understand the example, we need to examine the syntax of the for loop. The basic syntax is as follows:

for (initialisation; condition; iteration) command;

The initialisation section of the for statement is generally used to assign an initial value to a variable that can then be used as a counter or loop control variable. In the example above, the counter variable 'i' is initialised with one, which is to be the first digit to add to a string. The initialisation section is closed with a semicolon character (;).

The second section of the for statement is called the condition. This is a Boolean condition that must be met in order for the code within the loop to be executed. If the condition is broken before the loop has executed once, the code in the loop is never executed. In our example, the condition stated is 'i<=5'. This means that the code will continue to execute as long as the value of 'i' remains at or below five. Once this limit is exceeded, the loop stops executing and control passes to the statement immediately following the loop. The condition section is closed with a semicolon character (;).

The iteration section of the for statement contains a command that is executed on the completion of each iteration of the loop. In the example, the counter variable is incremented by one after each iteration. The result of this is that the code within the loop is executed five times with the value in 'i' increasing each time.

The initialisation, condition and iteration sections control how the entire loop will operate at run-time. These three elements make up the for statement and are enclosed in parentheses. The command to be executed for each iteration of the loop then follows. In the case of our example, the command is to append a string representation of the counter to another string that finally contains the text "12345".

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 C# Fundamentals tutorial, a code block logically groups several commands together and permits them to be used as a single entity. Therefore, in order to create a loop that contains more than one command, a code block should be used by surrounding the group of statements with the brace characters, { and }. The following example uses this example 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 only for that iteration. Once the loop restarts, the variable is destroyed and must be recreated. This means that the variable is not available outside the code block. Of course, if the variable is required to be accessible outside of the loop or persist between iterations, it can be declared 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. This means that 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 will cause the loop condition to be broken. In many cases, the loop control variable is required only for the duration of the loop's execution. Where this is the case, the loop control variable may be declared within the initialisation section of the for statement. On completion of the loop, the variable is destroyed and 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 is not limited to having a single control variable. It is possible to include two or more control variables, each with independent initialisation and iteration information. Any combination of these may then be included within the condition section of the for loop. The following example uses two loop control variables. Note that the initialisation and iterations sections are separated using commas.

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

*/

Excluding the Loop Control Variable from the Condition

The condition section of a for loop defines a Boolean condition that must be met to allow a new iteration to begin. However, there is no requirement for the loop control variable to be included in the condition. The following example shows a simple Boolean variable being used as a condition and ending the loop 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 within the body of the loop. However, in some cases it is useful to omit one or more of these sections. In fact, any combination of these sections may be left empty, although not providing any of the four items serves no purpose.

The first type of incomplete loop definition to consider is the uninitialised loop. When using an existing variable as the loop control variable, there is no need to initialise first. This can be useful when the initial value may vary due to user input or other conditions. To create the uninitialised loop, the first section is simply left blank. The first character within the parentheses is therefore a semicolon.

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

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

The condition section of the for statement may be omitted to create an conditionless loop or infinite loop. As there is no condition to be broken, the loop will continue to execute until explicitly stopped or until an exception occurs. This can be useful when the number of iterations required is not immediately known or if the conditions that cause the halting of the loop are very complex. The method for stopping the execution is 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. The iteration changes to the loop control variable may be controlled internally within the loop instead. This can be useful where the changes are more complex, or when it is difficult or untidy to represent the iteration within the for statement itself. 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 definitions to examine is the bodyless loop. In this type of loop, all of the desired functionality is defined within the for statement meaning that no commands are required within the body of the loop. Instead of adding a command or code block, the statement is simply closed using a semicolon. The following example uses a bodyless loop in order to calculate the total of all of the integer values from one to ten. Note that the iteration section not only increments a counter but also increases the running total value.

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 a loop within a loop. Each time the outer loop iterates, the inner loop is executed in full. The following example shows the principle of nested loops to populate the values of an entire two-dimensional array of multiplication tables. Note the optional indentation of the inner loop that is included 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 when using an infinite loop but can be equally useful to end a loop early once its purpose is served. This can also lead to the program executing more quickly. 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 the required 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 and immediately understand. Before using break, other alternative loop structures should be considered. 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. The outer loop(s) will continue executing as normal.

Completing a Loop Iteration Early

The break statement described above exits a loop completely. Sometimes it is useful to simply exit the current iteration of a loop 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 all of 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 then the loop control variable must be even and is therefore not outputted.

for (int i = 0; i <= 100; i++)
{
    if ((i % 2) == 0) continue;
    
    Console.WriteLine(i);
}
Link to this Page26 January 2007
RSS RSS Feed