从零开始学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循环的密码程序伪代码:

相关推荐
catchadmin10 分钟前
PHP 在领域驱动(DDD)设计中的核心实践
开发语言·php
BomanGe217 分钟前
NSK直线导轨LH55EL与NH55EM替代指南
前端·javascript·数据库·经验分享·规格说明书
旅僧18 分钟前
机械臂学习笔记(更新中)
笔记·学习
SilentSamsara25 分钟前
MLflow 实验追踪与模型注册:从实验到生产的可复现工作流
开发语言·人工智能·pytorch·python·青少年编程
qingwufeiyang_53031 分钟前
Python学习笔记3-项目实战-AI应用
笔记·学习
dongf201931 分钟前
R语言朴素贝叶斯算法---iris数据集
开发语言·算法·数据分析·r语言
下班走回家34 分钟前
RAG 技术的进化:从朴素检索到 Agentic RAG
开发语言·人工智能·python
weixin_3077791335 分钟前
从“大海捞针”到“主动推理”:AI如何重塑云原生故障诊断的根因链
开发语言·人工智能·算法·自动化·原型模式
Johnstons35 分钟前
网页加载到一半卡住?视频看到关键处花屏?可能是丢包在作祟
开发语言·php·音视频·弱网测试·网络损伤