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

(Romina) #1

could be worded in spoken language like this:


“If you aren’t a charter member, you must...”


As you have no doubt figured out, these three spoken statements describe exactly the same tests done
by the three if statements. You often place an and between two conditions, such as “If you take out
the trash and clean your room, you can play.”


Note

Reread that stern statement you might say to a child. The and condition places a strict
requirement that both jobs must be done before the result can take place. That’s what
&& does also. Both sides of the && must be true for the body of the if to execute.

Let’s continue with this same line of reasoning for the || (or) operator. You might be more lenient on
the kid by saying this: “If you take out the trash or clean your room, you can play.” The or is not as
restrictive. One side or the other side of the || must be true (and they both can be true as well). If
either side is true, the result can occur. The same holds for the || operator. One or the other side of
the || must be true (or they both can be true) for the body of the if to execute.


The! (not) operator reverses a true or a false condition. True becomes false, and false becomes true.
This sounds confusing, and it is! Limit the number of! operators you use. You can always rewrite a
logical expression to avoid using! by reversing the logic. For example, the following if:


if ( !(sales < 3000)) {

is exactly the same as this if:


if ( sales >= 3000) {

As you can see, you can remove the! and turn a negative statement into a positive test by removing
the! and using an opposite relational operator.


The following program uses each of the three logical operators to test data. Two of the three
conditions will be met, and their if sections of code will print; the third is not true, so the else
section of code will print.


Click here to view code image


// Example program #1 from Chapter 12 of Absolute Beginner's Guide
// to C, 3rd Edition
// File Chapter12ex1.c
/* This program defines a series of variables and expressions and
then uses both relational and logical operators to test them against
each other. */
#include <stdio.h>

main()
{
Free download pdf