C# Language for


Example

Syntax: for (initializer; condition; iterator)

  • The for loop is commonly used when the number of iterations is known.
  • The statements in the initializer section run only once, before you enter the loop.
  • The condition section contains a boolean expression that's evaluated at the end of every loop iteration to determine whether the loop should exit or should run again.
  • The iterator section defines what happens after each iteration of the body of the loop.

This example shows how for can be used to iterate over the characters of a string:

string str = "Hello";
for (int i = 0; i < str.Length; i++)
{
    Console.WriteLine(str[i]);                
}

Output:

H
e
l
l
o

Live Demo on .NET Fiddle

All of the expressions that define a for statement are optional; for example, the following statement is used to create an infinite loop:

for( ; ; )
{
    // Your code here
}

The initializer section can contain multiple variables, so long as they are of the same type. The condition section can consist of any expression which can be evaluated to a bool. And the iterator section can perform multiple actions separated by comma:

string hello = "hello";
for (int i = 0, j = 1, k = 9; i < 3 && k > 0; i++, hello += i) {
    Console.WriteLine(hello);
}

Output:

hello
hello1
hello12

Live Demo on .NET Fiddle