1. 概述
for循环是一种计数循环结构,它将循环的初始化、条件和更新都放在一行代码中。for循环特别适合已知循环次数的情况,代码结构清晰简洁。
2. 基本语法
for循环的基本语法如下:
for (初始化; 条件表达式; 更新表达式)
{
// 循环体:当条件为true时重复执行的代码
}
其中:
- 初始化:循环开始前执行一次,通常用于初始化循环变量
- 条件表达式:每次循环开始前检查,如果为true则执行循环体
- 更新表达式:每次循环结束后执行,通常用于更新循环变量
- 循环体:当条件为true时执行的代码块
3. 基本用法示例
示例:输出1到10的数字
for (int i = 1; i <= 10; i++)
{
Console.WriteLine(i);
}
输出结果:
1
2
3
4
5
6
7
8
9
10
4. for循环的执行流程
执行步骤
- 执行初始化表达式(只执行一次)
- 检查条件表达式是否为true
- 如果为true,执行循环体中的代码
- 执行更新表达式
- 回到步骤2
- 如果条件为false,跳出循环,继续执行后面的代码
5. 常见应用场景
场景1:遍历数组
int[] numbers = { 10, 20, 30, 40, 50 };
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine($"数组[{i}] = {numbers[i]}");
}
场景2:计算累加和
int sum = 0;
for (int i = 1; i <= 100; i++)
{
sum += i;
}
Console.WriteLine($"1到100的和是:{sum}");
场景3:打印乘法表
for (int i = 1; i <= 9; i++)
{
for (int j = 1; j <= i; j++)
{
Console.Write($"{j}×{i}={i*j} ");
}
Console.WriteLine();
}
场景4:倒计时
Console.WriteLine("倒计时开始:");
for (int i = 10; i >= 1; i--)
{
Console.WriteLine(i);
}
Console.WriteLine("发射!");
6. for循环的变体
for循环的三个部分都是可选的,可以创建各种变体。
示例:省略初始化
int i = 1;
for (; i <= 10; i++)
{
Console.WriteLine(i);
}
示例:省略条件(无限循环)
for (int i = 1; ; i++)
{
Console.WriteLine(i);
if (i > 10)
{
break; // 手动退出循环
}
}
示例:省略更新
for (int i = 1; i <= 10; )
{
Console.WriteLine(i);
i++; // 在循环体内更新
}
示例:多个初始化和更新
for (int i = 0, j = 10; i < j; i++, j--)
{
Console.WriteLine($"i={i}, j={j}");
}
7. foreach与for的比较
C#还提供了foreach循环,用于遍历集合。for循环和foreach循环各有优势:
| 特性 | for循环 | foreach循环 |
|---|---|---|
| 访问索引 | 可以访问索引 | 无法访问索引 |
| 修改集合 | 可以修改集合 | 不能修改集合 |
| 代码简洁性 | 较复杂 | 更简洁 |
| 适用场景 | 需要索引或修改集合 | 只读遍历 |
8. break和continue语句
在for循环中,可以使用break和continue语句来控制循环流程。
示例:使用break和continue
for (int i = 1; i <= 10; i++)
{
if (i == 5)
{
continue; // 跳过本次循环
}
if (i == 8)
{
break; // 退出整个循环
}
Console.WriteLine(i);
}
输出结果:
1
2
3
4
6
7
9. 嵌套for循环
for循环可以嵌套使用,形成多层循环结构。
示例:打印星形图案
for (int i = 1; i <= 5; i++)
{
for (int j = 1; j <= i; j++)
{
Console.Write("* ");
}
Console.WriteLine();
}
输出结果:
*
* *
* * *
* * * *
* * * * *
10. 注意事项
重要注意事项
- 确保循环条件最终会变为false:否则会导致无限循环
- 注意循环变量的作用域:循环变量在循环外部不可访问
- 注意数组边界:避免数组越界错误
- 考虑性能:在循环内避免重复计算
- 选择合适的循环类型:根据需求选择for、foreach、while或do-while
11. 常见错误与解决方案
错误1:循环条件错误
// 错误示例
for (int i = 1; i < 10; i++) // 应该是 <= 10
{
Console.WriteLine(i);
}
// 正确示例
for (int i = 1; i <= 10; i++)
{
Console.WriteLine(i);
}
错误2:数组越界
// 错误示例
int[] arr = { 1, 2, 3 };
for (int i = 0; i <= arr.Length; i++) // 应该是 < arr.Length
{
Console.WriteLine(arr[i]);
}
// 正确示例
int[] arr = { 1, 2, 3 };
for (int i = 0; i < arr.Length; i++)
{
Console.WriteLine(arr[i]);
}
错误3:循环变量作用域错误
// 错误示例
for (int i = 1; i <= 10; i++)
{
Console.WriteLine(i);
}
Console.WriteLine(i); // 错误:i在这里不可访问
// 正确示例
int i;
for (i = 1; i <= 10; i++)
{
Console.WriteLine(i);
}
Console.WriteLine(i); // 正确:i在这里可以访问
12. 完整示例程序
示例:成绩统计程序
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("=== 成绩统计程序 ===");
Console.Write("请输入学生人数:");
if (int.TryParse(Console.ReadLine(), out int studentCount) && studentCount > 0)
{
double[] scores = new double[studentCount];
double sum = 0;
double maxScore = double.MinValue;
double minScore = double.MaxValue;
// 输入成绩
for (int i = 0; i < studentCount; i++)
{
Console.Write($"请输入第{i + 1}个学生的成绩:");
if (double.TryParse(Console.ReadLine(), out double score) && score >= 0 && score <= 100)
{
scores[i] = score;
sum += score;
if (score > maxScore)
{
maxScore = score;
}
if (score < minScore)
{
minScore = score;
}
}
else
{
Console.WriteLine("无效的成绩,请重新输入!");
i--; // 重新输入当前学生的成绩
}
}
// 计算平均分
double average = sum / studentCount;
// 输出统计结果
Console.WriteLine("\n=== 统计结果 ===");
Console.WriteLine($"学生人数:{studentCount}");
Console.WriteLine($"平均分:{average:F2}");
Console.WriteLine($"最高分:{maxScore}");
Console.WriteLine($"最低分:{minScore}");
Console.WriteLine($"总分:{sum}");
// 输出所有成绩
Console.WriteLine("\n=== 所有成绩 ===");
for (int i = 0; i < studentCount; i++)
{
Console.WriteLine($"第{i + 1}个学生:{scores[i]}");
}
}
else
{
Console.WriteLine("无效的学生人数!");
}
Console.WriteLine("\n按任意键退出...");
Console.ReadKey();
}
}
13. 总结
for循环是C#中最常用的循环结构之一,它具有以下特点:
- 结构清晰:初始化、条件和更新都放在一行代码中
- 适用场景:已知循环次数的情况
- 灵活性:可以省略各个部分,创建各种变体
- 支持索引:可以访问循环索引,便于操作
通过本教程的学习,你应该掌握了:
- for循环的基本语法和使用方法
- for循环的执行流程
- for循环的各种变体
- break和continue语句的使用
- 嵌套for循环的使用
- for循环与foreach循环的比较
- 常见错误与解决方案
熟练掌握for循环是学习C#编程的基础,它将帮助你编写更加简洁和高效的程序。