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

相关推荐
花海如潮淹2 分钟前
前端性能追踪工具:用户体验的毫秒战争
前端·笔记·ux
Andy杨1 小时前
20250718-5-Kubernetes 调度-Pod对象:重启策略+健康检查_笔记
笔记·容器·kubernetes
古月-一个C++方向的小白5 小时前
C++11之lambda表达式与包装器
开发语言·c++
沐知全栈开发5 小时前
Eclipse 生成 jar 包
开发语言
杭州杭州杭州6 小时前
Python笔记
开发语言·笔记·python
tanyongxi667 小时前
C++ AVL树实现详解:平衡二叉搜索树的原理与代码实现
开发语言·c++
棐木8 小时前
【C语言】动态内存管理
c语言·free·malloc·realloc·calloc·动态内存
阿葱(聪)8 小时前
java 在k8s中的部署流程
java·开发语言·docker·kubernetes
浮生带你学Java8 小时前
2025Java面试题及答案整理( 2025年 7 月最新版,持续更新)
java·开发语言·数据库·面试·职场和发展