← C# from Scratch Lesson 14 of 39 · 10 XP

if / else

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

if (hp <= 0)
{
    Console.WriteLine("Game over");
}
else if (hp < 30)
{
    Console.WriteLine("Careful!");
}
else
{
    Console.WriteLine("All good");
}

The branches are checked from top to bottom, and the first one that fits runs. The condition must be a bool.

The ternary operator is a short if for choosing a value:

string label = hp > 0 ? "alive" : "dead";

Task. Read a score (0–100) and print the grade: 90+ → A, 75–89 → B, 60–74 → C, lower → F.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.