A C# for loop repeats a statement or block while a Boolean condition is true: for (int i = 0; i < 5; i++) { ... } runs the body five times, with i going from 0 to 4. When you only need each element of a collection and not a counter, C# also has the foreach loop.
for (int i = 0; i < 5; i++)
{
Console.WriteLine($"Count is: {i}");
}
Example output: Count is: 0 up to Count is: 4, one line each.
C# for loop syntax
The for statement has three sections in the parentheses, separated by semicolons, followed by the body. Microsoft's language reference describes them like this:
for (initializer; condition; iterator)
{
// body
}
| Section | When it runs | Typical use |
|---|---|---|
| initializer | once, before entering the loop | int i = 0 |
| condition | before each iteration; the loop exits when it is false | i < 5 |
| iterator | after each execution of the body | i++ or i-- |
The condition must be a Boolean expression. Unlike C, an int such as 1 is not accepted as true, and the compiler rejects it. If the condition is missing, the next iteration always runs.
The iterator section can hold zero or more statement expressions separated by commas. The documentation lists prefix and postfix increments and decrements (++i, i--), assignments such as i += 2, method calls, await expressions and object creation with new.
A variable declared in the initializer is local to the loop. The documentation says you can't access it from outside the for statement, so reading i after the closing brace is a compile error. If you need the final value, declare the variable before the loop and leave the declaration out of the initializer.
Common for loop examples in C#
Loop through an array by index
Start at 0 and stop before Length. The last valid index is Length - 1, so the condition is <, not <=. With <= the final pass reads past the end of the array and throws an IndexOutOfRangeException, the classic off-by-one bug.
string[] fruits = { "apple", "banana", "cherry" };
for (int i = 0; i < fruits.Length; i++)
{
Console.WriteLine($"{i} {fruits[i]}");
}
Example output:
0 apple
1 banana
2 cherry
On an array you read Length. A List<T> exposes the same information as Count, so the condition becomes i < names.Count.
Count down
Start high, test against a lower bound and decrement:
for (int i = 3; i > 0; i--)
{
Console.WriteLine(i);
}
Console.WriteLine("liftoff");
Example output: 3, 2, 1, then liftoff.
Step by more than one
for (int i = 0; i <= 10; i += 2)
{
Console.WriteLine(i);
}
Example output: 0 2 4 6 8 10, one per line. The assignment i += 2 is one of the statement expressions allowed in the iterator section.
Sum numbers
Declare the accumulator before the loop. A variable declared inside the body is created anew on every pass and is gone when the loop ends.
decimal[] prices = { 4.50m, 10m, 2.25m };
decimal total = 0;
for (int i = 0; i < prices.Length; i++)
{
total += prices[i];
}
Console.WriteLine(total);
Example output: 16.75.
Two variables at once
Microsoft's reference shows that the iterator section can change several variables, separated by commas. This version walks from both ends of an array toward the middle:
int[] values = { 1, 2, 3, 4, 5 };
for (int left = 0, right = values.Length - 1; left < right; left++, right--)
{
Console.WriteLine($"{values[left]} and {values[right]}");
}
Example output: 1 and 5, then 2 and 4. The loop stops when left and right meet at index 2.
The reference also shows a less common form in which the loop variable is declared outside and the initializer and iterator call methods. You will rarely need it, but it confirms how loose the three sections are:
int i;
int j = 3;
for (i = 0, Console.WriteLine($"Start: i={i}, j={j}"); i < j; i++, j--, Console.WriteLine($"Step: i={i}, j={j}"))
{
}
Example output, as printed on Microsoft Learn:
Start: i=0, j=3
Step: i=1, j=2
Step: i=2, j=1
Nested loops
The inner loop runs completely for every pass of the outer one, so a 3 by 3 table runs the inner body 9 times:
for (int row = 1; row <= 3; row++)
{
for (int col = 1; col <= 3; col++)
{
Console.Write($"{row * col} ");
}
Console.WriteLine();
}
Example output:
1 2 3
2 4 6
3 6 9
The foreach loop in C#
When you want the elements and not the index, use foreach. It executes its body for each element of a type that implements System.Collections.IEnumerable or System.Collections.Generic.IEnumerable<T>. That covers arrays, List<T>, HashSet<T> and most other collections. The documentation's example:
List<int> fibNumbers = new() { 0, 1, 1, 2, 3, 5, 8, 13 };
foreach (int element in fibNumbers)
{
Console.Write($"{element} ");
}
// Output: 0 1 1 2 3 5 8 13
You can write var instead of the type and let the compiler infer it: foreach (var item in collection). If you name a type explicitly and a collection element cannot be converted to it at run time, the loop throws an InvalidCastException.
Two behaviors are worth knowing. An empty collection simply skips the body. A null collection throws a NullReferenceException, so check for null first when the value can be missing.
A foreach loop has no index. If you need the position, or you want to assign into an array slot with items[i] = ..., use a plain for loop. For await foreach, which consumes an IAsyncEnumerable<T>, the syntax is the same with await in front.
break and continue
Inside any iteration statement, break exits the loop and continue starts the next iteration. The documentation defines both against the closest enclosing loop. In a for loop, continue still runs the iterator section before the condition is tested again, which is why a continue in a counting loop does not hang it.
for (int i = 1; i <= 10; i++)
{
if (i % 2 == 0) continue; // skip even numbers
if (i > 7) break; // stop entirely after 7
Console.WriteLine(i);
}
Example output: 1 3 5 7, one per line.
Microsoft's own continue example prints Iteration 0: skip through Iteration 2: skip, then Iteration 3: done and Iteration 4: done, using if (i < 3) before the continue.
One trap: break at the end of a switch section leaves only the switch. If a switch sits inside a loop, the loop carries on.
How to exit nested loops
An unlabeled break in nested loops terminates only the innermost loop. To leave all of them you have three options.
- Labeled break (C# 15). The documentation says that starting in C# 15 a
breakcan name a label placed directly on an enclosing loop orswitch. The same applies tocontinue, and the target must be a loop. As of November 2026 this needs a compiler that supports C# 15, so check your project's language version first. gotopast the loops. Works in older versions. The reference notes that you can usegototo exit a nested loop, and that the label must be in scope.- Move the loops into a method and
return. The documentation tip suggests refactoring nested loops into separate methods for simpler, more readable code.
The C# 15 form, from Microsoft's example (the label sits right on the outer for):
outer: for (int aisle = 0; aisle < stockChecks.GetLength(0); aisle++)
{
for (int bay = 0; bay < stockChecks.GetLength(1); bay++)
{
if (stockChecks[aisle, bay] == "Blocked")
{
break outer;
}
}
}
And the version that works in earlier language versions, using goto:
int[,] grid = { { 1, 2, 3 }, { 4, 5, 6 } };
int target = 5;
for (int row = 0; row < grid.GetLength(0); row++)
{
for (int col = 0; col < grid.GetLength(1); col++)
{
if (grid[row, col] == target)
{
Console.WriteLine($"Found {target} at {row}, {col}");
goto Done;
}
}
}
Console.WriteLine("Not found");
Done:
Console.WriteLine("Search finished");
Example output: Found 5 at 1, 1, then Search finished. When the value is absent, Not found prints first.
Infinite loops and the stray semicolon
All sections of the for statement are optional. Microsoft's reference defines the infinite loop as for ( ; ; ) { }. That is legitimate for a loop that reads input until an end marker, provided the body has a reachable exit such as break or return:
for (;;)
{
if (IsDone()) break; // the only normal exit
DoWork();
}
Accidental infinite loops usually have one of two causes. The first is an iterator that moves away from the condition, such as i-- in a loop that starts at 0 and tests i < 10. (An int eventually wraps around in unchecked code, but you should not rely on that.) The second is a semicolon straight after the closing parenthesis:
for (int i = 0; i < 3; i++); // empty statement is the loop body
{
Console.WriteLine("runs once");
}
The semicolon is an empty statement and becomes the whole body. The loop counts to 3 doing nothing, and the block below it runs exactly once. Compilers and IDEs commonly warn about this pattern.
for, foreach, while or do: which one?
| You want | Use |
|---|---|
| to count, or step by a custom amount | for |
| every element of an array or collection | foreach |
| the index and the element | for |
| to assign into array slots by index | for with items[i] = ... |
| to loop until a condition changes, zero or more times | while |
| to loop at least once, then test the condition | do ... while |
The documentation draws the line between the last two clearly: while evaluates its condition before each execution, so it runs zero or more times, and do evaluates it after, so it runs one or more times. If you only use the condition section of a for loop, a while loop says the same thing more plainly.
Coming from other languages?
The basic loop looks almost identical in several languages, but the details differ. C# requires a Boolean condition and a declared (or var) loop variable. For the same topic in related languages, see C for loop: syntax and examples, Java for loop: syntax and examples and JavaScript for loop: syntax and examples.
Frequently asked questions
- Can a C# for loop have no condition?
- Yes. All sections of the for statement are optional. Microsoft's documentation shows for ( ; ; ) as an infinite loop, and states that if the condition section is not present, the next iteration always runs. You then need a break, return or exception inside the body to leave it.
- What is the difference between for and foreach in C#?
- A for loop gives you an initializer, a condition and an iterator, so you control the counter and can step by any amount. A foreach loop enumerates the elements of a collection, such as an array or a List<T>, and gives you each element without an index. Use for when you need the index or a custom step, and foreach when you only need the elements.
- Can I use the loop variable after a C# for loop ends?
- Not if you declared it in the initializer section. Microsoft's documentation says you can't access that variable from outside the for statement. Declare the variable before the loop if you need its final value afterwards.
- Does C# have a labeled break to exit nested loops?
- Starting in C# 15, yes: put a label directly on the outer loop and write break outer; inside the inner loop. In earlier language versions, use a goto statement that jumps past the loops, or move the loops into a method and use return.