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

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
}
posted @ 2015-08-11 13:48  programnote  阅读(753)  评论(0编辑  收藏  举报