1.while 循环
1.1 if 和 while 的对比
1.1.1 用法对比
1 if(表达式)
2 语句;
3
4
5 while(表达式)
6 语句;
1.1.2 代码对比
if 代码
#include <stdio.h>
int main()
{
if (1)
printf("hehe\n");
return 0;
}
while 代码
#include <stdio.h>
int main()
{
while (1)
printf("hehe\n");//死循环打印hehe
return 0;
}
while 语句是可以实现循环打印
1.2.while 语句的执行流程
1.3.while 循环实践
练习:在屏幕上打印数字1~10
#include <stdio.h>
int main()
{
int i = 1;
while (i <= 10)
{
printf("%d ", i);
i++;
}
return 0;
}
2. for 循环
2.1 语法形式
1 for(表达式1;表达式2;表达式3)
2 语句;
表达式1 :用于循环变量的初始化
表达式2 :用于循环结束条件的判断
表达式3 :用于循环变量的调整
注:for 循环的初始化,判断,循环三个表达式都可以省略,若判断部分省略,则表达式判断部分恒为真
!!!但不要轻易省略
例如:
执行下面两个代码并判断各打印了几次
#include <stdio.h>
int main()
{
int i = 0;
int j = 0;
int a = 0;
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
printf("hehe\n");
a++;
}
}
printf("打印了%d次\n", a);
return 0;
}
#include <stdio.h>
int main()
{
int i = 0;
int j = 0;
int a = 0;
for (; i < 5; i++)
{
for (; j < 5; j++)
{
printf("hehe\n");
a++;
}
}
printf("打印了%d次\n", a);
return 0;
}
第一个代码运行结果为打印了25次hehe
第二个代码运行结果为打印了5次hehe
这是因为第一个代码中, i 和j 的初始值为0,外层循环 i =0时,内层循环执行5次,当外层循环 i =1 时,内层循环又执行5次,直到外层循环 i = 5时停止打印,总共执行25次;第二个代码中由于 j 没有初始值,当外层循环 i=0 时,内层循环从 j =0 时开始打印,直到 j=5 时停止打印,内层循环执行5次后就不再执行。
2.2 for循环执行流程
2.3 for 的循环实践
练习:在屏幕上打印1~10的数字
#include <stdio.h>
int main()
{
int i = 0;
for (i = 1; i <= 10; i++)
{
printf("%d ", i);
}
return 0;
}
3.while 循环和 for 循环 的对比
int i = 1; //初始化
while (i <= 10) //判断
{
printf("%d ", i);
i++; //调整
}
初始化 判断 调整
for (i = 1; i <= 10; i++)
{
printf("%d ", i);
}
for 循环的三个部分集中,便于代码维护,如果代码较多时,while 循环的三个部分比较分散。