Labs ICT
⭐ Pro Login

For Loop

2 min read | C# Tutorial
⭐

Want the full learning experience?

Get structured courses, certificates, projects, and instructor support with LabsICT Pro.

Explore Pro Courses

The for loop is the most classic loop in programming. It packs the initialization, condition, and increment into one compact line. When you know exactly how many times you want to loop, reach for for.

The for Loop

Three parts in the parentheses: start, condition, step. for (int i = 0; i < 5; i++) — set i to 0, run while i is less than 5, add 1 after each round.


using System;

class Program {
  static void Main() {
    for (int i = 0; i < 5; i++) {
      Console.WriteLine("Iteration " + i);
    }
  }
}
    

Counting Backwards

You're not stuck counting up. Decrement with i-- to go backward, or change the step to skip numbers.


using System;

class Program {
  static void Main() {
    for (int i = 10; i >= 1; i--) {
      Console.WriteLine(i);
    }
    Console.WriteLine("Liftoff!");
  }
}
    

Nested for Loops

Put a for inside another for and you get a nested loop. Great for grids, multiplication tables, or anything with rows and columns.


using System;

class Program {
  static void Main() {
    for (int row = 1; row <= 3; row++) {
      for (int col = 1; col <= 3; col++) {
        Console.Write(row * col + " ");
      }
      Console.WriteLine();
    }
  }
}
    

Skipping Parts

You can leave any of the three parts empty. A for with no condition runs forever — same as while (true).


using System;

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