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
statement.
Questions must be expressions.
Other expression examples:
42
a + b
temperature > 30
Not expressions but statements:
temperature = 10;
if (temperature > 30) Console.WriteLine("Hot");
Activity 4
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.
Example:
if temperature > 30
air_conditioner = 1;
Lunar lander control#
Activity 5
Write code for landing using the following flowchart:
Copy the following template into your IDE and work on it:
int Control(int altitude)
{
int thruster = 0;
// YOUR CODE HERE
return thruster;
}
void Test(int altitude)
{
int thruster = Control(altitude);
bool behaviorCorrect = (altitude > 100 && thruster == 0) ||
(altitude is <= 100 and > 0 && thruster == 1) ||
(altitude <= 0 && thruster == 0);
var behaviorCorrectIcon = behaviorCorrect ? "✅" : "❌";
Console.WriteLine($"For altitude {altitude}, your thruster is {thruster} |{behaviorCorrectIcon}|");
}
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;