The fundamental way to repeat code.
📌 1. for Loop
Use for when you know how many times to iterate.
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Iteration: " + i);
}-
Structure:
for(initialization; condition; increment/decrement) -
Executes as long as the condition is true.
📌 2. while Loop
Use while when you want to repeat until a condition becomes false.
int count = 0;
while (count < 5)
{
Console.WriteLine("Count: " + count);
count++;
}- The condition is checked before each iteration.
📌 3. do-while Loop
Similar to while, but executes at least once because the condition is checked after the loop.
int count = 0;
do
{
Console.WriteLine("Count: " + count);
count++;
} while (count < 5);- Use when the loop must run at least once.
📌 4. foreach Loop
Use foreach to iterate over collections/arrays.
string[] names = { "Alice", "Bob", "Charlie" };
foreach (string name in names)
{
Console.WriteLine(name);
}-
Read-only access to elements.
-
Cannot modify the collection itself inside
foreach.
📌 5. Loop Control Keywords
break
Exits the loop immediately.
for (int i = 0; i < 10; i++)
{
if (i == 5) break;
Console.WriteLine(i); // prints 0..4
}continue
Skips the rest of the current iteration and moves to the next.
for (int i = 0; i < 5; i++)
{
if (i == 2) continue;
Console.WriteLine(i); // prints 0,1,3,4
}goto
Rarely used, jumps to a labeled statement. Use sparingly.
int i = 0;
start:
Console.WriteLine(i);
i++;
if (i < 5) goto start;📌 6. Nested Loops
Loops can be nested inside each other.
for (int i = 1; i <= 3; i++)
{
for (int j = 1; j <= 2; j++)
{
Console.WriteLine($"i={i}, j={j}");
}
}📌 7. Summary Table
| Loop Type | Check Condition | Usage |
|---|---|---|
for | Before | Known number of iterations |
while | Before | Condition-controlled |
do-while | After | Must run at least once |
foreach | N/A | Iterate over collection |
✅ Tip:
-
Use
fororwhilefor numeric/index-based loops. -
Use
foreachfor arrays, lists, or collections. -
Use
breakandcontinueto control loop flow.