码迷,mamicode.com
首页 > 编程语言 > 详细

C语言中不同类型的循环(Different types of loops in C)

时间:2015-08-11 15:33:16      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:

C语言中有三种类型的循环:for,while,do-while。

while循环先判断循环条件。

while (condition)
{
    //gets executed after condition is checked
}

do-while循环先执行循环体重的语句,再判断循环条件。

do
{
    //gets executed at least once
} while (condition);

for循环可以一行中初始化一个计数变量,设置一个判断条件,和计数变量的自增。

for (int x = 0; x < 100; x++)
{
    //executed until x >= 100
}

归根到底它们都是循环,但如何执行这些循环还有一些灵活的变化。


for循环看起来最舒服,因为他最精确。

for (int x = 0; x < 100; x++)
{
    //executed until x >= 100
}

为了将上面的for循环改写成while循环,你需要这样:

int count = 0;
while (count < 100)
{
    //do stuff
    count++;
}

这种情况下,也许你会在count++;下面添加一些别的内容。这样count在什么地方自增就要考虑清楚,实在逻辑比较之后还是之前?在for循环中计数变量每一次自增都在下一次迭代之前,这会让你的代码保持某种一致性。

break与continue语句

break语句的作用是终止当前的循环(直接跳到循环体外),当前循环的所有迭代都会停止。

//will only run "do stuff" twice
for (int x = 0; x < 100; x++)
{
    if (x == 2)
    {
        break;
    }
    //do stuff
}

continue语句的作用是终止当前的迭代,直接跳到下次迭代。

//will run "do stuff" until x >= 100 except for when x = 2
for (int x = 0; x < 100; x++)
{
    if (x == 2)
    {
        continue;
    }
    //do stuff
}

C语言中不同类型的循环(Different types of loops in C)

标签:

原文地址:http://www.cnblogs.com/programnote/p/4720802.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!