C# For

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.

Collections

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.

Loop

So:We see an increment for-loop, a decrement for-loop, a for-loop that adds two and a for-loop that subtracts two.

Also:The example shows the exact output of this program when it is executed in the Common Language Runtime.

Program that uses for loops: C#

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
Int keyword

When the for-loops are encountered, the first of the three statements is executed. The for-loop shown first in the example has its "int i = 0" statement executed. The loop starts with its iteration variable set to zero.

Tip:You can start the for-loops with any value for the iteration variable. The value does not need to be a constant.

Lowercase i

The second part is evaluated before the loop body is initially executed. This condition is also checked after each iteration through the loop. In the first loop, the expression "i < 10" is evaluated. If this is true, the loop proceeds.

But:If it is false, the loop terminates before the next iteration. The loop body statements are not reached again.

True, False

The third part of the for-statements specifies how the iteration variable (i) changes after each successful iteration. The loop body is executed after checking the condition in the second part of the for-loop.

Iterate

Then:After the loop body has been executed for the first time, the iteration variable is changed according to this expression.

The expressions i++, ++i, i-­-, -­-i, i += 2 and i -= 2 change the variable. They add one, add one, subtract one, subtract one, add two and subtract two. The iteration-expression is evaluated after the loop body statements.

Variable names

Code Complete

When you are using very simple loops where the iteration variable is not used in additional logic, a simple name such as 'i' is good. It is standard, short and easy to type and remember.

But:If the variable is used to access an array, you can change the name to a more descriptive word to indicate its purpose.

Also, the name 'i' has no importance to the language or the compiler's understanding of the program. You can find detailed help on loop variable names in Code Complete by Steve McConnell.

Code Complete

Compilers

Framework: NET

Programs commonly spend most of their time in tight loops such as for-loops. Compilers put considerable effort into speeding up these constructs. This is worthwhile. The bulk of program execution is spent in loops.

Fields of mathematics such as linear algebra can be used to analyze data reuse and data dependence in two for-loops. This helps improve performance by determining what optimizations are safe to make.

Also:Compilers use techniques such as strength reduction to improve performance of affine expressions based on iteration variables.

Dragon Book: Compilers

Usage

Framework: NET

For-loops are common and useful in many algorithms and methods in the C# language. They are found in many functions in the .NET Framework internals as well. We provide examples in real-world C# programs.

2D Array LoopsLoop, String ArrayLoop Over String CharsString For-Loop

Performance

Just-in-time compiler: JIT

There are performance factors related to the for-loop. The for-loop is often the fastest way to loop over a series of numbers as it does not require allocations on the managed heap and is easy for the compiler to optimize.

The JIT compiler can detect that you are accessing an array in a for-loop, and that the loop iteration variable will never be out-of-bounds for that array. It can then automatically removes array bounds checking.

And:Because of this, the simplest for-loops with no manual optimizations are sometimes the fastest.

Summary

C# programming language

We looked at the for-loop and the "int i" variable in the C# language. This pattern is used to loop forward through a series of numbers, backwards through numbers, and also through larger intervals at once.

Review:We noted examples of the for-loop in the .NET Framework. We explored some compiler optimizations.


C#: Loop