Resources The for Loop

Learning Resources
 

The for Loop


For loops use an iteration variable. They are ideal when looping over many numbers in order with a definite terminating condition. No collection of elements is required. But we can use the variable to index a separate collection. This iteration variable allows more flexibility than for each.

Example
This example program loops using the for-loop construct in the C# language. The name of the variable "i" is a convention. Because of this, it is easier for other programmers to understand than unusual variable names in many cases.

The program shows an increment for-loop, a decrement for-loop, a for-loop that adds two the variable, and a for-loop that subtracts two from the variable. The example shows also the exact output of this program when it is executed in the Common Language Runtime.

using System;

class Program
{
    static void Main()
    {
    //
    // Shows five 'for int i' loops.
    //
    Console.WriteLine("--- For 1 ---");
    for (int i = 0; i < 10; i++)
    {
        Console.WriteLine(i);
    }
    Console.WriteLine("--- For 2 ---");
    for (int i = 10 - 1; i >= 0; i--)
    {
        Console.WriteLine(i);
    }
    Console.WriteLine("--- For 3 ---");
    for (int i = 0; i < 10; i += 2)
    {
        Console.WriteLine(i);
    }
    Console.WriteLine("--- For 4 ---");
    for (int i = 10 - 1; i >= 0; i -= 2)
    {
        Console.WriteLine(i);
    }
    Console.WriteLine("--- For 5 ---");
    for (int i = 0; i < (20 / 2); i += 2)
    {
        Console.WriteLine(i);
    }
    }
}

Output

--- For 1 ---
0
1
2
3
4
5
6
7
8
9
--- For 2 ---
9
8
7
6
5
4
3
2
1
0
--- For 3 ---
0
2
4
6
8
--- For 4 ---
9
7
5
3
1
--- For 5 ---
0
2
4
6
8

The for-loop construct is followed by parentheses with three statements separated by semicolons. When the for-loops are encountered, the first of the three statements is executed. The for-loop shown first in the example will first has its "int i = 0" statement executed. The loop will start with its iteration variable set to zero.

 

 For Support