Start learning free

LESSON 118 OF 347 · WHILE LOOPS & FOR LOOPS

The For Loop in C#: Initialization, Condition, Iteration

Lesson Read the full explanation

There is a more powerful way to use the for loop in C#.

For loops can be declared with three optional expressions separated by semicolons:

for (initialization; condition; iteration) {
	instruction1;
	instruction2;
	...
}

Let's break down each component:

  • The initialization statement is executed one time only before the loop starts and is typically used to define and set up the iterator variable.

  • The condition statement is evaluated at the beginning of every loop iteration and will continue as long as it evaluates to true. When the condition is false at the start of the iteration, the loop will stop executing.

  • The iteration statement is executed at the end of each loop iteration, prior to the next condition check and is usually used to update the iterator variable.


Example:

for (int i = 0; i < 4; i++) {
	Console.WriteLine("Hello world!");
}

// This code prints "Hello world!" on four different lines

Let's break down this code:

  • The initialization statement is int i = 0. We create and initialize the iterator variable i so the loop starts counting from 0.

  • The condition statement is i < 4, meaning the loop will run as long as the iterator variable, i, is less than 4.

  • The iteration statement is i++. This means that after each iteration, after running the code inside {}, i will get increased by 1.


This is what the computer does behind the scenes during this loop:

0. Creates and initializes a variable i = 0

1. First iteration:
	a. Is i < 4 true? <=> Is 0 < 4 true? Yes. 
	b. Run the code inside {}. Print "Hello World".
	c. i++ => i = 1
	
2. Second iteration:
	a. Is i < 4 true? <=> Is 1 < 4 true? Yes. 
	b. Run the code inside {}. Print "Hello World".
	c. i++ => i = 2
	
3. Third iteration:
	a. Is i < 4 true? <=> Is 2 < 4 true? Yes. 
	b. Run the code inside {}. Print "Hello World".
	c. i++ => i = 3
	
4. Forth iteration:
	a. Is i < 4 true? <=> Is 3 < 4 true? Yes. 
	b. Run the code inside {}. Print "Hello World".
	c. i++ => i = 4

5. Fifth iteration:
	a. Is i < 4 true? <=> Is 4 < 4 true? No.
	b. Exit the loop.

Assignment

Let's print "I promise to learn coding." 5 times using a for loop.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 2
    Ctrl + Enter to check

    C# · WHILE LOOPS & FOR LOOPS

    The For Loop in C#, explained

    Why the for loop exists

    Most loops that count follow the same pattern: set a variable, test it, change it. A while loop spreads those three jobs over different lines. The classic for loop puts them in one header, so you can see how the loop counts at a glance.

    The syntax

    for (initialization; condition; iteration) {
        // body
    }
    

    The three parts are separated by semicolons and run at different times:

    • Initialization runs once, before the loop starts. It usually declares the counter, such as int i = 0.
    • Condition is checked before every pass, including the first. While it is true the body runs. When it is false, the loop ends.
    • Iteration runs after every pass of the body, before the next condition check. It usually updates the counter, such as i++.

    A first example

    for (int i = 0; i < 4; i++) {
        Console.WriteLine("Hello world!");
    }
    

    This prints Hello world! four times. The order of events is:

    1. i is created with the value 0.
    2. Is 0 < 4? Yes, so the body runs, and then i++ makes i equal to 1.
    3. The same check and body repeat for i equal to 1, 2 and 3.
    4. After the pass with i equal to 3, i++ makes it 4. Is 4 < 4? No, so the loop ends.

    Starting at 0 and using < with the number of repetitions is the usual way to run a body exactly that many times. The counter takes the values 0, 1, 2 and 3, which is four passes.

    Scope of the counter

    A variable declared in the initialization part exists only inside the loop. Using i after the closing brace is a compile error. If you need the final value later, declare the variable before the loop and leave the initialization part empty or assign to the existing variable.

    The exercise: a promise, five times

    The lesson asks you to print "I promise to learn coding." five times. It has two steps.

    1. Write the loop header. Declare int i = 0, keep going while i < 5, and increase with i++. The counter runs through 0, 1, 2, 3, 4, which is five values.
    2. Print inside the body. Call Console.WriteLine with the message. The body runs once per value of the counter, so one line of code produces five lines of output.
    for (int i = 0; i < 5; i++) {
        Console.WriteLine("I promise to learn coding.");
    }
    

    Common mistakes

    • Commas instead of semicolons. The header needs exactly two semicolons: for (int i = 0, i < 5, i++) does not compile.
    • Off-by-one errors. i <= 5 from 0 prints six times, and i < 5 from 1 prints four times. Count the values the counter takes.
    • A semicolon after the header. for (...); makes the loop body empty, and the braces below it run once, after the loop. The compiler usually warns about a possible mistaken empty statement.
    • Updating the counter in the wrong direction. A condition that never becomes false produces an infinite loop.
    • Lowercase method names. C# is case-sensitive: it is Console.WriteLine, not console.writeline.

    Looping over an array's positions

    The same header walks through the positions of an array. Positions start at 0 and the last one is Length - 1, so i < nums.Length is the natural condition:

    int[] nums = {4, 8, 15};
    for (int i = 0; i < nums.Length; i++) {
        Console.WriteLine(nums[i]);
    }
    

    This prints 4, 8 and 15. Using <= here would try to read nums[3] and throw an IndexOutOfRangeException.

    Every part is optional

    Each of the three parts can be left empty, but the semicolons stay. for (;;) has no condition, which C# treats as always true, so it loops until a break or a return leaves it. Beginners rarely need this form; the full three-part header is clearer.

    Key takeaways

    • A for header has three parts: initialization (once), condition (before every pass) and iteration (after every pass).
    • for (int i = 0; i < n; i++) runs the body exactly n times.
    • The counter declared in the header is only visible inside the loop.
    Keep going with C#About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free