一、什麼是break關鍵字?
在C++中,break是一種關鍵字,可用於各種循環語句中進行中斷。當程序執行到break語句時,循環將會立即終止,程序控制流將轉移至循環體之後的下一條語句。
使用break可以提高程序性能,避免不必要的循環操作,對於需要在滿足某一條件時立即終止循環的情況非常有用。
二、在for循環中使用break
在for循環中使用break通常表示在找到所需元素後跳出循環。例如,以下代碼演示了如何在數組中查找指定元素:
#include int main() { int arr[] = { 1, 2, 3, 4, 5 }; int num = 3; bool found = false; for (int i = 0; i < 5; i++) { if (arr[i] == num) { found = true; break; } } if (found) { std::cout << "Number found in array" << std::endl; } else { std::cout << "Number not found in array" << std::endl; } return 0; }
在以上代碼中,for循環遍曆數組中的元素,一旦找到指定元素,就將found標記設置為true,然後使用break跳出循環。如果找到了指定元素,程序就輸出”Number found in array”,否則輸出”Number not found in array”。
三、在while循環中使用break
在while循環中使用break通常表示在找到所需條件後跳出循環。例如,以下代碼演示了如何在while循環中動態生成隨機數,直到生成了指定數量的偶數:
#include #include #include int main() { srand(time(NULL)); int count = 0; while (count < 5) { int num = rand() % 100; if (num % 2 == 0) { count++; std::cout << num << " "; } if (count == 5) { break; } } return 0; }
在以上代碼中,while循環用於生成隨機數。使用if語句檢查隨機數是否為偶數,如果是,則將計數器count加1並輸出該隨機數。一旦找到了指定數量的偶數(在本例中為5個),程序就使用break跳出循環。
四、在嵌套循環中使用break
在嵌套循環中使用break通常表示在滿足某些條件時跳出所有循環,即跳出外層循環和內層循環。例如,以下代碼演示了如何在二維數組中查找到指定元素的位置:
#include int main() { int arr[3][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; int num = 5; int row = -1; int col = -1; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (arr[i][j] == num) { row = i; col = j; break; } } if (row != -1 && col != -1) { break; } } if (row != -1 && col != -1) { std::cout << "Number found at row " << row << " and column " << col << std::endl; } else { std::cout << "Number not found in array" << std::endl; } return 0; }
在以上代碼中,內層循環遍歷二維數組中的元素,一旦找到指定元素,就將其行列位置保存下來,然後使用兩個break跳出外層循環和內層循環。如果找到了指定元素,程序就輸出”Number found at row x and column y”,否則輸出”Number not found in array”。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/304466.html