C# 11 Looping with the for Statement

This chapter will continue looking at flow control in C# code. In the preceding chapters, we have examined using logical expressions to decide what C# code should be executed. Another aspect of control flow entails the definition of loops. Loops are essentially sequences of C# statements that will be executed repeatedly until a specified condition (or conditions) are met.

Why Use Loops?

It is generally common knowledge that computers are great at performing repetitive tasks an infinite number of times and doing so very quickly. It is also common knowledge that computers really don’t do anything unless someone programs them to tell them what to do. Loop statements are the primary mechanism for telling a computer that a sequence of tasks needs to be repeated a specific number of times. Suppose, for example, that you need to add a number to itself ten times. One way to do this might be to write the following C# code:

long j = 1;

j += j;
j += j;
j += j;
j += j;
j += j;
j += j;
j += j;
j += j;
j += j;
j += j;Code language: C# (cs)

While somewhat cumbersome, this does work. What would happen if you needed to perform this task 100 or even 10,000 times? Writing C# code to perform this as above would be prohibitive. Such a scenario is exactly what the for loop is intended to handle.

The syntax of a C# for loop is as follows:

for ( <initializer>; <conditional expression'>; <loop expression> )
{
      statements to be executed
}Code language: C# (cs)

The typically initializes a counter variable. Traditionally the variable i is used for this purpose. For example:

i = 0;Code language: C# (cs)

This sets the counter to be variable i and sets it to zero. Note that if the counter variable has not been previously declared, it may be declared as part of the for statement:

int i = 0;Code language: C# (cs)

The specifies the test to perform to verify whether the loop has been performed the required number of iterations. For example, if we want to loop 100 times:

i < 100;Code language: C# (cs)

Finally, the loop expression specifies the action to perform on the counter variable. For example to increment by 1:

i++; Code language: C# (cs)

The body of statements to be executed on each iteration of the loop is contained within the code block defined by the opening ({) and closing (}) braces.

By bringing this all together we can create a for loop to perform the task outlined in the earlier example:

long j = 1;

for (int i=0; i<50; i++) {
      j += j;
      System.Console.WriteLine ("j = " + j);
}Code language: C# (cs)

C# loop variable scope

A key point to note in creating loops is that any variables defined within the body of a loop are only visible to code within the loop. This is a concept known as scope. If, for example, a variable myCounter is defined within the body of a for loop, that variable ceases to exist once the loop terminates:

// variable myCounter does not yet exist

for (int i = 0; i < 10; i++)
{
       int myCounter = 0; //myCounter variable created in scope of for loop
       myCounter += i;
}

// after loop exit variable myCounter is now out of scope and ceases to existCode language: C# (cs)

Creating an infinite for loop

for loop which will execute an infinite number of times may be constructed using for (;;) syntax. For example, the following code sample will output “Hello from C#” until the program is manually terminated by the user (or the computer is turned off or rebooted):

for (;;)
{
    System.Console.WriteLine ("Hello from C#");
}Code language: C# (cs)

Breaking out of a for loop

Having created a loop, it is possible that under certain conditions, you might want to break out of it before the completion criteria have been met (particularly if you have created an infinite loop). One such example might involve continually checking for activity on a network socket. Once the activity has been detected, it will be necessary to break out of the monitoring loop and perform some other task.

To break out of a loop, C# provides the break statement which breaks out of the current loop and resumes execution at the code directly after the loop. For example:

int j = 10;

for (int i = 0; i < 50; i++)
{
     j += j;

     System.Console.WriteLine ("j = " + j);
 
     if (j > 100)
          break;
}Code language: C# (cs)

In the above example, the loop will continue to execute until the value of j exceeds 100, at which point the loop will exit.

Nested for loops

So far, we have looked at only a single level of for loop. It is also possible to nest for loops where loops reside inside other loops. For example:

for (int i = 0; i < 100; i++) {
     System.Console.WriteLine ( "i = " + i);

     for (int j = 0; j < 10; j++) {
             System.Console.WriteLine ( "j = " + j);
     }
}Code language: C# (cs)

The above example will loop 100 times, displaying the value of i on each iteration. In addition, for each of those iterations, it will loop 10 times, displaying the value of j.

The above example shows two levels of nesting. It is, of course, possible to nest to more levels, though too many levels may result in code that is difficult to understand.

Breaking from nested loops

An important point to be aware of when breaking out of a nested for loop is that the break only exits from the current level of the loop. For example, the following C# code example will exit from the current iteration of the nested loop when j is equal to 5. The outer loop will, however, continue to iterate and, in turn, execute the nested loop:

for (int i = 0; i < 100; i++) {
     System.Console.WriteLine ( "i = " + i);

     for (int j = 0; j < 10; j++) {
        if (j == 5)
            break;
            System.Console.WriteLine ( "j = " + j);
     }
}Code language: C# (cs)

Continuing for Loops

Another useful statement for use in loops is the continue statement. When the execution process finds a continue statement in any kind of loop, it skips all remaining code in the loop’s body and begins execution once again from the top of the loop. Using this technique, we can, for example, construct a for loop that outputs only even numbers between 1 and 9:

for (int i = 1; i < 10; i++) {
     if ((i % 2) != 0)
          continue;
     System.Console.WriteLine ($"i = {i}");
}Code language: C# (cs)

In the example, if i is not divisible by 2 with 0 remaining, the code performs a continue operation, sending execution to the top of the for loop, thereby bypassing the code to output the value of i. This results in only even numbers appearing in the console.

The C# foreach statement

The foreach loop is used to iterate over a sequence of items contained in a collection and provides a simple-to-use looping option.

The syntax of the foreach loop is as follows:

foreach <name> in <collection> {
    // code to be executed
}Code language: C# (cs)

In this syntax, <name> is the name to be used for a constant that will contain the current item from the object through which the loop is iterating. The code in the loop’s body will typically use this constant name to reference the current item in the loop cycle. The <collection> is the object through which the loop is iterating. This could, for example, be an array of string or numeric values (the topic of collections will be covered in greater detail within the course section entitled C# Arrays).

Consider, for example, the following foreach loop construct:

string[] myColors = {"red", "green", "yellow", "orange", "blue"};

foreach (string color in myColors)
{
    System.Console.Write("{0} ", color);
}Code language: C# (cs)

The loop begins by stating that the current item is to be assigned to a constant named color. We then tell the statement that it is to iterate through all of the elements in the myColors array. The loop’s body simply sends a message to the console panel indicating the current value assigned to the color constant.

As we will see in the C# Arrays lesson, the foreach loop is particularly beneficial when working with collections such as arrays and dictionaries.


Categories