The for Statement


The for statement has the following form:

for (initialization; condition; iteration)
 statement;

where:

The initialization statement is usually a declaration and/or assignment that sets the initial value of a loop control variable whose value is tested by the condition. For example, to add the numbers from 0 through to 99, the following may be used.

int j=0;
for (int i=0; i<100; i++)
 j += i;

The integer i is declared and initialized in the initialization section of the loop. The termination condition is i<100. This condition is tested before each iteration. When the condition becomes false, the loop is terminated and execution resumes at the first statement after the loop. It is possible that the condition is initially false, whereby the loop will not be executed at all. For the case at hand, the statement i++ increments the loop variable and this is done at the end of each iteration of the loop.

The next program prints out the primes less than 100. This program is redone later using arrays. This program makes no use of arrays.

// Primes - Calculate the Primes Less than 100

using System;

class Program
{
    static void Main()
    {
        for (int i = 2; i < 100; i++)
        {
            bool IsPrime = true;
            int limit = (int)Math.Sqrt(i);
            
            for (int j = 2; j <= limit; j++)
                if (i % j == 0)
                {
                    IsPrime = false;
                    break;
                }

            if (IsPrime)
                Console.WriteLine("{0} is prime", i);
        }
    }
}

The output of this program is shown below.

2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime

It is possible to leave out any or all of the initialization, condition or iteration portions of a loop. For example:

for (int i=0; i<10; )
 {
  i++;
 }

is a valid for loop that will terminate correctly. Indeed, this example can be further modified to form the following example.

int i=0;
for (; i<10 ;)
 {
  i++;
 }

At this stage, the for loop resembles a while loop, which would probably be used instead. Yet another variation is the infinite loop, which is shown below.

int i=0;
for (;;)  // loop for ever
 {
  i++;
  if (i == 100) break;  // manually break out of the infinite loop at this point
 }

This infinite loop would continue to execute forever except that a statement manually breaks out of the loop. Such constructs are often very useful in programming.

Often the iteration portion of the loop has side effects. Another variation of a loop is where the side effects are all that is required and the loop therefore has no body. Consider the next example.

// ForNoBody - A For Loop with No Body - Sum 1 to 99.
//           - Side effects are all that is required.


using System;

class Program
{
    static void Main()
    {
        int j = 0;
        for (int i = 0; i < 100; j += i++) ;
        Console.WriteLine("Sum of 1 to 99 is: {0}", j);
    }
}

The output of the program is as follows.

Sum of 1 to 99 is: 4950

The iteration portion of the for loop is:

j += i++

and this statement has two side effects:

  1. i is incremented by 1 and
  2. the previous value of i is added to j.

In effect, the side effects perform the calculation and no body for the loop is required.