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:
iis created with the value 0.- Is
0 < 4? Yes, so the body runs, and theni++makesiequal to 1. - The same check and body repeat for
iequal to 1, 2 and 3. - After the pass with
iequal to 3,i++makes it 4. Is4 < 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.
- Write the loop header. Declare
int i = 0, keep going whilei < 5, and increase withi++. The counter runs through 0, 1, 2, 3, 4, which is five values. - Print inside the body. Call
Console.WriteLinewith 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 <= 5from 0 prints six times, andi < 5from 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, notconsole.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
forheader has three parts: initialization (once), condition (before every pass) and iteration (after every pass). for (int i = 0; i < n; i++)runs the body exactlyntimes.- The counter declared in the header is only visible inside the loop.