C语言中do-while语句的2种写法示例

所属分类: 软件编程 / C 语言 阅读数: 99
收藏 0 赞 0 分享

while循环和for循环都是入口条件循环,即在循环的每次迭代之前检查测试条件,所以有可能根本不执行循环体中的内容。C语言还有出口条件循环(exit-condition loop),即在循环的每次迭代之后检查测试条件,这保证了至少执行循环体中的内容一次。这种循环被称为do while循环。

看下面的例子:

#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;
}

运行结果:

To enter the triskaidekaphobia therapy club,

please enter the secret code number: 12

To enter the triskaidekaphobia therapy club,

please enter the secret code number: 14

To enter the triskaidekaphobia therapy club,

please enter the secret code number: 13

Congratulations! You are cured!

使用while循环也能写出等价的程序,但是长一些,如程序清单6.16所示。

#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循环的通用形式:

do
 statement
while ( expression );

statement可以是一条简单语句或复合语句。注意,do-while循环以分号结尾。

Structure of a =do while= loop=

do-while循环在执行完循环体后才执行测试条件,所以至少执行循环体一次;而for循环或while循环都是在执行循环体之前先执行测试条件。do while循环适用于那些至少要迭代一次的循环。例如,下面是一个包含do while循环的密码程序伪代码:

do
{
 prompt for password
 read user input
} while (input not equal to password);

避免使用这种形式的do-while结构:

do
{
 ask user if he or she wants to continue
 some clever stuff
} while (answer is yes);

这样的结构导致用户在回答“no”之后,仍然执行“其他行为”部分,因为测试条件执行晚了。

总结

更多精彩内容其他人还在看

java 中ArrayList与LinkedList性能比较

这篇文章主要介绍了java 中ArrayList与LinkedList性能比较的相关资料,需要的朋友可以参考下
收藏 0 赞 0 分享

麻将游戏算法深入解析及实现代码

这篇文章主要介绍了麻将游戏算法深入解析及实现代码的相关资料,需要的朋友可以参考下
收藏 0 赞 0 分享

C++中的explicit关键字实例浅析

在C++程序中很少有人去使用explicit关键字,不可否认,在平时的实践中确实很少能用的上,再说C++的功能强大,往往一个问题可以利用好几种C++特性去解决。接下来给大家介绍 C++中的explicit关键字,需要的朋友可以参考下
收藏 0 赞 0 分享

C语言 二叉查找树性质详解及实例代码

这篇文章主要介绍了C语言 二叉查找树性质详解及实例代码的相关资料,需要的朋友可以参考下
收藏 0 赞 0 分享

数据结构 双向链表的创建和读取详解及实例代码

这篇文章主要介绍了数据结构 双向链表的创建和读取详解及实例代码的相关资料,需要的朋友可以参考下
收藏 0 赞 0 分享

C语言 数据结构双向链表简单实例

这篇文章主要介绍了C语言 数据结构双向链表简单实例的相关资料,需要的朋友可以参考下
收藏 0 赞 0 分享

VC使用编译时间作为版本号标识的方法

这篇文章主要介绍了VC使用编译时间作为版本号标识的方法,需要的朋友可以参考下
收藏 0 赞 0 分享

c++利用stl set_difference对车辆进出区域进行判定

这篇文章主要介绍了set_difference,用于求两个集合的差集,结果集合中包含所有属于第一个集合但不属于第二个集合的元素,需要的朋友可以参考下
收藏 0 赞 0 分享

c++ STL set_difference set_intersection set_union 操作

这篇文章主要介绍了c++ STL set_difference set_intersection set_union 操作,需要的朋友可以参考下
收藏 0 赞 0 分享

c/c++ 奇技淫巧(一些c语言的技巧)

这篇文章主要介绍了c/c++ 奇技淫巧,需要的朋友可以参考下
收藏 0 赞 0 分享
查看更多