Loop Structures
while Loop
The while loop repeats a code block as long as its condition is true. The condition is checked before each iteration - if it's false, the entire loop body is skipped.
int count = 1;
while (count <= 5)
{
Console.WriteLine($"Execution #{count}");
count++;
}
Execution #1
Execution #2
Execution #3
Execution #4
Execution #5
Tip: If the condition is
falsefrom the start, the loop body never executes.
do...while Loop
The do...while loop executes the body first, then checks the condition. The loop body runs at least once, regardless of the condition.
int number;
do
{
Console.WriteLine("Enter a positive number:");
number = int.Parse(Console.ReadLine());
} while (number <= 0);
Console.WriteLine($"You entered: {number}");
Warning: The semicolon at the end of
do...whileis required - this is a syntax difference from thewhileloop.
for Loop
The for loop combines initialization, condition, and iteration update into a single line, making it ideal when the number of iterations is known in advance.
for (int i = 1; i <= 5; i++)
{
Console.WriteLine($"i = {i}");
}
i = 1
i = 2
i = 3
i = 4
i = 5
All three parts of the for statement can be omitted, but the semicolons must remain:
int j = 0;
for (; j < 3; )
{
Console.WriteLine($"j = {j}");
j++;
}
j = 0
j = 1
j = 2
foreach Loop
The foreach loop is a C# feature for iterating over each element in a collection. It offers clean, safe syntax and works with arrays, lists, and any collection implementing IEnumerable.
string[] fruits = { "Apple", "Banana", "Orange" };
foreach (var fruit in fruits)
{
Console.WriteLine($"Fruit: {fruit}");
}
Fruit: Apple
Fruit: Banana
Fruit: Orange
Warning: The
foreachloop is read-only - the iteration variable is a read-only copy. You cannot modify collection elements through it, nor add or remove elements during iteration, or anInvalidOperationExceptionwill be thrown.
Example
int[] scores = { 90, 85, 72, 60, 95 };
int sum = 0;
foreach (int score in scores)
{
sum += score;
}
Console.WriteLine($"Total: {sum}, Average: {(double)sum / scores.Length:F1}");
Total: 402, Average: 80.4
Nested Loops
A loop inside another loop is called a nested loop, commonly used for processing two-dimensional data structures like matrices and tables.
for (int row = 1; row <= 3; row++)
{
for (int col = 1; col <= 4; col++)
{
Console.Write($"{row * col,4}");
}
Console.WriteLine();
}
1 2 3 4
2 4 6 8
3 6 9 12
Warning: Nested loops have O(n^2) time complexity - more layers mean worse performance. In practice, avoid deep nesting and consider using LINQ or extracting methods to optimize.
break and continue
break
break immediately exits the current loop, skipping all remaining iterations.
for (int i = 0; i < 10; i++)
{
if (i == 5) break;
Console.Write($"{i} ");
}
0 1 2 3 4
continue
continue skips the rest of the current iteration and jumps to the next one.
for (int i = 0; i < 6; i++)
{
if (i % 2 == 0) continue;
Console.Write($"{i} ");
}
1 3 5
Tip:
breakandcontinueonly affect the innermost loop. To break out of multiple layers, use a flag variable or labeled statements.
Common Loop Patterns
Counting Pattern
Count elements that satisfy a condition:
int[] data = { 12, 25, 8, 33, 17, 6, 41 };
int count = 0;
foreach (int val in data)
{
if (val > 20) count++;
}
Console.WriteLine($"Count of values > 20: {count}");
Count of values > 20: 3
Accumulation Pattern
Sum a series of numbers:
int sum = 0;
for (int i = 1; i <= 100; i++)
{
sum += i;
}
Console.WriteLine($"Sum of 1 to 100: {sum}");
Sum of 1 to 100: 5050
Search Pattern
Find a target element in a collection:
int[] numbers = { 3, 7, 15, 22, 9, 31 };
int target = 22;
int index = -1;
for (int i = 0; i < numbers.Length; i++)
{
if (numbers[i] == target)
{
index = i;
break;
}
}
Console.WriteLine(index >= 0 ? $"Found {target} at index {index}" : "Not found");
Found 22 at index 3
Example
Combining multiple patterns - tally grade distribution and calculate the average:
int[] scores = { 92, 78, 55, 88, 43, 96, 67, 73, 81, 50 };
int excellent = 0, pass = 0, fail = 0, total = 0;
foreach (int s in scores)
{
total += s;
if (s >= 90) excellent++;
else if (s >= 60) pass++;
else fail++;
}
double avg = (double)total / scores.Length;
Console.WriteLine($"Excellent: {excellent}, Pass: {pass}, Fail: {fail}");
Console.WriteLine($"Average: {avg:F1}");
Excellent: 2, Pass: 5, Fail: 3
Average: 72.3
Infinite Loops and How to Avoid Them
An infinite loop occurs when the loop condition is always true, causing the loop to never terminate. Common infinite loop patterns:
while (true)
{
}
for (; ; )
{
}
Example
A controlled loop with exit conditions to avoid infinite loops:
Random rnd = new Random();
int attempts = 0;
while (true)
{
int value = rnd.Next(1, 101);
attempts++;
if (value == 42)
{
Console.WriteLine($"Got 42 on attempt #{attempts}!");
break;
}
if (attempts > 1000)
{
Console.WriteLine("Too many attempts, exiting loop.");
break;
}
}
Guidelines for avoiding infinite loops:
- Ensure that
whileandforconditions will eventually becomefalse - When using
while (true)orfor (; ; ), always provide abreakexit path - Set a maximum iteration count as a safety valve
- Double-check the loop variable update logic to prevent accidentally skipping increments or decrements
In practice,
while (true)withbreakis a common loop pattern, but make sure every branch has an exit opportunity.
❓ FAQ
while and do...while?while checks the condition first and may never execute the body; do...while executes the body first, so it runs at least once.foreach loop?for loop with index access if you need to modify elements.break exit multiple nested loops?break only exits the innermost loop. To exit multiple layers, use a flag variable or extract the inner loop into a method and use return.for (; ; ) and while (true)?while (true) is more readable, while for (; ; ) may avoid compiler warnings in some environments.📖 Summary
whilechecks the condition first; the body runs only when the condition istruedo...whileexecutes the body once before checking the conditionforis ideal for known iteration counts with compact syntaxforeachis a C# feature for cleanly iterating collections, but the iteration variable is read-only- Nested loops handle multi-dimensional data - watch out for O(n^2) performance impact
breakimmediately exits the loop;continueskips the current iteration- Common patterns: counting, accumulation, searching, traversal
- Infinite loops can be controlled with
while (true)+break, but always set an exit condition
📝 Exercises
- Write a program that uses a
whileloop to calculate powers of 2 until the value exceeds 1000, and output all results. - Use a
forloop to print a multiplication table in upper-triangular form (avoid duplicates). - Given a string array, use
foreachto count how many strings have a length greater than 5. - Write a program using
do...whilethat repeatedly asks the user for a password until the correct one is entered (define the correct password yourself). - Use nested
forloops to find all prime numbers between 1 and 50. - Use
continuein aforloop to print all numbers from 1 to 20 that are not divisible by 3.



