Utilizor
Contact Us

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);
    }
  }
}

Nested Loops

Loop inside a loop.

using System;

class Program
{
  static void Main(string[] args)
  {
    for (int i = 1; i <= 2; ++i) 
    {
      Console.WriteLine("Outer: " + i);
      for (int j = 1; j <= 3; j++) 
      {
        Console.WriteLine(" Inner: " + j);
      }
    }
  }
}

Decreasing Loop

Loop counting backwards.

using System;

class Program
{
    static void Main()
    {
        for (int i = 5; i > 0; i--)
        {
            Console.WriteLine(i);
        }
    }
}