在前面的几篇文章之中,写到了for,while,do while循环的基本用法,for循环用法链接:https://blog.csdn.net/qqj3066574300/article/details/105038846 while循环用法链接:https://blog.csdn.net/qqj3066574300/article/details/105039377 do while循环用法链接:https://blog.csdn.net/qqj3066574300/article/details/105040121 而本篇文章主要写的内容是嵌套循环,相对于前面几篇文章来说,代码内容是复杂一些,但对于嵌套循环,可以这样子理解,循环中再加一个循环,基本的结构如下:
for(条件){
for(条件)
代码块
}
下面的内容就以两个案例为解析,如有疑问的,可以私聊本人或者到网上查看基本资料。
代码案例:
#include <stdio.h>
#include <stdlib.h>
#define ROWS 6
#define CHSRS 10
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(){
int row;
int ch;
for(row = 0;row < ROWS;row++){
for(ch = 1;ch < (1 + CHSRS);ch++)
printf("%d",ch);
printf("\n");
}
return 0;
}
运行结果;
代码案例:
#include <stdio.h>
#include <stdlib.h>
#define ROWS 6
#define CHSRS 10
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(){
int row;
char ch;
for(row = 0;row < ROWS;row++){
for(ch = 'A';ch < ('A' + CHSRS);ch++)
printf("%c",ch);
printf("\n");
}
return 0;
}
运行结果:
如上就是两个简单的嵌套循环案例,其实代码还是很简单的,可能对于初学者而言,其中有两个疑问,#define是什么?代码还可以这样子写?(for(ch = 'A';ch < ('A' + CHSRS);ch++))。