for

suggest change

Syntax: for (initializer; condition; iterator)

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 hello1hello12

Live Demo on .NET Fiddle

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents