> For the complete documentation index, see [llms.txt](https://ubtechedu.gitbook.io/chinese/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ubtechedu.gitbook.io/chinese/arduino-language/structure/control-structure/untitled-4.md).

# for

for语句用于重复执行一段在花括号之内的代码。通常使用一个增量计数器计数并终止循环

for语句用于重复性的操作非常有效，通常与数组结合起来使用来操作数据、引脚。

for循环开头有3个部分：

```c
for（初始化;条件;增量计数）{
    //语句
}
```

“初始化”只在循环开始执行一次。每次循环，都会检测一次条件；如果条件为真，则执行语句和“增量计数”，之后再检测条件。当条件为假时，循环终止。

### 例子 <a href="#li-zi" id="li-zi"></a>

```c
//用PWM引脚将LED变暗
int PWMpin = 10; //将一个LED与47Ω电阻串联接在10脚 
void setup(){
    //无需设置
}

void loop(){   
    for (int i=0; i <= 255; i++){      
    analogWrite(PWMpin, i);      
    delay(10);
    }
}
```

### 编程提示 <a href="#bian-cheng-ti-shi" id="bian-cheng-ti-shi"></a>

C语言的for循环语句比BASIC和其他电脑编程语言的for语句更灵活。除了分号以外，其他3个元素都能省略。同时，初始化，条件，增量计算可以是任何包括无关变量的有效C语句，任何C数据类型包括float。这些不寻常的for语句可能会解决一些困难的编程问题。

例如，在增量计数中使用乘法可以得到一个等比数列：

```c
for(int x = 2; x < 100; x = x * 1.5){
    println(x);
}
```

生成：2,3,4,6,9,13,19,28,42,63,94

另一个例子，使用for循环使LED产生渐亮渐灭的效果：

```c
void loop(){   
    int x = 1;   
    for (int i = 0; i > -1; i = i + x){
        analogWrite(PWMpin, i);      
        if (i == 255) x = -1;// 在峰值转变方向     
        delay(10);
    }
}
```
