404 Not Found

404 Not Found


nginx

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.

CSHARP
int count = 1;
while (count <= 5)
{
    Console.WriteLine($"Execution #{count}");
    count++;
}
TEXT
Execution #1
Execution #2
Execution #3
Execution #4
Execution #5

Tip: If the condition is false from 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.

CSHARP
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...while is required - this is a syntax difference from the while loop.

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.

CSHARP
for (int i = 1; i <= 5; i++)
{
    Console.WriteLine($"i = {i}");
}
TEXT
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:

CSHARP
int j = 0;
for (; j < 3; )
{
    Console.WriteLine($"j = {j}");
    j++;
}
TEXT
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.

CSHARP
string[] fruits = { "Apple", "Banana", "Orange" };
foreach (var fruit in fruits)
{
    Console.WriteLine($"Fruit: {fruit}");
}
TEXT
Fruit: Apple
Fruit: Banana
Fruit: Orange

Warning: The foreach loop 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 an InvalidOperationException will be thrown.

Example

CSHARP
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}");
▶ Try it Yourself
TEXT
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.

CSHARP
for (int row = 1; row <= 3; row++)
{
    for (int col = 1; col <= 4; col++)
    {
        Console.Write($"{row * col,4}");
    }
    Console.WriteLine();
}
TEXT
   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.

CSHARP
for (int i = 0; i < 10; i++)
{
    if (i == 5) break;
    Console.Write($"{i} ");
}
TEXT
0 1 2 3 4

continue

continue skips the rest of the current iteration and jumps to the next one.

CSHARP
for (int i = 0; i < 6; i++)
{
    if (i % 2 == 0) continue;
    Console.Write($"{i} ");
}
TEXT
1 3 5

Tip: break and continue only 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:

CSHARP
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}");
TEXT
Count of values > 20: 3

Accumulation Pattern

Sum a series of numbers:

CSHARP
int sum = 0;
for (int i = 1; i <= 100; i++)
{
    sum += i;
}
Console.WriteLine($"Sum of 1 to 100: {sum}");
TEXT
Sum of 1 to 100: 5050

Search Pattern

Find a target element in a collection:

CSHARP
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");
TEXT
Found 22 at index 3

Example

Combining multiple patterns - tally grade distribution and calculate the average:

CSHARP
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}");
▶ Try it Yourself
TEXT
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:

CSHARP
while (true)
{
}

for (; ; )
{
}

Example

A controlled loop with exit conditions to avoid infinite loops:

CSHARP
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;
    }
}
▶ Try it Yourself

Guidelines for avoiding infinite loops:

In practice, while (true) with break is a common loop pattern, but make sure every branch has an exit opportunity.

❓ FAQ

Q What is the difference between while and do...while?
A while checks the condition first and may never execute the body; do...while executes the body first, so it runs at least once.
Q Can I modify collection elements in a foreach loop?
A No. The iteration variable is a read-only copy - modifying it does not affect the original collection. Use a for loop with index access if you need to modify elements.
Q Can break exit multiple nested loops?
A No. 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.
Q Is there a difference between for (; ; ) and while (true)?
A They are functionally identical - both create infinite loops. while (true) is more readable, while for (; ; ) may avoid compiler warnings in some environments.

📖 Summary

📝 Exercises

  1. Write a program that uses a while loop to calculate powers of 2 until the value exceeds 1000, and output all results.
  2. Use a for loop to print a multiplication table in upper-triangular form (avoid duplicates).
  3. Given a string array, use foreach to count how many strings have a length greater than 5.
  4. Write a program using do...while that repeatedly asks the user for a password until the correct one is entered (define the correct password yourself).
  5. Use nested for loops to find all prime numbers between 1 and 50.
  6. Use continue in a for loop to print all numbers from 1 to 20 that are not divisible by 3.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏