C/C++之do while循环

       while循环和for循环都是入口条件循环,即在循环的每次迭代之前检查测试条件,所以有可能根本不执行循环体中的内容。C语言还有出口条件循环(exit-condition loop),即在循环的每次迭代之后检查测试条件,这保证了至少执行循环体中的内容一次。这种循环被称为do while循环。如下程序演示了一个示例。
#include <stdio.h>
int main(void)
{
     const int secret_code = 13;
     int code_entered;

     do
     {
          printf("To enter the triskaidekaphobia 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;
}

       在用户输入13之前不断提示用户输入数字。

下面是一个运行结果:

To enter the triskaidekaphobia therapy club,
please enter the secret code number: 12
To enter the triskaidekaphobia therapy club,
please enter the secret code number: 14
To enter the triskaidekaphobia therapy club,
please enter the secret code number: 13
Congratulations! You are cured!
        使用while循环也能写出等价的程序,但是长一些,如下程序所示。
#include <stdio.h>
int main(void)
{
     const int secret_code = 13;
     int code_entered;

     printf("To enter the triskaidekaphobia therapy club,\n");
     printf("please enter the secret code number: ");
     scanf("%d", &code_entered);
     while (code_entered != secret_code)
     {
          printf("To enter the triskaidekaphobia 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 );

       statement可以是一条简单语句或复合语句。注意,do while循环以分号结尾,do while循环的结构在执行完循环体后才执行测试条件,所以至少执行循环体一次;而for循环或while循环都是在执行循环体之前先执行测试条件。do while循环适用于那些至少要迭代一次的循环。例如,下面是一个包含do while循环的密码程序伪代码: do
{
     提示用户输入密码
     读取用户输入的密码
} while (用户输入的密码不等于密码);
 避免使用这种形式的do while结构:

do
{
     询问用户是否继续
     其他行为
} while (回答是yes);

       这样的结构导致用户在回答“no”之后,仍然执行“其他行为”部分,因为测试条件执行晚了。 小结:do while语句 关键字:do while 一般注解: do while语句创建一个循环,在expression为假或0之前重复执行循环体中的内容。do while语句是一种出口条件循环,即在执行完循环体后才根据测试条件决定是否再次执行循环。因此,该循环至少必须执行一次。statement部分可是一条简单语句或复合语句。

 

  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小枭码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值