C 语言的 do while 循环

while 和 for 循环都是入口条件循环, 即在每次循环开始之前检查测试条件, 有可能根本不执行循环体中的内容.

do...while 是出口条件循环 (exit-condition loop), 在循环的每次迭代之后检测测试条件, 所以至少执行循环体中的内容一次.

do...while 循环的通用形式:

do
{
	statement
} while (expression);

statement 可以是一条简单语句或复合语句.

do...while 以分号结尾.

do...while 适合那些至少执行一次的循环.

程序示例:

#include<stdio.h>
int main(void)
{
	int i = 0;
	do
	{
		printf("%d\n", i);
		i++;
	} while (i < 10);

	return 0;
}

结果:

0
1
2
3
4
5
6
7
8
9

程序示例:

#include<stdio.h>
int main(void)
{
	const int SECRET = 10;
	int secret;

	do
	{
		printf("Enter the secret: ");
		scanf("%d", &secret);
	} while (secret != SECRET);

	printf("You are right!\n");

	return 0;
}

结果:

Enter the secret: 12
Enter the secret: 11
Enter the secret: 10
You are right!

这个程序非常不安全, 一旦 scanf() 读取失败, 输入的内容会保留着内存中, 下一次还是这个内存中的内容, 还是会读取失败, 所以形成一个死循环.

改写为 while 入口循环:

#include<stdio.h>
int main(void)
{
	const int SECRET = 10;
	int secret;
	printf("Enter the secret: \n");
	scanf("%d", &secret);
	while (secret != SECRET)
	{
		printf("Enter the secret: \n");
		scanf("%d", &secret);
	}

	printf("You are right!\n");

	return 0;
}

结果:

Enter the secret:
12
Enter the secret:
11
Enter the secret:
10
You are right!

显然程序要更长一点.

一个死循环:

#include<stdio.h>
int main(void)
{
	int i = 1;

	do {
		if (i == 5)
			continue;
		printf("%d\n", i);
		i++;
	} while (i <= 10);

	return 0;
}

打印完 1234 后进入死循环.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值