C++ 中的 For 迴圈與 While 迴圈


程式設計中的迴圈用於多次計算一段程式碼。在這裡,我們將看到程式中兩種型別的迴圈之間的區別,For 迴圈和 While 迴圈

For 迴圈

For 迴圈 是一種重複控制迴圈,允許使用者迴圈執行給定的程式碼塊特定次數。

語法

for(initisation; condition; update){
   …code to be repeated
}

While 迴圈

While 迴圈是一種入口控制迴圈,允許使用者重複執行給定的語句,直到給定的條件為真。

語法

while(condition){
   …code to be repeated
}

For 迴圈和 While 迴圈的區別

  • For 迴圈是迭代控制迴圈,而 While 迴圈是條件控制迴圈。

  • For 迴圈的條件語句允許使用者在其中新增更新語句,而 While 迴圈的條件語句只能寫入控制表示式。

  • For 迴圈中的測試條件通常是整數比較,而在 While 迴圈中,測試條件可以是任何其他計算結果為布林值的表示式。

兩個迴圈都可以提供不同解決方案的程式碼

一個例子是,迴圈體包含一個 continue 語句,該語句在 While 迴圈中的更新語句之前,但在 For 迴圈中,更新語句本身就在初始化中。

示例

程式說明解決方案的工作原理:(For 迴圈)

#include<iostream>
using namespace std;

int main(){

   cout<<"Displaying for loop working with continue statement\n";
   for(int i = 0; i < 5; i++){
      if(i == 3)
      continue;
      cout<<"loop count "<<i<<endl;
   }
   return 0;
}

輸出

Displaying for loop working with continue statement
loop count 0
loop count 1
loop count 2
loop count 4

示例

程式說明解決方案的工作原理:(While 迴圈)

#include<iostream>
using namespace std;

int main(){

   cout<<"Displaying for loop working with continue statement";
   int i = 0;
   while(i < 5){
      if(i == 3)
      continue;
      cout<<"loop count "<<i<<endl;
      i++;
   }
   return 0;
}

輸出

Displaying for loop working with continue statementloop count 0
loop count 1
loop count 2

更新於:2022年2月1日

157 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始
廣告