📚 什么是嵌套循环?
嵌套的概念
在一个循环的循环体中再写一个或多个循环,形成多层循环结构。
- ✅ 处理二维数据
- ✅ 打印图案和表格
- ✅ 实现多重遍历
- ⚠️ 注意时间复杂度
基本语法
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 3; i++) {
cout << "第" << i << "行:";
for (int j = 1; j <= 3; j++) {
cout << "* ";
}
cout << endl;
}
return 0;
}
💡 执行流程:
• 外层循环执行1次 → 内层循环执行n次
• 外层循环执行m次 → 总执行 m×n 次
• 外层控制行,内层控制列
• 每次外层迭代,内层从头开始
⚙️ 双重循环示例
打印矩形图案
#include <iostream>
using namespace std;
int main() {
int rows = 4, cols = 5;
cout << "打印" << rows << "行" << cols << "列的矩形:" << endl;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= cols; j++) {
cout << "* ";
}
cout << endl;
}
return 0;
}
打印三角形
#include <iostream>
using namespace std;
int main() {
int n = 5;
cout << "直角三角形:" << endl;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
cout << "* ";
}
cout << endl;
}
return 0;
}
🎮 互动实验:图案生成器
输入行数和类型,生成不同图案
输入参数后点击"生成"...
🛠️ 常见应用场景
九九乘法表
#include <iostream>
using namespace std;
int main() {
cout << "九九乘法表:" << endl;
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= i; j++) {
cout << j << "×" << i << "=" << (i*j) << "\t";
}
cout << endl;
}
return 0;
}
遍历二维数组
#include <iostream>
using namespace std;
int main() {
int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
cout << "遍历二维数组:" << endl;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
cout << matrix[i][j] << "\t";
}
cout << endl;
}
return 0;
}
🎯 乘法表生成器
生成指定范围的乘法表
输入数字后点击"生成"...
🚀 三重循环
三层嵌套示例
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 3; i++) {
cout << "第" << i << "层:" << endl;
for (int j = 1; j <= 3; j++) {
for (int k = 1; k <= 3; k++) {
cout << "* ";
}
cout << endl;
}
cout << endl;
}
return 0;
}
⚠️ 性能考虑:
• 双重循环:O(n²) - 可以接受
• 三重循环:O(n³) - 谨慎使用
• 四层以上:通常有优化方案
• 避免不必要的嵌套
📝 实战练习
📝 小练习:嵌套理解
以下代码总共输出多少个*?
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 4; j++) {
cout << "* ";
}
cout << endl;
}
return 0;
}
选择答案查看解析...
💻 编程挑战
题目:使用嵌套循环打印菱形图案(上半部分+下半部分)。
输入数字后点击"生成代码"...