C# Tutorial - Dissecting Our Second Application – for Loops


We could implement the same functionality of the foreach loop using the more commonly used iteration statement, for, like this;

using System;
using System.Collections.Generic;
using System.Text;

namespace App02
{
  class Program
  {
    static void Main(string[] args)
    {
      for (int i = 0; i < args.Length; i++)
      {
        Console.WriteLine("Hello " + args[i]);			 
      }

      Console.Read();
    }
  }
}

The for loop is used to iterate over a block of code a fixed number of times until a terminating condition is achieved. The three fields of the for statement are normally used for initialization, testing for termination, and incrementing of a local variable.

In our case the first statement creates a local variable (an integer called i)and initializes it to have a value of zero. The second statement checks to see if the value of i is less than the number of elements in the array args. Finally the third statement increments i every time that the end of the loop has been reached.

In comparison to the foreach loop, the for loop requires an extra local variable to be used plus the array is then accessed dependant upon the value of the local variable.

Iteration Statement - for

The for loop executes a statement or a block of statements repeatedly until a specified expression evaluates to false. The loop is always declared in the following manner:

for( initializer ; condition ; iterator )
{
  embedded-statements;
}

Where:

  • The optional initializer component consists of a local-variable declaration. The local variable may be created inside or outside of the for loop. If it is created within the loop declaration, then it is valid for use only within the confines of the for loop itself.

  • The optional condition component is a boolean expression that evaluates to either true or false.

  • The optional iterator component is a statement to be run every time the loop body is completed. This is usually an increment of the local-variable.

A simple example to print the numbers 1 to 10 would be:

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

Would output

1,2,3,4,5,6,7,8,9,10,

No Parameters

If no condition is supplied, then the loop will run forever. So the following code would give an infinite loop.

for (;;)
{
  // ...
}

Multiple Parameters

Each of the statements may be supplied with more than one statement separated by commas. The following example shows this.

for( int high = 50, int low = 0; high >= low; high--, low++)
{
  // ...
}

<< Previous Contents Next >>

© Publicjoe, 2008