循环语句大体分为三种,while,for,do while。三种语句各有优缺。
在三种循环语句中,for循环语句是其中最简单的循环语句,for的操作形式如下:
for(; ;){ }其中小括号中从左到右分别是单次表达式,循环条件,末次循环体,大括号中的是中间循环体,就是在循环中需要做的事。
一般来说,我们会在单次表达式中给一个初始值,然后在后来的末次循环体去改变这个值,当循环条件不符时,循环结束。例如下面的求1000~2000年间的闰年的代码。
#include <stdio.h>
int main()
{
int a = 0;
for (a = 1000; a <= 2000; a++)
{
if (a % 4 == 0)
{
if (a % 400 == 0)
printf("%d\n", a);
else if (a % 100 != 0)
printf("%d\n", a);
}
}
return 0;
}
a表示初始的值,a<=2000为循环条件,a++为末次循环体,用来改变a。
while循环比for循环稍微复杂点,但可以表示一些特定环境的循环。while的操作形式如下:
while( ){ }。在小括号中的为while循环的循环条件,大括号和for循环中的大括号作用一样。
while循环和for循环的操作有一定的区别。
#include <stdio.h>
int main()
{
int a =1000;
while(a<=2000)
{
if (a % 4 == 0)
{
if (a % 400 == 0)
printf("%d\n", a);
else if (a % 100 != 0)
printf("%d\n", a);
a++
}
}
return 0;
}
while循环没有特定位置来放末次循环体,所以a++这个末次循环体要放在while循环大括号的末尾。
do while循环其实与while循环区别不大,它的操作型式为do {}while()。do while循环不管如何都会循环一次,因为它的循环条件在最后,只有经过一次循环后才会判定循环条件是否成立
#include <stdio.h>
int main()
{
int a =1000;
do
{
if (a % 4 == 0)
{
if (a % 400 == 0)
printf("%d\n", a);
else if (a % 100 != 0)
printf("%d\n", a);
a++
}
}while(a<=2000)
return 0;
}
do while循环的使用中一定要注意a的值,一不小心就会出bug。