← C++ from Scratch Lesson 15 of 62 · 10 XP

if / else

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

if (hp <= 0) {
    std::cout << "Game over\n";
} else if (hp < 30) {
    std::cout << "Careful!\n";
} else {
    std::cout << "All good\n";
}
  • the condition goes in parentheses and can be any expression that can be turned into a bool (the number 0 is false, everything else is true);
  • the conditions are checked from top to bottom, and the first branch that fits runs;
  • a common mistake: if (x = 5) is an assignment, not a comparison (==). With -Wall the compiler warns you.

In C++17 you can declare a variable right in the if: if (int d = a - b; d > 0) { … } — d is visible only inside.

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

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