C# Loops
Repeat an action with a for loop.
On this page
The concept
The initializer runs once. The condition is checked before each iteration. The increment runs after each body execution.
Code example
C#
using System;
class Program {
static void Main() {
for (int i = 1; i <= 3; i++) {
Console.WriteLine(i);
}
}
}Output
1 2 3
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
Guided walkthroughReady
1
using System;2
class Program {3
static void Main() {4
for (int i = 1; i <= 3; i++) {5
Console.WriteLine(i);6
}7
}8
}Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| Start i at 1; run while i is no greater than 3. | — | — | |
| Print i, increment it, and repeat for 2 and 3. | i = 1 → 2 → 3 → 4 | 1 2 3 |
Behind the scenes
How C# processes this code
C# compiles to code for the .NET runtime, which invokes the program entry point.