Understanding C#'s `for` Loop: Iterating a Specific Number of Times

This tutorial provides a comprehensive guide to C#'s `for` loop, explaining its syntax, components (initializer, condition, iterator), and how to use it for iterative execution of code blocks. It also covers nested `for` loops and provides examples for practical application.



Understanding C#'s `for` Loop

The `for` loop in C# is a control flow statement used to iterate over a block of code a specific number of times. It's ideal for situations where you know the number of iterations in advance.

`for` Loop Syntax


for (initializer; condition; iterator) {
    // Code to be executed repeatedly
}

The `for` loop has three parts:

  • initializer: Executed once at the beginning of the loop (usually to declare and initialize a counter variable).
  • condition: Checked before each iteration; if true, the loop continues; otherwise, it stops.
  • iterator: Executed after each iteration (usually to increment or decrement the counter).

Example 1: Simple `for` Loop

This example prints numbers 1 through 10:


for (int i = 1; i <= 10; i++) {
    Console.WriteLine(i);
}

Example 2: Nested `for` Loops

Nested `for` loops involve placing one `for` loop inside another. The inner loop completes all its iterations for every single iteration of the outer loop.


for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 3; j++) {
        Console.WriteLine($"{i} {j}");
    }
}

Example 3: Infinite `for` Loop

An infinite `for` loop is created by omitting the loop condition. It runs indefinitely until manually stopped (e.g., using Ctrl+C in the console).


for (;;) {
    Console.WriteLine("Infinite loop!");
}