Logical Negation

Sometimes we need to find the opposite of a condition - that is, when a condition doesn't apply. This is what the negation operator ! is for:

bool isLoggedIn = false;

// Negation using !
if (!isLoggedIn) {
    std::cout << "User is not logged in" << std::endl;
}

Negation reverses the value of an expression:

  • !true is false
  • !false is true

It's often used to simplify conditions. Instead of:

if (age < 18) {
    std::cout << "Not an adult" << std::endl;
}

We can write:

bool isAdult = (age >= 18);
if (!isAdult) {
    std::cout << "Not an adult" << std::endl;
}

We can also negate more complex expressions using parentheses:

bool hasLicense = true;
bool hasCar = false;

// Negation of a compound expression
if (!(hasLicense && hasCar)) {
    std::cout << "Cannot drive" << std::endl;
}

Instructions

Complete the condition so that Going outside is printed if internetWorking is false. Use negation for this.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

8/10

Logical Negation | Start Coder