Control flow#
apply control flow syntax to implement a program
Syntax#
if (question1)
action1;
else if (question2)
action2;
else
action3;
Question examples:
is the time 1?
time == 1
is the temperature lower or equal 20?
temperature <= 20
Action examples:
set the speed to 10
speed = 10
Example#
In words:
assume everything is turned off, i.e.,
0
if
temperature
is greater than 30 then activateair_conditioner
else if
temperature
greater than 25 activateventilator
else turn everything off.
In code:
if (temperature > 30)
air_conditioner = 1;
else if (temperature > 25)
ventilator = 1;
else { // ️⚠️ Use parantheses if you have multiple actions
air_conditioner = 0;
ventilator = 0;
}
Terms#
if-else-if-else
chain and actions (e.g., a = 0
) are statements.
C statements usually end with a semicolon. Example exception: if we have a compound statement
Questions must be expressions.
Other expression examples:
42
a + b
temperature > 30
Not expressions but statements:
temperature = 10;
if (temperature > 30) printf("Hot");
Activity 2
Which of the below are statements?
air_conditioner = 1;
if (...) else ...
a > b
5
success = a > b;
Process (1 min):
think individually
answer the poll in the virtual classroom
We have to adhere to this syntax, otherwise we get a syntax error.
Can you spot the syntax error in the following example?
if temperature > 30
air_conditioner = 1;
Lunar lander control#
Activity 3
Write code for landing using the following flowchart:
Copy the following template into your IDE and work on it:
#include <stdio.h>
int Control(int altitude) {
int thruster = 0;
// YOUR CODE HERE
return thruster;
}
void Test(int altitude) {
int thruster = Control(altitude);
int behaviorCorrect = (altitude > 100 && thruster == 0) ||
(altitude <= 100 && altitude > 0 && thruster == 1) ||
(altitude <= 0 && thruster == 0);
char *behaviorCorrectIcon = behaviorCorrect ? "✅" : "❌";
printf("For altitude %3d, your thruster is %d |%s|\n", altitude, thruster,
behaviorCorrectIcon);
}
int main(void) {
Test(150);
Test(100);
Test(50);
Test(0);
Test(-1);
}
Steps:
Work ~2 min individually. The program automatically tests your code.
Compare your result with your neighbor and help them.
Confused 😕 and want some clues? Then click here.
Use the following independent lines:
else
else if (altitude > 0)
if (altitude > 0)
thruster = 1;
thruster = 0;
thruster = 0;