# 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);
    }
}
```


---

# Agent Instructions: Querying This Documentation

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

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://ubtechedu.gitbook.io/chinese/arduino-language/structure/control-structure/untitled-4.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
