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 returnstrueif bothaandbaretrue.a || b: the or operator. It returnstrueif either (of both) ofaorbaretrue.! a: the not operator. It turnstrueifaisfalse.
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:
#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;
}
}