Lesson 3 of 10

Conditionals

Goal

Branching with if, switch and the ternary operator

01

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.

02

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
  1. Grade returns A from 90 up, and B for 89
  2. Grade returns C, D and F at each of their boundaries
  3. Grade returns "?" for a score outside the range 0 to 100
  4. Direction knows the W, S, A and D keys
  5. Direction accepts lowercase letters and returns "idle" for any other key
  6. ShieldDamage halves the damage only when the player has a shield
03

Hints

0/3
Track lessons0 of 10 done

C# is the language behind Unity games and .NET apps. Every variable has a fixed type, programs are built from classes, and it comes with ready-made tools for most of what you need.

Beginner level, 10 lessons, 2.5 hours in total.

Program.cs
OutputC# (Mono 6.6, Judge0)

Compiling and running your code on the server.

–/6

Compiling and running your code on the server.

6 checks listed under “Your task”.

Track lessons0 of 10 done

C# is the language behind Unity games and .NET apps. Every variable has a fixed type, programs are built from classes, and it comes with ready-made tools for most of what you need.

Beginner level, 10 lessons, 2.5 hours in total.