天天看點

C++循環控制C++循環控制

C++循環控制

循環可以通過你給定的一個條件,重複的做一件事情,c++中有while,do-while,for三種循環控制。

while

  • 文法
while (循環執行的條件) {
	// 循環中需要做的事情
}
           
  • 例子
#include <iostream>


int main() {
    int cout = 0;
    // 循環輸出十次"我錯了"
    while (cout < 10) {
        std::cout << "我錯了" << std::endl;
        cout += 1;
    }
    return 0;
}
           

do-while

do-while和while循環最主要的差別在于:

​ do-while不論小括号中的條件是什麼,都會先執行一次循環中的代碼,之後再判斷小括号中的條件是否滿足。

​ while則會先判斷循環執行的條件,滿足就執行循環,不滿足就不執行。

  • 文法
do {
	// 循環需要做的事情
} while (循環執行的條件);
           
  • 例子
#include <iostream>


int main() {

    int count = 0;
    do {
        // 循環輸出十次"It's all my fault."
        std::cout << "It's all my fault." << std::endl;
        count++;
    } while (count < 10);

    return 0;
}
           

for

再日常編寫代碼的過程中,for循環往往是使用頻率最高的一個。

for循環主要用于已知循環次數的時候,如周遊字元串和數組時,相較于while循環會友善很多。

while循環用于循環次數未知,或者循環的進行需要滿足特定條件的時候。

  • 文法
for (init;condition;increment) {
	// 需要做的事情
}

// init:首先被執行的代碼,而且隻執行一次,通常會聲明一個為0的變量,用來擷取數組或字元串中對應下标的資料。
// condition:條件判斷語句,如果為True就會繼續循環,如果為False就會結束循環。
// increment:再執行完一次for循環中的代碼之後,會執行increment的代碼,用來控制循環的次數。
//
// init,condition,increment都可以不寫,但是中間用來分割的';'一定要寫。 
           
  • 例子
#include <iostream>

int main() {    
    // 循環輸出十次"Winter Is Coming"
    for (int count = 0; count < 10; count++) {
        std::cout << "Winter Is Coming" << std::endl;
    }

    return 0;
}
           

continue和break

當循環遇到特殊情況需要跳過本次循環,或是結束循環時,就需要用到continue和break。
  • 文法
用在循環中
           
  • 例子
#include <iostream>

int main() {
    int num = 1;
    while (num <= 10) {
        // 如果num=5,就使用continue跳過本次循環。
        if (num == 5) {
            // 如果時while循環,這裡需要給循環調節執行+=1。
            // 因為while循環并不像for循環一樣,while的continue會直接進行下一次的循環判斷,
            // 而for循環則會執行一次increment中的代碼,
            // 這是while和for循環的一個差別,也是while循環使用頻率低的一個潛在原因
            num++;
            continue;
        }
        // 如果num=8,就是用continue結束本次循環
        if (num == 8) {
            break;
        }
        std::cout << "目前的num值 = " << num << std::endl;
        num++;
    }

    for (int i = 1; i <= 10; i++) {
        // 如果i=5,就使用continue跳過本次循環。
        if (i == 5) {
            continue;
        }
        // 如果i=8,就是用continue結束本次循環
        if (i == 8) {
            break;
        }
        std::cout << "目前的i值 = " << i << std::endl;
    }

    return 0;
}
           

繼續閱讀