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

相关推荐
火兮明兮11 分钟前
Python训练第四十五天
开发语言·python
独行soc20 分钟前
2025年渗透测试面试题总结-腾讯[实习]玄武实验室-安全工程师(题目+回答)
linux·安全·web安全·面试·职场和发展·渗透测试·区块链
我爱Jack24 分钟前
ObjectMapper 在 Spring 统一响应处理中的作用详解
java·开发语言
小白杨树树39 分钟前
【SSM】SpringMVC学习笔记8:拦截器
java·开发语言
冷心笑看丽美人42 分钟前
Spring MVC 之 异常处理
java·开发语言·java-ee·spring mvc
超级小忍43 分钟前
Java集合中Stream流的使用
java·开发语言
搏博1 小时前
将图形可视化工具的 Python 脚本打包为 Windows 应用程序
开发语言·windows·python·matplotlib·数据可视化
int型码农1 小时前
数据结构第八章(二)-交换排序
c语言·数据结构·算法·排序算法
zm1 小时前
极限复习c++
开发语言·c++
追风赶月、1 小时前
【QT】认识QT
开发语言·qt