> For the complete documentation index, see [llms.txt](https://docs.1l.lol/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.1l.lol/basics/loop.md).

# 循环结构（for / while / do-while）

### for 循环

适合**已知次数**的循环：

```cpp
for (int i = 1; i <= 5; i++) {
    cout << i << " ";
}
```

三段式：`for (初始化; 条件; 步进)`。

### while 循环

适合**条件控制**的循环：

```cpp
int n = 123, cnt = 0;
while (n > 0) {
    n /= 10;
    cnt++;
}
cout << cnt << endl;  // 3
```

### do-while 循环

**至少执行一次**，条件在后：

```cpp
int x;
do {
    cin >> x;
} while (x < 0);  // 反复输入直到 x 非负
```

### break 与 continue

* `break`：立即跳出整个循环
* `continue`：跳过本次循环剩余部分，进入下一次

```cpp
for (int i = 1; i <= 10; i++) {
    if (i == 5) continue;  // 跳过 5
    if (i == 8) break;     // 到 8 停止
    cout << i << " ";      // 输出 1 2 3 4 6 7
}
```

### 死循环

`while (true) { ... }` 配合 `break` 使用，可做“不确定次数”的循环。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.1l.lol/basics/loop.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
