Lesson 3 of 10
Conditionals
- 12 min
- 6 checks
- 3 hints
- Go to task
Goal
Branching with if, else if and switch
Explanation
if runs what's inside it when its condition is true, else if adds another condition that's checked when none of the ones before it were true, and else takes everything left over. The condition goes between parentheses and the code to run goes between curly braces. The branches are checked in order and only the first one whose condition is true runs, so start with the invalid case and then work down from the highest cutoff. You combine conditions with && (and), || (or) and ! (not), as in if (hp < 0 || hp > maxHp).
There are two mistakes C++ accepts without a single complaint. The first is writing = instead of ==: if (hp = 0) doesn't compare anything, it sets the health to zero, so the condition is never true. The second is writing a comparison the way you would in math: if (50 <= score <= 74) works out 50 <= score first, which gives 0 or 1, and both are less than 74, so the condition is always true. The correct way is to write it as two conditions: score >= 50 && score <= 74.
switch compares a single value, a whole number or a character, against a list of fixed values: each value gets a case, and default handles anything that didn't match. Execution starts at the matching case and keeps going through the ones below it until it reaches a break or a return, so if you forget them, the next case runs too. That same behavior is what lets you stack two cases on top of one piece of code, like case 'w': case 'W':. And switch doesn't work with std::string.
Your task
Complete std::string grade(int score) with an if chain so it returns "S" from 90 to 100, "A" from 75, "B" from 50, "C" for anything below that down to zero, and "Invalid" for any score outside the range 0 to 100. Then complete std::string direction(char key) with a switch over the movement keys, so it returns "up" for the w key, "down" for s, "left" for a and "right" for d, treats an uppercase letter the same as a lowercase one, and returns "none" for any other key.
Checks
6 checks- grade returns S from 90 to 100
- grade is correct at the boundaries between grades
- grade returns "Invalid" outside the range 0 to 100
- direction knows the keys w, s, a and d
- direction treats uppercase letters like lowercase ones
- direction returns "none" for any other key