C# For Loops

For loop

For loops use an iteration variable. They are ideal when you want to loop over many numbers in order with a definite terminating condition. No collection of elements is required, but you can use the variable to index a separate collection. This iteration variable allows more flexibility than foreach.

These C# examples use the for-loop. For uses an index value. It has special syntax.

Example

Note

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

The program demonstrates 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 also shows the exact output of this program when it is executed in the Common Language Runtime.

Program that uses for "int i" 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

Overview. 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. You can start the for-loops with any value for the iteration variable.

Lowercase i

Checking int against value. The second part of the for-statements checks against a condition. It is checked before the loop body is ever executed the first time. Also, this condition is checked after each iteration through the loop has completed. In the first loop shown, the expression "i < 10" is evaluated and if this is true, the loop proceeds. If it is false, the loop terminates before the next iteration.

True False

Variable after every iteration. 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. 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 by adding one, adding one, subtracting one, subtracting one, adding two, and subtracting two. This iteration-expression is evaluated after the loop body statements are executed each time.

Loop 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. However, if the variable is used to access an array, you can change the name to a more descriptive word to indicate its purpose.

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: Book Review

For-loop compilation

Programs commonly spend most of their time in tight loops such as for-loops, and compilers put considerable effort into speeding up these constructs. Fields of mathematics such as linear algebra can be used to analyze data reuse and data dependence in two for-loops to improve performance by understanding what optimizations are safe to make. Compilers also use techniques such as strength reduction to improve performance of affine expressions based on the loop iteration variables in these loops.

Dragon Book: Compilers

More

.NET Framework information

For-loops are extremely common and useful in many algorithms and methods in the C# language, and they can be found in many functions in the .NET Framework internals as well. We provide specific usages of the for-loop that are applicable in real-world C# programs.

2D Array Loop Example Loop Over String Array Loop Over String Chars String For-Loop

Performance

Just-in-time compiler (JIT)

There are performance factors related to the for-loop in the C# language. 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.

If the JIT compiler detects that you are accessing an array in a for-loop and the loop iteration variable will never be out-of-bounds for that array, it can remove array bounds checking automatically. Because of this, the simplest for-loops with no manual optimizations are sometimes the fastest.

Summary

The C# programming language

We looked at the for-loop and the "int i" variable in the C# programming language and saw how this pattern can be used to loop forward through a series of numbers, backwards through numbers, and also through larger intervals at once. We noted examples of the for-loop in the .NET Framework and some compiler optimizations.

Loop Constructs
.NET