
🔁 For Loop in C#
The for loop in C# is used to repeat a block of code a specific number of times. It's one of the most common loops and is useful when you know in advance how many iterations you want.
📘 Syntax of for loop
for (initialization; condition; increment/decrement) {
// Code to execute repeatedly
}
for (initialization; condition; increment/decrement) {
// Code to execute repeatedly
}
💡 How it works
- Initialization: executed once before the loop starts
- Condition: checked before each iteration; if true, loop continues
- Increment/Decrement: executed after each iteration
📝 Example: For Loop in C#
using System;
class Program {
static void Main() {
for (int i = 1; i <= 5; i++) {
Console.WriteLine($"Iteration number: {i}");
}
}
}
📤 Sample Output
Iteration number: 1
Iteration number: 2
Iteration number: 3
Iteration number: 4
Iteration number: 5
Iteration number: 2
Iteration number: 3
Iteration number: 4
Iteration number: 5
🧠 Explanation
- The loop starts with
i = 1. - Before each iteration, it checks if
i <= 5. - On each iteration, it prints the current value of
i. - After printing,
iincrements by 1 (i++). - The loop stops when
ibecomes 6, as the conditioni <= 5fails.
The for loop is a fundamental construct in C# programming and helps to run repetitive tasks efficiently and cleanly.
Post a Comment