循环嵌套:当循环语句中的循环体又是一个循环语句时,就构成了“嵌套循环”。
嵌套层次:循环的嵌套层次从语法上没有限制,但一般不超过三层,否则将影响可读性。
应用举例:
【例2.16】 打印九九表。打印格式为:
* 1 2 3 4 5 6 7 8 9
1 1
2 2 4
3 3 6 9
…
9 9 18 27 36 45 54 63 72 81
#include <iostream>
#include <iomanip>
using namespace std;
int main(){
int i,j;
cout<<setw(3)<<'*'<<setw(4)<<' ';
for(i=1;i<10;i++) cout<<setw(4)<<i; //输出第一行表头
cout<<endl<<endl; //输出空行
for(i=1;i<10;i++){
cout<<setw(3)<<i<<setw(4)<<' '; //输出行
for(j=1;j<=i;j++) cout<<setw(4)<<i*j; //输出表值数据
cout<<endl; //准备输出下一行
}
return 0;
}
【例2.17】 打印如下图形。
* * * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * *
#include <iostream>
#include <iomanip>
using namespace std;
int main(){
int i,j;
for(i=1;i<=5;i++){
for(j=1;j<=5-i;j++) cout<<" " ; //输出若干空格
for(j=1;j<=11;j++) cout<<"* "; //输出若干*
cout<<endl; //准备输出下一行
}
return 0;
}
嵌套形式:for 语句、while语句和do-while语句均可以构成嵌套形式,这三种语句还可以互相嵌套。
嵌套层次:循环的嵌套层次从语法上没有限制,但一般不超过三层,否则将影响可读性。
应用举例:
【例2.16】 打印九九表。打印格式为:
* 1 2 3 4 5 6 7 8 9
1 1
2 2 4
3 3 6 9
…
9 9 18 27 36 45 54 63 72 81
#include <iostream>
#include <iomanip>
using namespace std;
int main(){
int i,j;
cout<<setw(3)<<'*'<<setw(4)<<' ';
for(i=1;i<10;i++) cout<<setw(4)<<i; //输出第一行表头
cout<<endl<<endl; //输出空行
for(i=1;i<10;i++){
cout<<setw(3)<<i<<setw(4)<<' '; //输出行
for(j=1;j<=i;j++) cout<<setw(4)<<i*j; //输出表值数据
cout<<endl; //准备输出下一行
}
return 0;
}
【例2.17】 打印如下图形。
* * * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * *
#include <iostream>
#include <iomanip>
using namespace std;
int main(){
int i,j;
for(i=1;i<=5;i++){
for(j=1;j<=5-i;j++) cout<<" " ; //输出若干空格
for(j=1;j<=11;j++) cout<<"* "; //输出若干*
cout<<endl; //准备输出下一行
}
return 0;
}
嵌套形式:for 语句、while语句和do-while语句均可以构成嵌套形式,这三种语句还可以互相嵌套。
本文通过两个具体例子介绍循环嵌套的基本概念及使用方法。首先展示如何利用双重循环打印九九乘法表,并强调了输出格式的重要性。接着,通过另一个图形绘制的例子进一步解释循环嵌套在实际编程中的应用。
3282

被折叠的 条评论
为什么被折叠?



