> For the complete documentation index, see [llms.txt](https://labspc.gitbook.io/cnippets/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://labspc.gitbook.io/cnippets/chap3.-kong-zhi-liu/3.5-while-xun-huan-yu-ju-yu-for-yu-ju.md).

# 3.5 while 循环语句与 for 语句

在这一节中，我们请自行回顾 Chap1 里使用 while 和 for 循环的例子。

<figure><img src="https://labspc.com/wp-content/uploads/2024/01/1705732475-word-image-307-1.png" alt=""><figcaption></figcaption></figure>

上述说明可以看成是一个惯例，下面两个具体使用 while 和 for 的例子证实了这一点。

### 3.5.1 while 循环 <a href="#l8o10" id="l8o10"></a>

```c
while (条件) {
    // 循环体，当条件为真时执行
}
```

可以回看 1.2 节，温度转换的例子。

{% code title="3.5.1 fahr-cel-while.c" lineNumbers="true" %}

```c
#include <stdio.h>
int main()
{
    int fahr, cel;
    int lower, upper, step;
    lower = 0;   // 最低温度
    upper = 300; // 最高温度
    step = 20;   // 步长

    fahr = lower;
    while (fahr <= upper)
    {
        cel = 5 * (fahr - 32) / 9;
        printf("%d\t%d\n", fahr, cel);
        fahr = fahr + step;
    }
    return 0;
}
```

{% endcode %}

```
➜  
0	-17
20	-6
40	4
60	15
80	26
100	37
120	48
140	60
160	71
180	82
200	93
220	104
240	115
260	126
280	137
300	148
```

### 3.5.2 for 循环 <a href="#zprdd" id="zprdd"></a>

```c
for (初始化; 条件; 更新) {
    // 循环体，当条件为真时执行
}
```

可以回看 1.3 节，温度转换的例子。

{% code title="3.5.2 fahr-cel-for.c" lineNumbers="true" %}

```c
#include <stdio.h>
int main()
{
    int fahr, cel;
    int lower, upper, step;
    lower = 0;   // 最低温度
    upper = 300; // 最高温度
    step = 20;   // 步长

    for (fahr = lower; fahr <= upper; fahr = fahr + step)
    {
        cel = 5 * (fahr - 32) / 9;
        printf("%d\t%d\n", fahr, cel);
    }

    return 0;
}
```

{% endcode %}

使用 for 的惯用法：

```c
for (i=0;i<n;i++)
    ...
```

处理数组前 n 个元素

### 3.5.3 for 和 while 的转化 <a href="#xpsg8" id="xpsg8"></a>

♻️ 我们可以尝试把一个 for 循环转化成一个 while 循环，也可以倒过来。

### 3.5.4 for 的几个惯用法 idioms

从 0 向上加到 n-1：

```c
for (i=0;i<n;i++)
```

从 1 向上加到 n：

```c
for (i=1;i<=n;i++)
```

从 n-1 向下减到 0:

```c
for (i=n-1;i>=0;i--)
```

从 n 向下减到 1:

```c
for (i=n;i>0;i--)
```
