C# 控制语句 - 循环结构

6.1 for 循环

基本语法

1
2
3
4
for (初始化; 条件; 迭代)
{
// 循环体
}

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 打印 0 到 4
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}

// 计算 1 到 100 的和
int sum = 0;
for (int i = 1; i <= 100; i++)
{
sum += i;
}
Console.WriteLine($"总和: {sum}"); // 5050

// 倒序
for (int i = 10; i >= 1; i--)
{
Console.Write($"{i} ");
}
// 输出: 10 9 8 7 6 5 4 3 2 1

6.2 foreach 循环

遍历集合

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 遍历数组
int[] numbers = { 1, 2, 3, 4, 5 };
foreach (int num in numbers)
{
Console.WriteLine(num);
}

// 遍历列表
List<string> fruits = new() { "apple", "banana", "orange" };
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}

// 遍历字符串
string text = "Hello";
foreach (char c in text)
{
Console.WriteLine(c);
}

带索引遍历(.NET 6+)

1
2
3
4
5
6
string[] names = { "Alice", "Bob", "Charlie" };

foreach (var (index, name) in names.Select((n, i) => (i, n)))
{
Console.WriteLine($"{index}: {name}");
}

6.3 while 循环

基本语法

1
2
3
4
while (条件)
{
// 循环体
}

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 计数循环
int count = 0;
while (count < 5)
{
Console.WriteLine(count);
count++;
}

// 用户输入验证
string input = "";
while (input != "quit")
{
Console.Write("输入命令 (quit 退出): ");
input = Console.ReadLine();
Console.WriteLine($"执行: {input}");
}

6.4 do-while 循环

基本语法

1
2
3
4
do
{
// 循环体(至少执行一次)
} while (条件);

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 至少执行一次
int number;
do
{
Console.Write("输入正数: ");
} while (!int.TryParse(Console.ReadLine(), out number) || number <= 0);

Console.WriteLine($"你输入了: {number}");

// 菜单系统
string choice;
do
{
Console.WriteLine("1. 开始游戏");
Console.WriteLine("2. 设置");
Console.WriteLine("3. 退出");
choice = Console.ReadLine();
} while (choice != "3");

6.5 break 语句

break 用于立即退出循环。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// 找到第一个偶数就退出
for (int i = 1; i <= 10; i++)
{
if (i % 2 == 0)
{
Console.WriteLine($"找到偶数: {i}");
break;
}
}
// 输出: 找到偶数: 2

// 搜索
int[] numbers = { 3, 7, 2, 9, 5 };
int target = 9;
int foundIndex = -1;

for (int i = 0; i < numbers.Length; i++)
{
if (numbers[i] == target)
{
foundIndex = i;
break;
}
}

if (foundIndex >= 0)
Console.WriteLine($"找到 {target},索引: {foundIndex}");
else
Console.WriteLine("未找到");

6.6 continue 语句

continue 用于跳过当前迭代,继续下一次。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 只打印奇数
for (int i = 1; i <= 10; i++)
{
if (i % 2 == 0)
continue; // 跳过偶数
Console.Write($"{i} ");
}
// 输出: 1 3 5 7 9

// 过滤数据
string[] words = { "apple", "", "banana", null, "orange" };
foreach (string word in words)
{
if (string.IsNullOrEmpty(word))
continue;
Console.WriteLine(word.ToUpper());
}

6.7 嵌套循环

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// 打印九九乘法表
for (int i = 1; i <= 9; i++)
{
for (int j = 1; j <= i; j++)
{
Console.Write($"{j}×{i}={i * j}\t");
}
Console.WriteLine();
}

// 打印图案
for (int i = 1; i <= 5; i++)
{
for (int j = 1; j <= i; j++)
{
Console.Write("*");
}
Console.WriteLine();
}
// 输出:
// *
// **
// ***
// ****
// *****

6.8 无限循环

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// for 无限循环
for (; ; )
{
Console.WriteLine("无限循环");
break; // 需要手动退出
}

// while 无限循环
while (true)
{
string input = Console.ReadLine();
if (input == "exit")
break;
}

// 实际应用场景
// 服务器监听、游戏主循环、后台任务

6.9 循环最佳实践

1. 选择合适的循环

1
2
3
4
5
6
7
8
9
10
11
// 已知次数:for
for (int i = 0; i < 10; i++) { }

// 遍历集合:foreach
foreach (var item in collection) { }

// 条件循环:while
while (condition) { }

// 至少执行一次:do-while
do { } while (condition);

2. 避免修改循环变量

1
2
3
4
5
6
7
8
9
10
11
12
// 不推荐
for (int i = 0; i < 10; i++)
{
i = 5; // 修改循环变量可能导致无限循环
}

// 推荐:使用 continue 或 break
for (int i = 0; i < 10; i++)
{
if (i == 5)
continue;
}

3. 提前计算循环边界

1
2
3
4
5
6
// 不推荐:每次迭代都计算 Length
for (int i = 0; i < array.Length; i++) { }

// 推荐:提前计算
int len = array.Length;
for (int i = 0; i < len; i++) { }

6.10 本章小结

  • for 用于已知次数的循环
  • foreach 用于遍历集合
  • while 用于条件循环
  • do-while 至少执行一次
  • break 退出循环,continue 跳过当前迭代
  • 嵌套循环用于多维数据处理
  • 选择合适的循环类型提高代码可读性

练习题

  1. 使用 for 循环计算 1 到 100 所有偶数的和
  2. 使用 while 循环实现斐波那契数列前 20 项
  3. 使用嵌套循环打印菱形图案
  4. 以下代码输出什么?
    1
    2
    3
    4
    5
    6
    for (int i = 0; i < 5; i++)
    {
    if (i == 3)
    break;
    Console.Write(i);
    }
ByteFisher
分享编程技术 · 记录钓鱼乐趣
扫码关注
▸ 扫码关注 ◂
C#基础教程 系列
第 6/20 篇
分享: