Comet writes Beacon's first alert rule on the whiteboard and underlines it twice.
"If the water is under 30, show The tomatoes need water. Done."
Lena reads it over his shoulder. "And when the water is fine? The screen just stays blank?"
"Blank feels like broken," Wren says. "What do you notice? We only told Beacon what to do half the time."
Nova draws a fork in the road on the whiteboard. "Interesting," she says. "Every IF can have a second path."
Comet grabs the marker. "Then let's build both paths."
Selection decides which parts of an algorithm run, based on a condition being true or false.
Conditional statements, or if-statements, change the usual top-to-bottom flow of a program.
They run different statements based on the value of a Boolean expression.
In our pseudocode, the statements inside the curly braces run only when the condition is true.
waterLevel ← INPUT()
IF (waterLevel < 30)
{
DISPLAY("The tomatoes need water")
}
DISPLAY("Check complete") An IF with an ELSE always takes exactly one of two paths.
If the condition is true, the first block runs. If it is false, the ELSE block runs instead.
IF (waterLevel < 30)
{
DISPLAY("The tomatoes need water")
}
ELSE
{
DISPLAY("Water is fine")
} The AP reference sheet provides three logical operators: NOT, AND and OR. Each one evaluates to a Boolean value. This week uses AND and OR.
condition1 AND condition2 is true if both conditions are true. Otherwise it is false.
condition1 OR condition2 is true if either condition is true, or if both are. Otherwise it is false.
| waterLevel < 30 | lightLevel > 80 | AND gives | OR gives |
|---|---|---|---|
| true | true | true | true |
| true | false | false | true |
| false | true | false | true |
| false | false | false | false |
| Statement | True or false? |
|---|---|
| Selection decides which parts of an algorithm run. | ? |
| An IF with an ELSE can run both paths at once. | ? |
| AND is true only when both conditions are true. | ? |
| OR is false when both conditions are true. | ? |
Nice decisions. Tomorrow in Beacon Lab you test two alert programs with a decision table.