for 語法敘述
描述
for 是用來重覆執行一個被大括號包住的程式碼區塊,通常會使用一個持續增加的計數器去判斷何時要結束這個迴圈。for 除了用於重覆執行程式碼,也常用在處理陣列內的資料。
for 迴圈的開頭包含三個部分:
for (initialization ; condition ; increment)
{
//statement(s);
}

initialization 只會在進入迴圈前執行一次。每次區塊內程式結束後都會去判斷 condition 是否成立,如果 condition 成立就重覆執行區塊內程式以及 increment,反之則離開迴圈。(格式與C語言等常用語言相同,且可以於初始化時宣告變數型態)
範例
// 使用 PWM 控制 LED
int PWMpin = 10; // LED 燈與 470 歐姆的電阻串聯於 pin 腳 10
void setup()
{
// 不需任何動作
}
void loop()
{
for (int i=0; i <= 255; i++) {
analogWrite(PWMpin, i);
delay(10);
}
}
提醒
與其他的程式語言相比,C 語言的 for 迴圈較具有彈性。在 for 迴圈開頭的三項設定皆可以省略,但仍須保留分號。且 for 迴圈開頭的三項設定並不限制僅可使用在與迴圈執行相關的變數,也不限制變數的資料型態。這在解決某些問題時可以提供很大的幫助。
這個例子中我們使用乘法來遞增計數器去產生一個對數級數:
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 燈的漸明與漸暗控制:
void loop()
{
int x = 1;
for (int i = 0; i > -1; i = i + x) {
analogWrite(PWMpin, i);
if (i == 255) x = -1; // 在 PWM 極限值 255 會切換
delay(10);
}
}
See also
- while
本頁由熱血青年 LBU 譯自英文版。
The text of the 86Duino reference is a modification of the Arduino reference, and is licensed under a Creative Commons Attribution-ShareAlike 3.0 License. Code samples in the reference are released into the public domain.
