Codiqo

Learn C++ · lesson 13 of 61 · about 8 minutes

Project: The Guard at the Gate

A guard blocks the way out of the cave. Read a password, check the rule with comparisons and logic, and open the gate or not.

What you'll learn

  • Translate rules into conditions
  • Name each rule with a bool
  • Test a rule at its edges

The guard's rule

A guard blocks the gate out of the cave. The rule:

1. You must still be standing: health above 0
2. And you must know the password or pay the 15-gold toll

Each part becomes a comparison with a name, and the words between them become && and ||.

The rule, step by step

#include <iostream>
#include <string>

int main() {
    int health = 85;
    int gold = 7;
    std::string answer = "dragon";
    bool knowsWord = answer == "dragon";
    bool canPay = gold >= 15;
    bool letIn = (knowsWord || canPay) && health > 0;
    std::cout << (letIn ? "The gate swings open." : "The guard blocks the way.") << "\n";
}

Output

The gate swings open.

Reading the password

std::cin >> answer reads one word, so the password can't have spaces. The comparison is exact: Dragon isn't dragon.

Test the edges

Rules break at their edges. With exactly 15 gold, can the hero pay? The toll is 15, so it's >= 15, not > 15. Test the exact numbers first, then the ones either side.

Tip

Names like knowsWord and canPay make a long rule read like the sentence it came from.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.