PROGRAMMING: GOING AROUND IN LOOPS
Loops are one of the most important parts of programming. Loops are a block of code that can be made to run many times. We use conditional statements to tell the program how many times to run the loop. The loop will keep running over and over again until the conditional statement is no longer true. The most common loop is the for loop. It looks a lot like our if statement but it runs the block of lines over and over again until the statement is no longer true:
//blink the blue LED 10 times
for(int j = 0; j < 10; j++){
digitalWrite(blueLED, HIGH);
delay(1000);
digitalWrite(blueLED,LOW);
delay(1000);
}
The for statement is nifty in that you can declare a new variable (j in the example), do a conditional test, and then change its value. In the example, j++ means add 1 to the current value of j. We could also write it as j = j +1. The loop above will run 10 times as j takes on the values 0, 1, 2, … ,9.
There are two other loops: while and do … while. The while loop is like the for loop. Arduino looks at the conditional statement and decides whether to run the block of code. It reassesses the conditional statement each time it reaches the top of the loop:
int k = 0;
while(k < 100){ //this loop will run 100 times
k ++;
}
With the do … while loop, the conditional statement is at the bottom. Arduino always runs the block of code once, and then decides whether to run it again:
int k = 0;
do{
k++; //this line will always run once
}while(k<100);
//blink the blue LED 10 times
for(int j = 0; j < 10; j++){
digitalWrite(blueLED, HIGH);
delay(1000);
digitalWrite(blueLED,LOW);
delay(1000);
}
The for statement is nifty in that you can declare a new variable (j in the example), do a conditional test, and then change its value. In the example, j++ means add 1 to the current value of j. We could also write it as j = j +1. The loop above will run 10 times as j takes on the values 0, 1, 2, … ,9.
There are two other loops: while and do … while. The while loop is like the for loop. Arduino looks at the conditional statement and decides whether to run the block of code. It reassesses the conditional statement each time it reaches the top of the loop:
int k = 0;
while(k < 100){ //this loop will run 100 times
k ++;
}
With the do … while loop, the conditional statement is at the bottom. Arduino always runs the block of code once, and then decides whether to run it again:
int k = 0;
do{
k++; //this line will always run once
}while(k<100);