for Loop (C#)
The basic syntax of a for loop, which repeats a block of code a specified number of times. In C#, the for statement declares three expressions separated by semicolons — an initializer, a condition, and an iterator — and executes the block repeatedly as long as the condition is true.
Syntax
The basic form and common patterns of the for statement.
for (initializer; condition; iterator) {
// Executes repeatedly while the condition is true.
}
// Count up (from 0 up to but not including n) — the most common pattern.
for (int i = 0; i < n; i++) {
// i takes the values 0, 1, 2, ... n-1 in order.
}
// Count down (from n-1 down to 0).
for (int i = n - 1; i >= 0; i--) {
// i takes the values n-1, n-2, ... 0 in order.
}
// Changing the step (example: increment by 2).
for (int i = 0; i < n; i += 2) {
// i takes the values 0, 2, 4, ... in order.
}
// Use break to exit the loop early.
for (int i = 0; i < n; i++) {
if (condition) {
break; // Exits the entire loop.
}
}
// Use continue to skip the rest of the current iteration.
for (int i = 0; i < n; i++) {
if (condition) {
continue; // Skips the remaining code in this iteration and moves to the next.
}
}
Role of Each Part
| Part | Timing | Description |
|---|---|---|
| Initializer | Once before the loop starts | Declares and initializes the counter variable. Multiple variables can be listed with commas. |
| Condition | Before each iteration | An expression that returns a bool. The loop ends the moment it becomes false. If omitted, the loop runs indefinitely. |
| Iterator | After each iteration | Increments or decrements the counter. Common forms include i++, i--, and i += 2. Multiple expressions can be listed with commas. |
Sample Code
ForLoopBasic.cs
Demonstrates count-up, count-down, step change, break, and continue.
using System;
class ForLoopBasic {
static void Main() {
Console.WriteLine("=== Processing Start ===");
for (int i = 1; i <= 5; i++) {
Console.WriteLine("Processing " + i + " complete");
}
Console.WriteLine("\n=== Reverse Order ===");
string[] items = { "item_a", "item_b", "item_c", "item_d", "item_e" };
for (int i = items.Length - 1; i >= 0; i--) {
Console.WriteLine((i + 1) + ": " + items[i]);
}
Console.WriteLine("\n=== Even Indices Only ===");
for (int i = 0; i < items.Length; i += 2) {
Console.WriteLine("items[" + i + "] = " + items[i]);
}
Console.WriteLine("\n=== Searching for item_c ===");
for (int i = 0; i < items.Length; i++) {
Console.WriteLine("Checking " + items[i] + "...");
if (items[i] == "item_c") {
Console.WriteLine("Found item_c! Search complete.");
break; // Exit the loop.
}
}
Console.WriteLine("\n=== Filtering (excluding item_a) ===");
for (int i = 0; i < items.Length; i++) {
if (items[i] == "item_a") {
continue; // Skip this iteration and move to the next.
}
Console.WriteLine(items[i]);
}
}
}
This produces the following output:
dotnet script ForLoopBasic.cs === Processing Start === Processing 1 complete Processing 2 complete Processing 3 complete Processing 4 complete Processing 5 complete === Reverse Order === 5: item_e 4: item_d 3: item_c 2: item_b 1: item_a === Even Indices Only === items[0] = item_a items[2] = item_c items[4] = item_e === Searching for item_c === Checking item_a... Checking item_b... Checking item_c... Found item_c! Search complete. === Filtering (excluding item_a) === item_b item_c item_d item_e
NestedForLoop.cs
Nested loops and two patterns for breaking out of them: a bool flag and method extraction.
using System;
class NestedForLoop {
static void Main() {
// C# does not have labeled break.
// To break out of nested loops at once, use a bool flag or extract the loop into a method.
string[] items = { "item_a", "item_b", "item_c" };
int[] scores = { 90, 80, 120 };
Console.WriteLine("=== Score Check ===");
for (int i = 0; i < items.Length; i++) {
Console.WriteLine(items[i] + ": Score " + scores[i]);
}
// Find the first item whose score exceeds the target.
Console.WriteLine("\n=== Searching for Score above 90 ===");
int targetScore = 90;
bool found = false; // Discovery flag.
for (int i = 0; i < items.Length; i++) {
for (int j = 0; j < scores.Length; j++) {
if (i == j && scores[j] > targetScore) {
Console.WriteLine("Found: " + items[i] + " (Score: " + scores[j] + ")");
found = true;
break; // Exit the inner loop.
}
}
if (found) {
break; // Exit the outer loop as well (escaping nested loops via flag).
}
}
// Using return lets you exit regardless of nesting depth.
string result = FindMatch(items, scores, targetScore);
Console.WriteLine("\n=== Method Extraction Pattern ===");
Console.WriteLine(result);
}
// Extracting the nested loop into a method lets you escape with return.
static string FindMatch(string[] names, int[] values, int threshold) {
for (int i = 0; i < names.Length; i++) {
for (int j = 0; j < values.Length; j++) {
if (i == j && values[j] > threshold) {
return names[i] + " was the first to meet the condition (Score: " + values[j] + ")";
}
}
}
return "No item met the condition.";
}
}
This produces the following output:
dotnet script NestedForLoop.cs === Score Check === item_a: Score 90 item_b: Score 80 item_c: Score 120 === Searching for Score above 90 === Found: item_c (Score: 120) === Method Extraction Pattern === item_c was the first to meet the condition (Score: 120)
Common Mistakes
Off-by-one errors
Confusing < with <= makes the loop run one too many or one too few times. This can lead to an IndexOutOfRangeException when accessing array elements.
int[] arr = { 10, 20, 30 };
// Wrong: i <= arr.Length accesses arr[3], which throws an exception.
for (int i = 0; i <= arr.Length; i++) {
Console.WriteLine(arr[i]); // IndexOutOfRangeException when i == 3
}
// Correct.
for (int i = 0; i < arr.Length; i++) {
Console.WriteLine(arr[i]);
}
Infinite loop from a missing iterator
Forgetting the iterator expression (such as i++) causes the condition to remain true forever, resulting in an infinite loop.
for (int i = 0; i < 10; ) {
Console.WriteLine(i); // i stays at 0 and the loop never ends.
}
Some IDEs warn about a missing iterator. If you intentionally omit it (e.g., when incrementing inside the loop body based on a condition), add a comment to clarify the intent.
Overview
The C# for statement is characterized by its three semicolon-separated expressions: an initializer, a condition, and an iterator. Because C# does not have labeled break, the common approaches for breaking out of nested loops at once are to use a bool flag or to extract the loop logic into a method and escape with return.
The loop variable i is scoped to the for block. If you need the value of i after the loop ends, declare the variable outside the for statement.
If you only need to iterate through a collection (array or list) in order, foreach is simpler to write. Use foreach when the index is not needed, and for when you need the index, reverse order, or a custom step. For functional iteration with LINQ, see Enumerable.Where and Enumerable.Select.
If you find any errors or copyright issues, please contact us.