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

(Romina) #1

previous Note.)


TABLE 12.1 The Logical Operators

Logical operators appear between two or more relational tests. For example, here are the first parts
of three if statements that use logical operators:


Click here to view code image


if ((age >= 21) && (age <= 65)) {

and


Click here to view code image


if ((hrsWorked > 40) || (sales > 25000.00)) {

and


if (!(isCharterMember)) {

If you combine two relational operators with a logical operator or you use the! (not) operator to
negate a relation, the entire expression following the if statement requires parentheses. This is not
allowed:


Click here to view code image


if !isCharterMember { /* Not allowed */

Of course, there is more to the preceding if statements than what is shown, but to keep things simple
at this point, the if bodies aren’t shown.


Logical operators work just as they do in spoken language. For example, consider the spoken
statements that correspond to the code lines just seen:


Click here to view code image


if ((age >= 21) && (age <= 65)) {

This could be worded in spoken language like this:


“If the age is at least 21 and no more than 65,...”


And the code


Click here to view code image


if ((hrsWorked > 40) || (sales > 25000.00)) {

could be worded in spoken language like this:


“If the hours worked are more than 40 or the sales are more than $25000,... “


Similarly,


if (!(isCharterMember)) {
Free download pdf