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.

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. In the real world, this type of program is useful only for the most basic tasks. For complex software program flow control statements are necessary.

Program flow control statements can be divided into four categories:

  • Loops. Loops allow a section of code to be executed repeatedly until a condition is met. A loop structure is the focus of this article.
  • Conditional Processing. Conditional processing statements and structures permit code to be executed when conditions are met. We'll look at these later.
  • Jumps. Jump statements are simple commands that 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 presenting the user with an error and halting execution, they should be handled. Exception handling statements allow this. They will be described in a later article.

The For Loop

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

int i;
string numbers = "";

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

To understand the example, we need to examine the syntax of the for loop. The 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 will be used as a counter or loop control variable. In the example above, the counter 'i' is initialised with one, which is the first digit to add to a string. The initialisation section is closed with a semicolon (;).

The second section is called the condition. This is a Boolean predicate that must be true in order for the code within the loop to be executed. If the condition is false before the loop has executed once, the code in the loop is skipped. In our example, the condition is 'i<=5'. Therefore, the code will execute whilst 'i' remains at or below five. Once this limit is exceeded, the loop stops executing and control passes to the statement following the loop. The condition section is closed with a semicolon (;).

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

The initialisation, condition and iteration sections control how the loop will operate at run-time. These three elements make up the for statement and are enclosed in parentheses. The command to be executed during each iteration follows. In the case of our example, the command appends 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 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