Conditional Statements and Loops
This lesson will introduce you to more programming structures which are essential to learn about.
Conditional statements
Conditional statements allow us to perform different actions depending on whether a specific condition is true or false (a Boolean value). They allow our projects to involve decision-making and follow different paths of execution depending on a condition. For example, we can use conditional statements to turn an LED off if it's dark. We'll explore this later when we learn about the LDR.
There are a few main types of conditional statements we can use.
if
statements
if
statements are used to execute some code if a certain condition is true:
if (condition) {
// Do something
}
if...else
statements
if...else
statements allow us to execute an alternate block of code if a condition is false:
if (condition) {
// Do something
} else {
// Do something else
}
if...else...if
statements
if...else...if
statements allow us to check through multiple conditions.
if (condition1) {
// Do something
} else if (condition2) {
// Do something else
} else {
// Do something else if both condition1 and condition2 are false
}
Loops
Loops can be used to execute certain blocks of code multiple times. Each cycle of a loop is known as an iteration.
for
loops
A for
loop is used when the number of iterations are known. This makes a for
loop a count-controlled loop, since it will execute a block of code for a specific number of times.
for (initialization; condition; increment) {
// statement(s);
}
for (int i = 0; i < 10; i++) {
// Do something 10 times
}
Blink an LED 5 times.
for (int i = 0; i < 5; i++) {
digitalWrite(2, HIGH);
delay(300);
digitalWrite(2, LOW);
delay(300);
}
while
loops
A while
loop is a pre-condition loop. This means it checks for a condition before iterating, and the number of iterations is unknown beforehand.
while (condition) {
// Do something
}
Be careful! If the condition being checked is always true, the loop will run forever. For example:
int blink = 1;
while (blink == 1) {
digitalWrite(2, HIGH);
delay(500);
digitalWrite(2, LOW);
delay(500);
}
Assignment
- Read this article to familiarse yourself with using conditional statements.
- Watch this video to understand loops better.
Next Steps
This section includes links to help you dive deeper into the topics from this lesson. It's optional, so don't worry if you choose to skip it.
- This article covers the
do...while
looping structure.