C# For Loop Tutorial For Beginners With Examples

C# for loops execute a block of code repeatedly.

Type of for Loops in C#

There are two type of for loops in C#:
  • for loop
  • foreach loop

C# for Loop

A for loop in C# is used when it is known in advance the number of times a code block has to be executed.
The syntax of a for loop is shown below:
for (Initialize; Condition; Increment)
{
    Code to be executed;
}              
  • In the Initialize step a variable is used as a counter and is initialized to a numeric value. The counter variable can be declared in this step or can be declared prior to the start of for loop.
  • The Condition is evaluated in the start of each iteration. If it is true then the iteration continues or else the iteration stops and the code after the for loop executes.
  • After each iteration the counter variable is Incremented.
In the below example a variable icount is initialized to zero and in the start of every iteration is incremented and compared with a numeric constant 10.
In the below example numbers from 0 to 9 will be displayed on the console window.
    for (int icount=0; icount < 10; icount++)
    {
        Console.WriteLine(icount);
    }
    

C# foreach Loop

A foreach loop in C# is used to iterate through an Array or a Collection.
The syntax of a foreach loop is shown below:
foreach (value in Array or Collection)
{
    Code to be executed;
}              
The number of iteration of a foreach loop will be same as the number of items present in the Array or Collection. When an item in an Array or Collection is processed the pointer is moved to the next item and so on. This continues until the last element in the Array or Collection is reached.
The below example displays the name of Planets present in an Array using a foreach loop.
    string[] planetNames = {"Earth","Mercury","Mars"};

    foreach(string name in planetNames)
    {
        Console.WriteLine(name);
    }