从零开始学C语言系列之第五章《do while》

往期回顾

1.【第一章】《认识C语言》
2.【第二章】C语言概述及基本知识1
3.【第二章】C语言概述及基本知识2
4.【第三章】字符串和格式化输入/ 输出
5.【第三章】 printf
6.【第三章】 scanf
7.【第三章】 putchar
8.【第三章】 getchar
9.【第三章】 sizeof
10.【第三章】 strlen
11.【第三章】 define
12.【第四章】运算符第一节
13.【第四章】运算符第二节
14.【第四章】运算符第三节
15.【第四章】运算符第四节
16.【第四章】类型转换
17.【第四章】函数与转化
18.【第五章】while
19.【第五章】for开篇
20.【第五章】for的灵活性
21.【第五章】逗号运算符


文章目录


do while

​   while循环和 for循环都是入口条件循环,即在循环的每次迭代之前检查测试条件,所以有可能根本不执行循环体中的内容。C语言还有出口条件循环,即在循环的每次迭代之后检查测试条件,这保证了至少执行循环体中的内容一次。这种循环被称为do while循环。

​   do while 语句创建一个循环,在expression为假或0之前重复执行循环体中的内容。do while语句是一种出口条件循环,即在执行完循环体后才根据测试条件决定是否再次执行循环。因此,该循环至少必须执行一次。

格式:

c 复制代码
do
{         
   statement;
}While(expression );

在expression为假或0之前,重复执行statement部分。

例子:

c 复制代码
#include <stdio.h>
int main()
{
	int i=1,sum=0;
	do
	{
		sum+=i;
		i++;	
	}while(i<=24);
	printf("%d",sum);
	return 0; 
 } 

如果是while写的

c 复制代码
#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写的:

c 复制代码
#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;
}

  do while循环在执行完循环体后才执行测试条件,所以至少执行循环体一次;而 for 循环或 while循环都是在执行循环体之前先执行测试条件。do while循环适用于那些至少要迭代一次的循环。例如,下面是一个包含do while循环的密码程序伪代码:

相关推荐
狂师9 小时前
比 Playwright 更给力,推荐一个AI Agent的浏览器自动化开源项目!
前端·开源·测试
AI袋鼠帝11 小时前
开源「仓颉.Skill」2.0,你现在可以蒸馏任何视频!
开源·aigc
冬奇Lab1 天前
每日一个开源项目(第146篇):openpilot - 开源自动驾驶辅助系统,曾在 Consumer Reports 评测中超过特斯拉 Autopilot
人工智能·开源·自动驾驶
她的男孩1 天前
后台接口加密别只会 HTTPS,ForgeAdmin 的 RSA + SM4/AES 源码拆解
后端·面试·开源
fthux1 天前
如果你用 Mac,那你可能需要 Noti Shift
macos·开源·github
努力的小雨2 天前
我用 QClaw 做了个 Web3 陪学助手,专治 Java 程序员的“概念劝退”
经验分享·ai智能
冬奇Lab2 天前
每日一个开源项目(第145篇):Trellis - 把项目记忆、规范和任务上下文持久化进代码仓库
人工智能·开源·资讯
小爷毛毛_卓寿杰2 天前
我把一个 3B 模型塞进了 Xinference,然后它干掉了 DeepSeek V3.2
人工智能·开源·github
饼干哥哥2 天前
扣子3.0测评:我让 Codex 和 Claude Code 住同一个桌面,结果它们打架了!
人工智能·开源·代码规范