And (&&) and Or (||)

And (&&) and Or (||)#

Sometimes we want to combine tests in a single conditional. For this we use the logical operators:

  • a && b : the add operator. It returns true if both a and b are true.

  • a || b : the or operator. It returns true if either (of both) of a or b are true.

  • ! a : the not operator. It turns true if a is false.

Keep in mind the precedence of these operators in expressions.

Here’s an example. Let’s ask the user for an integer and then test if it is divisible by both 2 and 3:

Listing 48 divisible.cpp#
#include <iostream>

int main() {

    int n{};

    std::cout << "Enter an integer: ";
    std::cin >> n;

    if (n % 2 == 0 && n % 3 == 0) {
        std::cout << "your number is divisible by 2 *and* 3" << std::endl;
    } else if (n % 2 == 0 || n % 3 == 0) {
        std::cout << "your number is divisible by 2 *or* 3" << std::endl;
    } else {
        std::cout << "your number is not divisible by 2 or 3" << std::endl;
    }

}