C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1
{
printf("*** Turn the printer on now. ***\n");
}
}
else
{
printf("You did not enter a Y or N.\n");
}

Tip

You can combine more than two relational operators with logical operators, but doing
too much in a single statement can cause confusion. This is a little too much:
Click here to view code image
if ((a < 6) || (c >= 3) && (r != 9) || (p <= 1)) {
Try to keep your combined relational tests simple so that your programs remain easy to
read and maintain.

The Order of Logical Operators


Because logical operators appear in the order of operators table, they have priority at times, just as
the other operators do. Studying the order of operators shows you that the && operator has precedence
over the ||. Therefore, C interprets the following logic:


Click here to view code image


if (age < 20 || sales < 1200 && hrsWorked > 15) {

like this:


Click here to view code image


if ((age < 20) || ((sales < 1200) && (hrsWorked > 15))) {

Use ample parentheses. Parentheses help clarify the order of operators. C won’t get confused if you
don’t use parentheses because it knows the order of operators table very well. However, a person
looking at your program has to figure out which is done first, and parentheses help group operations
together.


Suppose that a teacher wants to reward her students who perform well and have missed very few
classes. Also, the reward requires that the students either joined three school organizations or were in
two sports activities. Whew! You must admit, not only will that reward be deserved, but sorting out
the possibilities will be difficult.


In C code, the following if statement would test true if a student met the teacher’s preset reward
criteria:


Click here to view code image


if (grade > 93 && classMissed <= 3 && numActs >= 3 || sports >= 2) {
Free download pdf