• C Primer Plus(6) 中文版 第6章 C控制语句:循环 6.8 出口条件循环:do while


    6.8 出口条件循环:do while
    C语言出口条件循环(exix-condition loop),即在循环的每次迭代之后检查测试条件,这保证了至少执行循环体中的内容一次。这种循环被称为do while循环。
    /* do_while.c -- exit condition loop */
    #include
    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;

    /* 输出:

    */

    使用while循环也能写出等价的程序,但是长一些。
    /* entry.c -- entry condition loop */
    #include
    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( 回答是yes );
    这样的结构导致用户在回答“no”之后,仍然执行“其他行为”部分,因为测试条件执行晚了。
    小结:do while语句
    do while语句创建一个循环,在expression为假或0之前重复执行循环体中的内容。

  • 相关阅读:
    网工知识角|轻松拿offer【网工面试题】三层交换机与路由器有什么区别?
    问题 B: Ella的密码——map
    题目0158-快递业务站
    什么是堡垒机
    【MindSpore易点通】如何保存模型进行checkpoint对比以及Print算子使用说明
    【C++】【LeetCode】【二叉树的前序、中序、后序遍历】【递归+非递归】
    Centos7安装KingBaseES9(人大金仓V9)
    【C语言数据结构】线性表-顺序存储-动态分配(顺序表)
    数据可视化
    智能abc是什么输入法:win10可用的智能abc输入法免费下载
  • 原文地址:https://blog.csdn.net/weixin_40186813/article/details/126202189