C語言中不同類型的迴圈(Different types of loops in C)

來源:互聯網
上載者:User

標籤:

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" twicefor (int x = 0; x < 100; x++){    if (x == 2)    {        break;    }    //do stuff}

continue語句的作用是終止當前的迭代,直接跳到下次迭代。

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

C語言中不同類型的迴圈(Different types of loops in C)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.