if/else Statement
The if() statement is the most basic of all programming control structures. It allows you to make something happen or not, depending on whether a given condition is true or not. It looks like this:
if (someCondition) {
// do stuff if the condition is true
}
There is a common variation called if-else that looks like this:
if (someCondition) {
// do stuff if the condition is true
} else {
// do stuff if the condition is false
}
There’s also the else-if, where you can check a second condition if the first is false:
if (someCondition) {
// do stuff if the condition is true
} else if (anotherCondition) {
// do stuff only if the first condition is false
// and the second condition is true
}
For loop
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. It looks like this:
for (initialization; condition; increment) {
// statements;
}
- initialization: happens first and exactly once.
- condition: each time through the loop, 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.
- increment: executed each time through the loop when condition is true.
While loop
A while loop will loop continuously, and infinitely, until the expression inside the parenthesis, () becomes false. Something must change the tested variable, or the while loop will never exit. This could be in your code, such as an incremented variable, or an external condition, such as testing a sensor. It looks like this:
while (condition) {
// statements;
}
- condition: a boolean (Ture or False) expression that evaluates to true or false.