計數 for

for指令用於重複執行大括號內之程式碼。一個增量計數器通常用於遞增和終止迴圈。for適合用於任何重複執行程式碼,並且通常結合使用陣列(矩陣)。指令格式:for

for (初始值;判斷條件 ;增量或減量) {

//重複執行程式碼;

}

初始化後迴圈執行一次。每次迴圈執行後,條件測試; 如果這是真的,{}內程式碼和增量被執行,則該條件再次測試。當條件為假,迴圈結束。

範例Example

// 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);

   }

}

提示

C的 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

另一個範例, 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);

   }

}

See also