Home About Lessons Blog On The Mic Contact Projects
Lessons BASIC · C#

C# Basics — For Loop

8 min read · Emre Ulutabak
1
What is a loop?

In life, you repeat some actions again and again. When climbing stairs, you make the same movement on every step. The only difference is that you do it many times.

Software works the same way. When an operation needs to be repeated, instead of writing the same code manually, you use a loop.

csharp
for (int i = 1; i <= 3; i++)
{
    Console.WriteLine("Merhaba!");
}
💡
A loop repeats the same action in a controlled way.
2
Why is it used?

If you want to print something 10 times, you could write 10 lines. But that is both repetitive and messy.

With a for loop, you can write repetitive tasks in a shorter, cleaner, and more manageable way.

3
The structure of for

A for loop usually has three parts: initialization, condition, and increment.

First, a counter is created. Then the condition is checked. After each round, the counter is updated.

csharp
for (int i = 0; i < 5; i++)
{
    Console.WriteLine(i);
}
💡
Here, i starts at 0, the condition is checked, the code runs, and then i increases by one.
4
Counter logic

In loops, the counter variable is often called i. It tracks how many times the loop has run.

There is nothing magical about i; it is just a common convention. You can name it differently, but short and simple names are usually preferred.

csharp
for (int sayi = 1; sayi <= 5; sayi++)
{
    Console.WriteLine($"Tur: {sayi}");
}
💡
The counter variable is the heart of the loop. It determines how far and how many times it runs.
5
Golden rules

Loops are powerful, but if used carelessly they can cause errors. Infinite loops and incorrect counter logic are especially common problems.

💡
Write the condition carefully. A wrong condition can cause the loop to never run or run too many times.
💡
Do not forget to update the counter. Otherwise, the loop may get stuck.
💡
Only put the code that truly needs to repeat inside the loop. Avoid unnecessary clutter.
MINI QUIZ
Which of the following is correct?
A for loop only runs once
A for loop is used to manage repetitive tasks
No condition is written inside a for loop
The counter variable must be named x