C# For Loop
Loops through code a set number of times.
C# For Loop
When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop.
Syntax
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.
Foreach Loop
There is also a foreach loop, which is used exclusively to loop through elements in an array or other data collections:
foreach (type variableName in arrayName)
{
// code block to be executed
}
Examples
For Loop Example
Standard for loop 0 to 4.
using System;
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}
}
}Print Even Numbers
Incrementing by 2.
using System;
class Program
{
static void Main(string[] args)
{
for (int i = 0; i <= 10; i = i + 2)
{
Console.WriteLine(i);
}
}
}Foreach Loop
Iterating over an array.
using System;
class Program
{
static void Main(string[] args)
{
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
foreach (string i in cars)
{
Console.WriteLine(i);
}
}
}