while循环
语法:
while(表达式)
循环语句;
- 例题:打印1-10的数字。
#include<stdio.h>
int main()
{
int i = 1;
while (i<=10)
{
printf("%d", i);
i++;
}
system("pause");
return 0;
}
输出结果:
- break在while中的作用:在循环中只要遇到break,直接终止循环。
#include<stdio.h>
int main()
{
int i = 1;
while (i < 10)
{
if (i == 5)
break;
printf("%d", i);
i++;
}
system("pause");
return 0;
}
输出结果:
- continue在while循环中的作用:终止本次循环。
for循环
语法:
for(初始条件;条件判断;循环条件的调整)
循环语句;
- 打印1-10的数字。
#include<stdio.h>
int main()
{
int i = 0;
for (i = 1; i <= 10; i++)
printf("%d", i);
system("pause");
return 0;
}
输出结果:
- for循环中的break和continue与while循环中类似。
注意:不可在for循环体中修改循环变量,防止for循环市区控制。
do...while()循环
语法:
do
循环语句;
while(表达式);
#include<stdio.h>
int main()
{
int i = 10;
do
{
printf("%d", i);
} while (i < 10);
system("pause");
return 0;
}
输出结果:
循环至少执行一次。
- 在多重循环中,应该将最长的循环放在最内侧,最短的放在最外侧,减少CPU跨切循环层的次数
- 如果循环体内存在逻辑判断,且循环次数很大,将逻辑判断放到循环体的外边