while循环和for循环是入口条件循环,还有出口条件循环do while
do while出口条件循环
演示一个示例:
/* do_while.c -- 出口条件循环*/
#include <stdio.h>
int main (void)
{
const int secret_code = 13;
int code_entered;
do
{
printf("To enter the troskaidekaphobia therapy club,\n");
printf("please enter the secret code number:");
scanf("%d",&code_entered);
}while (code_entered != secret_code);
printf("Congratulations! You are cured!\n");
return 0;
}
只应该是一个猜数字的程序。。。
To enter the troskaidekaphobia therapy club,
please enter the secret code number:6
To enter the troskaidekaphobia therapy club,
please enter the secret code number:66
To enter the troskaidekaphobia therapy club,
please enter the secret code number:666
To enter the troskaidekaphobia therapy club,
please enter the secret code number:13
Congratulations! You are cured!
如果使用while循环,程序会比这长一些。
/* entry.c -- 出口条件循环*/
#include <stdio.h>
int main (void)
{
const int secret_code = 13;
int code_entered;
printf("To enter the troskaidekaphobia therapy club,\n");
printf("please enter the secret code number:");
scanf("%d",&code_entered);
while (code_entered != secret_code);
{
printf("To enter the troskaidekaphobia therapy club,\n");
printf("please enter the secret code number:");
scanf("%d",&code_entered);
}
printf("Congratulations! You are cured!\n");
return 0;
}
就像这样,把块里的内容,放到前面先运行一遍,这个程序的结果和上面一样。
下面是do while循环的通用形式:
do
statement
while ( expression );
其实和其它两个循环差不多,知识do while循环最后要以分号结尾
书上还介绍了do while循环的伪代码:
do
{
提示用户输入密码
读取用户输入的密码
}while (用户输入的密码不等于);
避免使用这种形式的do while结构:
do
{
询问用户是否继续
其他行为
}while (回答是yes);
这样的结构导致用户在回答“no”之后 ,仍然执行“其他行为”部分,因为测试条件晚了。