[Control Structures]
説明
The for statement is used to repeat a block of statements enclosed in curly braces. An increment counter is usually used to increment and terminate the loop. The for statement is useful for any repetitive operation and is often used in combination with arrays to operate on collections of data/pins.
for ループ ヘッダーには 3 つの部分があります。
for (initialization ; condition ; increment)
{
//statement(s);
}
The initialization happens first and exactly once. Each time through the loop, the condition is tested; if it’s true, the statement block, and the increment is executed, then the condition is tested again. When the condition becomes false, the loop ends.
例
// Dim an LED using a PWM pin
int PWMpin = 10; // LED in series with 470 ohm resistor on pin 10
void setup()
{
// no setup needed
}
void loop()
{
for (int i=0; i <= 255; i++) {
analogWrite(PWMpin, i);
delay(10);
}
}Coding Tips
C言語のforループは、BASICなどの他のコンピュータ言語のforループよりもはるかに柔軟です。3つのヘッダー要素は、セミコロンは必須ですが、一部または全部を省略できます。また、初期化、条件、増分の各文には、関連のない変数を含む任意の有効なC言語文を使用でき、浮動小数点数を含む任意のC言語データ型を使用できます。これらの特殊なfor文は、まれなプログラミング問題の解決策となる場合があります。
たとえば、増分行で乗算を使用すると、対数数列が生成されます。
for (int x = 2; x < 100; x = x * 1.5) {
println(x);
}生成数: 2,3,4,6,9,13,19,28,42,63,94
もう 1 つの例として、1 つの for ループで LED をフェードアップおよびフェードダウンします。
void loop()
{
int x = 1;
for (int i = 0; i > -1; i = i + x) {
analogWrite(PWMpin, i);
if (i == 255) x = -1; // switch direction at peak
delay(10);
}
}参照
- [Language] while
Language Reference Home
86Duinoリファレンスのテキストは、Arduinoリファレンスを改変したもので、Creative Commons Attribution-ShareAlike 3.0ライセンスに基づいてライセンスされています。リファレンス内のコードサンプルはパブリックドメインとして公開されています。