0
0
CsharpHow-ToBeginner · 3 min read

How to Use For Loop in C#: Syntax and Examples

In C#, a for loop repeats a block of code a set number of times using a counter variable. It has three parts inside parentheses: initialization, condition, and iteration, which control how many times the loop runs.
📐

Syntax

The for loop syntax in C# has three parts inside parentheses separated by semicolons:

  • Initialization: sets the starting value of the counter.
  • Condition: checked before each loop; if true, the loop runs.
  • Iteration: updates the counter after each loop.

The loop body runs as long as the condition is true.

csharp
for (int i = 0; i < 5; i++)
{
    // code to repeat
}
💻

Example

This example prints numbers from 0 to 4 using a for loop. It shows how the loop starts at 0, checks the condition, runs the code, then increases the counter by 1 each time.

csharp
using System;

class Program
{
    static void Main()
    {
        for (int i = 0; i < 5; i++)
        {
            Console.WriteLine(i);
        }
    }
}
Output
0 1 2 3 4
⚠️

Common Pitfalls

Common mistakes when using for loops include:

  • Forgetting to update the counter, causing an infinite loop.
  • Using the wrong condition, so the loop never runs or runs too many times.
  • Declaring the counter variable outside the loop unintentionally.

Always check the loop condition and counter update carefully.

csharp
/* Wrong: infinite loop because i is not updated */
for (int i = 0; i < 5; )
{
    Console.WriteLine(i);
    // i++ missing here
}

/* Correct: counter updated in iteration part */
for (int i = 0; i < 5; i++)
{
    Console.WriteLine(i);
}
📊

Quick Reference

Remember these tips for using for loops in C#:

  • Initialization runs once before the loop starts.
  • Condition is checked before each iteration; if false, loop ends.
  • Iteration runs after each loop cycle to update the counter.
  • Use int or other numeric types for the counter.
  • Keep loop body simple to avoid errors.

Key Takeaways

A for loop repeats code using initialization, condition, and iteration parts.
The loop runs while the condition is true and updates the counter each time.
Always update the counter to avoid infinite loops.
Use for loops to run code a known number of times.
Check your loop condition carefully to control how many times it runs.