← Back to C# Course | Chapter 4: Control Flow | Lesson 3 of 7

for Loop

A for loop repeats something a set number of times, like doing exactly ten push-ups while counting. You say where to start, when to stop, and how to count.

In this page:

  1. for Loop
Syntax
csharp
for (int i = start; i <= end; i++)
{
    // body
}

for Loop

A for loop repeats a block a known number of times, controlled by an initializer, a condition, and an increment step.

It's the standard choice when you know exactly how many iterations you need, such as walking through indices. All three parts of a for header are optional but conventionally used together.

Note: Use for when you need the loop index itself, not just each element.

Example: for Loop

markup
using System;

class Program
{
    static void Main(string[] args)
    {
        for (int i = 1; i <= 5; i++)
        {
            Console.WriteLine($"Count: {i}");
        }
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using <= with an array length, like i <= arr.Length, which throws IndexOutOfRangeException.
  2. Changing the loop variable inside the loop body and skipping iterations.
  3. Putting a semicolon after for (...);, making the loop body empty.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.