Lesson 3 of 10
Conditionals
- 13 min
- 6 checks
- 3 hints
- Go to task
Goal
Branching with if, switch and the ternary operator
Explanation
if runs its code when its condition is true, else if adds another condition that's checked only when the ones before it were false, and else takes everything that's left. The program checks the branches in order and runs only the first one that's true, so start with the highest threshold. You combine two conditions with && (and) or || (or), and flip a condition with !. In C# a condition must be a bool, so writing if (score) is a compile error, unlike in JavaScript and Python.
switch compares one value against several fixed cases. Every case must end with break or return, because C# doesn't let execution fall through from a case that has code into the next one. If you write two cases in a row with no code between them, they share the same code, as in case 'W': case 'w':, and default catches every value you didn't list.
The ternary operator cond ? a : b picks between two values in one line, as in int price = isMember ? 80 : 100;. It's a good fit for a short choice between two values, but write longer logic with if.
Your task
Complete Grade(score) with a chain of if statements so it returns "A" for a score of 90 or more, "B" from 80, "C" from 70, "D" from 60 and "F" below that, and returns "?" when the score is outside the range 0 to 100. Then complete Direction(key) with a switch on the movement keys: W returns "up", S returns "down", A returns "left" and D returns "right", whether the letter is upper or lower case, and any other key returns "idle". Finally, make ShieldDamage(damage, hasShield) use the ternary operator to return half the damage if the player has a shield, and the full damage if not.
Checks
6 checks- Grade returns A from 90 up, and B for 89
- Grade returns C, D and F at each of their boundaries
- Grade returns "?" for a score outside the range 0 to 100
- Direction knows the W, S, A and D keys
- Direction accepts lowercase letters and returns "idle" for any other key
- ShieldDamage halves the damage only when the player has a shield