C# Tutorials
C# Methods
C# Classes
C# Examples
If you know exactly how many times you want to enter a code block, use a for loop instead of a while loop:
for (statement 1; statement 2; statement 3)
{
// code block to be executed
}
Statement 1 is executed (one time) before the execution of the code block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been executed.
The example below will print numbers 0 to 4:
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}
This example will only print equal values between 0 and 10:
for (int i = 0; i <= 10; i = i + 2)
{
Console.WriteLine(i);
}
There is also a foreach loop, which is only used to loop through in the array:
foreach (type variableName in arrayName)
{
// code block to be executed
}
The following example removes all elements from the cars array, using a foreach loop:
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
foreach (string i in cars)
{
Console.WriteLine(i);
}