標籤:
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)