从零开始学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 小时前
【运维经验】服务器磁盘做镜像的方法
运维·服务器·windows·经验分享
麒qiqi3 小时前
理解 Linux IO 多路复用
开发语言·数据库
MediaTea3 小时前
Python:模块 __dict__ 详解
开发语言·前端·数据库·python
自然常数e3 小时前
字符函数和字符串函数
c语言·算法·visual studio
山上三树3 小时前
main()函数带参数的用法
linux·c语言
代码or搬砖4 小时前
HashMap源码
开发语言·python·哈希算法
星辰_mya4 小时前
reids哨兵集群与选主
java·开发语言
星轨初途4 小时前
郑州轻工业大学2025天梯赛解题
c++·经验分享·笔记·算法·链表·剪枝
期待のcode4 小时前
Java的多态
java·开发语言
lengjingzju4 小时前
一网打尽Linux IPC(一):进程间通信完全指南——总体介绍
linux·服务器·c语言