Lab: deciding with the if statement
An if statement lets a program choose a path. This lab builds one small decision and then grows it.
The task
Store a score, then display a different message depending on its value. Start with a single condition, then add an alternative, then add a middle case.
C#
int score = 72;
if (score >= 90)
{
resultLabel.Text = "Excellent";
}
else if (score >= 60)
{
resultLabel.Text = "Pass";
}
else
{
resultLabel.Text = "Keep practising";
}What to notice
- The first condition that is true wins, and the rest are skipped.
- The order of the conditions changes the result, so put the strictest first.
- An if can run with no else at all when nothing needs to happen otherwise.
Break it on purpose. Reverse the two conditions and see how the output changes. Watching the order matter is the fastest way to remember it.
When there are many fixed options, the switch statement lab is usually clearer.