C语言有三种循环方式,除了前面讲过的for循环外,还有while和do while两种形式。

(一)while循环

#include <stdio.h>

int main()
{
int i = 3;
while(i > 0)
{
i--;
printf("Excute loop! After decrementing, i = %d\n", i);
}

return 0;
}

运行结果:

Excute loop! After decrementing, i = 2
Excute loop! After decrementing, i = 1
Excute loop! After decrementing, i = 0

(二)do while循环

#include <stdio.h>

int main()
{
int i = 3;
do
{
i--;
printf("Excute loop! After decrementing, i = %d\n", i);
} while(i > 0);

return 0;
}

运行结果:

Excute loop! After decrementing, i = 2
Excute loop! After decrementing, i = 1
Excute loop! After decrementing, i = 0

(三)二者的区别

1 do while

#include <stdio.h>

int main()
{
int i = 0;
do
{
i--;
printf("Excute loop! After decrementing, i = %d\n", i);
} while(i > 0);

printf("Porgram end!");

return 0;
}

运行结果:

Excute loop! After decrementing, i = -1
Program end!

2 while

#include <stdio.h>

int main()
{
int i = 0;
while(i > 0)
{
i--;
printf("Excute loop! After decrementing, i = %d\n", i);
}

printf("Porgram end!");

return 0;
}

运行结果:

Porgram end!

从以上两个程序可以看出,while是先判断条件,再执行循环里的语句。而do while是先执行循环里的语句,再判断循环条件。
do while至少会执行一次循环;而while若第一次判断条件不成立时,一次循环都不会执行。


更多内容请关注微信公众号

小朋友学C语言(22):循环_微信公众号