> For the complete documentation index, see [llms.txt](https://acezxn.gitbook.io/vex-ji-qi-ren-cheng-shi-jiao-xue/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://acezxn.gitbook.io/vex-ji-qi-ren-cheng-shi-jiao-xue/ji-chu-jiao-xue/luo-ji-kong-zhi/for-while-hui-quan.md).

# for while 迴圈

for, while迴圈是一個程式語法，用來重複部分程式

## 重複 n 次 ：for loop

以下迴圈會先設 i = 0，重複顯示 "hello" 直到 i = 5，一共執行 5 次

```cpp
for (int i = 0; i < 5; i++) {
    printf("hello\n");
}
```

以下迴圈會枚舉在array裡的所有元件

```cpp
int array[5] = {1, 2, 3, 4, 5};

for (int number : array) {
    printf("%d\n", number);
}
```

## 重複直到條件達成：while loop

以下迴圈會先設 i = 0，重複顯示 "hello" 直到 i = 5，一共執行 5 次

```cpp
int i = 0;

while (i < 5) {
    printf("hello\n");
    i++;
}
```

以下為無限迴圈，如果 keep running 是 true，則會一直迴圈下去

```cpp
while (keep_running) {
    // run something until keep_running is false
}
```

也可以用 break 退出迴圈

```cpp
while (true) {
    if (should_exit()) {
        break; // leave the loop
    }
}
```
