Previous Page TOC Next Page



- 8 -
Relational and Logical Operators


relational operators


What You'll Learn About


Not all Visual C++ operators do math. This unit teaches you all about operators that test data. Computers are great not only for making speedy calculations but also for testing data. You might need a program to test data to find the answer to questions such as these:

The relational and logic operators give your programs the power to answer questions such as these. Now that you understand user input with cin, you can write programs that manipulate different data values every time someone runs the program, in case the user enters different values for each run. Customers don't always buy the same number of products, salespeople don't always sell the same items, and your employees don't always work the same hours.

definition

A data-driven program is a program whose data dictates the order of execution.

By being able to test data and act accordingly, your programs can take one of several logic paths. For the first time in this book, you will see data-driven programs that don't necessarily execute sequentially, line-by-line. From now on, many programs that you write will contain code that might or might not execute, depending on the data that is entered.



Think of data-driven programs as programs that take different paths, just as you do when you drive your car. You rarely drive to the same place each time you get in your car. You might leave your neighborhood using the same path but then turn into the grocer, get gas, take the freeway, or take a detour around construction. Your current needs determine the path you take, just as the data determines the path taken by the statements in your programs.


Making Decisions with Relational Operators




Learn how the six relational operators produce true or false results.

Table 8.1 lists the six relational operators that you'll learn about in this section. Unlike the math operators you learned about in Unit 3, the relational operators don't calculate numbers. Instead, relational operators test one data value against another, letting you determine how the values compare.



The relational operators are binary operators. Therefore, they work between two values, just as the * does.

definition

A relational operator tests data values against one another.

Table 8.1. The relational operators and their meanings.

Relational Operator Description
== Equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
!= Not equal to

Be sure that you compare similar data. For example, you would never compare a character variable to a floating-point variable. Make sure that the value on one side of a relational operator matches the data type on the other side.

As you read through the table's descriptions of the relational operators, perhaps you can begin to get a glimpse of their use. There are many times when you'll want to know if two values are the same, if one is less than another, if one is more than another, or if two values are different.

In everyday life, you compare data just as you will do in Visual C++ programs. For example, here is a list of six statements. Each statement, when spoken, matches the operation of each of the six relational operators shown in Table 8.1.

  1. My overcoat sales last month were equal to $50,000.

  2. Cable television provides fewer channels than satellite television. (The number of cable stations is less than the number of satellite stations.)

  3. A first-class ticket from New York to Los Angeles is greater than or equal to the price of a coach ticket around the world.

  4. It rained as much as, or perhaps less than, yesterday. (The amount of rain today was less than or equal to yesterday.)

  5. Shelly is older than Michael. (Shelly's age is greater than Michael's.)

  6. The color of your belt is not the same as the color of your shoes. (The belt's color is not equal to the shoes' color.)



All relational operators return either a true value, which is represented as a 1 in Visual C++, or a false value, which is represented as a 0 in Visual C++.

The relational operations are assumed to be true or false. In other words, the overcoat sales in statement 1 were equal to $50,000 or they were not, cable either provides fewer channels or it provides more, and so on. Whenever you compare any two values, either in real life or in a program, there is always a question of whether the comparison is true or not. You'll use the relational operators to test for a true or false result and act accordingly.

definition

Pseudocode is a written description of a program in plain speech, not in Visual C++ code.

Look at Figure 8.1; it acquaints you with relational logic in a program. The pseudocode in the program checks to see whether the daily sales were more than yesterday's sales. If the sales were more, one section of the program takes over. If the sales were less, a different section of the program takes over. In either case, only one of the two program sections executes.

Figure 8.1. The test determines which of the two sections to execute.

See how the data drives this program outline? One and only one section of the program (in addition to the initial testing of the data) executes, and the data dictates which of those sections executes. Eventually, whatever section took over finishes, the end of the program executes (perhaps to print a sales report), and the program terminates.

Let's move to a more Visual C++-like representation of the relational operators. Using the integer variables defined here, can you see that all of the following sentences are true?


int a = 1;

int b = 2;

int c = 3;

int d = 1;
  1. a == d because they contain the same value.

  2. c > b because 3 is greater than 2.

  3. c >= b because 3 is greater than or equal to 2. (The or implies that c can be less than b or equal to b.)

  4. a < c because 1 is less than 3.

  5. a <= d because 1 is less than or equal to 1.

  6. b != d because 2 is not equal to 1.

All of the preceding sentences about the variables are true. See whether you can spot which of the following are false:

  1. a >= d

  2. b != c

  3. a == c

  4. c <= a

The third and fourth statements are false. Working with simple variables such as these seems like little more than an easy mental exercise, and testing meaningful values such as sales figures in your Visual C++ programs isn't much more difficult.

Be sure that you use the double equal sign (==) when testing for equality, and reserve the use of the single equal sign (=) for assignment only. (Some programming languages, such as BASIC, use the single equal sign for both assignment and relational testing.) This is very important because, unlike most other languages, C++ will accept that assignment as valid, and then test the result of the assignment for being true or false. This version of Visual C++ will not warn you of this mistake. We will review this problem carefully later in this section.

I want to drive home a final point before you get to official Visual C++ code that uses relational operators for actual work. You saw earlier that Visual C++ evaluates true relational expressions as 1 and false relational expressions as 0. Listing 8.1 assigns the answers to several relational operators to variables and prints the results. Try to predict the program's output before looking at the answer.



The relational operators compare values against other values and determine whether those values compare as true or false based on the specified relational operation. Visual C++ prints only a 1 or a 0 in Listing 8.1 because 1 and 0 represent true and false relations.

Input Listing 8.1. Printing the results of relational operators.

1:  // Filename: RELAT1ST.CPP

2:  // Prints the results of several relational operations

3:  #include <iostream.h>

4:  void main()

5:  {

6:    int high = 45;

7:    int low = 10;

8:    int middle = 25;

9:    int answer;

10:

11:    answer = high > low;

12:    cout << "High > low is " << answer << endl;

13:

14:    answer = low > high;

15:    cout << "Low > high is " << answer << endl;

16:

17:    answer = middle == middle;

18:    cout << "Middle == middle is " << answer << endl;

19:

20:    answer = high >= middle;

21:    cout << "High >= middle is " << answer << endl;

22:

23:    answer = middle <= low;

24:    cout << "Middle <= low is " << answer << endl;

25:

26:    answer = 0 == 0;

27:    cout << "Bonus relation: 0 == 0 is " << answer << endl;

28:

29:    return;

30:  }

Output


High > low is 1

Low > high is 0

Middle == middle is 1

High >= middle is 1

Middle <= low is 0

Bonus relation: 0 == 0 is 1

Analysis

The 1s and 0s in the output show whether the relational tests performed were true or false. Most of this program's relational testing should now be obvious to you. The high value is certainly greater than the low value; hence, line 11 stores a 1 (true) in answer. The low value is not greater than the high value, so the second assignment, line 14, stores a 0 (false) in answer.

The only possibly tricky assignment occurs in line 26. Although 0 is equal to 0, you might be tempted to think that the zero means false. You must remember that the six relational operators return either 1 or 0 based on how two values compare. 0 compares exactly to 0 in line 26. It is because 0 is equal to 0 that == is true. The true result is always 1.



How Can This 1 or 0 Business Help Me?

At this point, you might be wondering how a return of 1 or 0 can help you when you write Visual C++ programs. Have patience, because the next section shows you how to incorporate the six relational operators into useful Visual C++ code using a new command named if.

To get a taste of 1's and 0's advantages, consider the following section of code:


cout << "How many tickets were sold? ";

cin >> num;

salePay = num * 1.45+(num > 500)*25;  // Maybe pay a bonus

The pay for the salesperson, stored in salePay, will always be at least $1.45 per ticket. The trick comes in the statement's second half. If more than 500 tickets are sold, the relation (num > 500) is true (or 1) and the 1 * 25 adds an additional $25 to the pay. If, however, the tickets did not total more than 500, (num > 500) is false (or 0) and 0 * 25 is $0, so no bonus is paid.

cout << "How many tickets were sold? ";

cin >> num;

salePay = num * 1.45+(num > 500)*25;  // Maybe pay a bonus


Before you continue, be sure that you understand the code in the preceding sidebar. Some newcomers to Visual C++ must take a few extra moments to figure out what's going on. Although such relational statements are efficient, some Visual C++ programmers overuse them. If your code is hard to read and maintain, you don't gain anything with tricks. If you think it's clearer to separate the preceding code's last line into more than one statement, do so for your sake as well as for those who must maintain your program later. The next section's if statement gives you a much better way to break the preceding assignment into two more-readable statements.


Obviously, not all relational logic requires that you work with sales figures, but sales totals and bonuses make for great illustrations of relational logic. That's why you're seeing so many such examples here.


The if Command Tests for Relations




The if statement uses the relational operators to determine which lines of a program to execute.

Every programming language has some form of an if statement. The if statement tests the relational operators and decides exactly which sections of a program to execute and which to ignore. It is the if statement that determines whether a program should detour or go straight.

definition

A keyword is a command's trigger word, such as if or return.

Although you now have several units of this book under your belt, you don't know a lot of Visual C++ commands (also called statements). You've seen the return statement at the end of main(). return sends control back to QuickWin after your program completes its execution. The assignment statement is a command, but no keyword is associated with the assignment, only an equal sign.



The if statement lets your programs make decisions at runtime based on data values.

The if statement is one of the most important statements in Visual C++. Without if, Visual C++ could only sequentially execute statements, limiting the amount of decision-making your programs could do. Now that you understand the relational operators, it's time to see how if can use the true and false relations to take action based on those relations.

The if statement is a multiline programming statement. Unlike return, if almost always takes more than one line of code. Here is the format of the if statement:


if (relationalTest)

  { A block of one or more Visual C++ statements }

From the italics, you can tell that if uses a relational test that you must supply inside parentheses. The parentheses are required; without them, Visual C++ won't compile your program. relationalTest can be the comparison of any two variables, literals, or a combination of both, as shown in the following sample if lines:


if (sales < 50000)


if (initial > 'M')
if (amount <= value)

Never put a semicolon after the closing parenthesis! Visual C++ will think that the if statement is finished and will begin executing the block of statements that follow the if, whether or not the relational test was true or false.



Semicolons terminate only complete Visual C++ statements and functions. The if doesn't end after the closing parenthesis; therefore, no semicolon follows the parenthesis. Put semicolons at the end of all statements inside the if's block.

The block of statements that follows the if can contain any valid Visual C++ statements, including couts, cins, assignments, and even additional if statements (meaning that you can nest if statements). If the block of code contains only a single statement, you don't need the enclosing braces. However, good Visual C++ programmers develop the habit early of including if's braces around even a block of just one statement. If you later add more to the body of the if, you could too easily forget to add the braces, and program logic errors would appear that can be difficult to trace.

Visual C++'s if reads exactly like you use if in real life. Consider the following statement:

"If I learn Visual C++, I'll be able to write Visual C++ programs."

What if you don't learn Visual C++? You'll never write a Visual C++ program. The body of that if statement, therefore, will never happen. What if you do learn Visual C++? You'll be able to write Visual C++ programs. The truth of the if relational test, if I learn Visual C++ or if I don't learn Visual C++, determines the next course of action.



if needs no header file. Only library functions such as strcpy() require header files.

Figure 8.2 illustrates how if works. It shows how the body of the if statement might or might not execute, depending on the relation.

Figure 8.2. The body executes only if the relational test is true.

In the following code, a special message might or might not print:


cout << "What is your IQ? ";

cin >> iq;   // Assume that iq is a defined integer

if (iq >= 140)

  { cout << "How brilliant you are!" << endl; }

cout << "Have a nice day.";

The program will print either


How brilliant you are!

Have a nice day.

or


Have a nice day.

Do you see how the data drives the program? There is a line in the program, the second cout, that might never execute. The cout's execution is based solely on the value of the variable iq and how that value compares to the number 140. If and only if iq holds a value greater than or equal to 140 will the second cout execute.

The preceding code sample's if body contained only a single statement to keep things simple initially. The braces aren't required, but they're still recommended. The following if statement's body contains four statements:


cout << "What is your IQ? ";

cin >> iq;   // Assume that iq is a defined integer

if (iq >= 140)

  {

    cout << "How brilliant you are!" << endl;

    cout << "Perhaps you should consider learning Visual C++" << endl;

    cout << "in order to put your talents and that %d IQ " << iq;

    cout << "to good use!" << endl;

  }

cout << "Have a nice day." << endl;


The indentation of the if's code body is not required. As you learned in Lesson 2, Visual C++ is a free-form language, so such spacing is optional. The indentation helps to show you where the if's body begins and ends. Therefore, by indenting the code body, you help to improve your program's readability.

Do you remember the following line from an earlier sidebar?


salePay = num * 1.45 + (num > 500) * 25;   // Maybe pay a bonus

You now know enough to break that tricky line into two more-readable but equivalent statements:


salePay = num * 1.45;

if (num > 500)

  { salePay += 25; }   // Pay a bonus if sold enough

You're writing a billing program for a small hotel. The hotel charges a high rate (called the rack rate) and a discount rate. First-time customers are charged the rack rate and repeat customers get the discount. Listing 8.2 contains a program that calculates the cost of a room according to the customer's history with the hotel.



The if statement chooses whether or not to execute a section of a Visual C++ program.

Input Listing 8.2. Computing a hotel rate.

1:   // Filename: HOTELIF.CPP

2:   // Determines a hotel price

3:   #include <iostream.h>

4:   #include <iomanip.h>

5:   void main()

6:   {

7:     char ans;

8:     int numNights;

9:     float rackRate = 67.50;

10:    float discRate = 57.65;

11:    float totalCost = 0.0;

12:

13:    cout << "How many nights did the customer stay? ";

14:    cin >> numNights;

15:

16:    cout << "Has the customer stayed here before (Y/N)? ";

17:    cin >> ans;

18:

19:    if (ans == 'Y')

20:      { totalCost = discRate * numNights; }

21:

22:    if (ans == 'N')

23:      { totalCost = rackRate * numNights; }

24:

25:    cout.setf(ios::showpoint);

26:    cout.setf(ios::fixed);

27:    cout << setprecision(2);

28:    cout << "The total cost is $" << totalCost << endl;

29:

30:    return;

31:  }


There are two possible outputs, depending on whether the customer has stayed at the hotel before. Therefore, two different runs of the program follow.

Output


How many nights did the customer stay? 2

Has the customer stayed here before (Y/N)? Y

The total cost is $115.30

How many nights did the customer stay? 2

Has the customer stayed here before (Y/N)? N

The total cost is $135.00

Analysis

The customer's number of nights is multiplied by either the rack rate, stored in rackRate, or the discount rate, stored in discRate. These two possibilities require that two if statements be made. If the first if on line 19 is true, the discount rate is computed. If the second if on line 22 tests for a true relation, the rack rate is computed.

This program assumes that the user will enter an uppercase Y or an uppercase N. The initial zero assigned to totalCost keeps garbage out of the variable, just in case the user doesn't enter an uppercase Y or N. If you ran the program and got a total cost of $0.00, you would know that you must enter an uppercase answer to the question. Later in this unit, you will learn how to ensure that the user enters exactly what is expected (such as an uppercase Y or N) through a process known as input validation. In Lesson 8, you will learn how to test for either uppercase or lowercase answers. Of course, you could use four sets of if statements—testing for Y, y, N, and n—but there are almost always better ways to program instead of duplicating effort.

Notice that the if statements test a character variable. Therefore, the ifs' relational operators must compare against a character. In this case, the characters tested are the Y and N character literals. The order of the comparison is unimportant; line 19's if, for example, could read like this with the same effect:


if ('Y' == ans)   // Reverse the comparison order

Never compare floating-point or double floating-point values for equality. It's difficult to represent exact floating-point quantities inside a computer. Therefore, use >= and <= to compare within a small range of values if you ever want to compare two floating-point values for equality.

There are several ways to improve upon this program. You'll learn how in the sections that follow.

Otherwise, There's else




else determines what happens if the relation is false.

The if statement determines whether a block of statements does or doesn't execute. Whatever happens, the statements that follow the if's closing brace execute after the if completes its test and possible body of code.

The if as you currently know it determines whether or not a block executes, but it's possible to extend the action of if so that it executes one block of code or another. To make if decide between one of two possible blocks of code, add the else statement after the if's closing brace. Here is the format of the if-else statement:


if (relationalTest)

  { A block of one or more Visual C++ statements }

else

  { A block of one or more Visual C++ statements }

Figure 8.3 shows the action of the if-else statement. Notice that either block executes and that the true or false relation determines which block executes. No matter which of the blocks executes, the statements following the if execute and the program continues as usual after the if-else does its job.

Figure 8.3. The body of the if or the body of the else executes, but never both.

With the simple if statement, the block executes if the relation is true. If you add an else block, that block of statements executes if the relation is false.

The if can execute only one optional block of code, or one of two blocks if you use else. There's no way to make if decide between one of three or more blocks of code unless you nest one if inside another. In Lesson 5, you'll learn about the switch statement, which lets your program choose from among more than two possible courses of action.

[ic: stop and type]else improves the hotel billing computation program in Listing 8.2. else eliminates the need for two if statements, as Listing 8.3 shows.



When your program must select between one of two possible actions, if-else handles the job well.

Input Listing 8.3. Only one if is now needed for the hotel billing.

1:   // Filename: HOTLELSE.CPP

2:   // Determines a hotel price by choosing

3:   // between one of two possible options

4:   #include <iostream.h>

5:   

6:   void main()

7:   {

8:     char ans;

9:     int numNights;

10:    float rackRate = 67.50;

11:    float discRate = 57.65;

12:    float totalCost;

13:

14:    cout << "How many nights did the customer stay? ";

15:    cin >> numNights;

16:

17:    cout << "Has the customer stayed here before (Y/N)? ";

18:    cin >> ans;

19:

20:    if (ans == 'Y')

21:      { totalCost = discRate * numNights; }

22:    else

23:      { totalCost = rackRate * numNights; }// Only one if needed

24:

25:    cout.precision(2);

26:    cout.setf(ios::showpoint);

27:    cout.setf(ios::fixed);

28:    cout << "The total cost is $" << totalCost << endl;

29:

30:    return;

31:  }

Output


How many nights did the customer stay? 2

Has the customer stayed here before (Y/N)? Y

The total cost is $115.30

How many nights did the customer stay? 2

Has the customer stayed here before (Y/N)? N

The total cost is $135.00

Analysis

As you can see, the program got simpler with the else. Two ifs, each testing for an opposite relation, are no longer needed. Basically, lines 20 through 23 say this:

"If the user typed a Y, use the discount rate; otherwise (else), use the rack rate."


Logical Operators




You can combine relational operators to add power to if statements.

definition

A logical operator extends the action of relational if tests.

There is another group of operators called the logical operators. They let you combine two or more relational tests into a single statement or change the value returned from a relation. Table 8.2 lists Visual C++'s logical operators. The first two logical operators are binary operators, because they work on two values. The last logical operator, !, is a unary operator. The values that the logical operators work on are always relational tests.

Table 8.2. The logical operators.

Logical Operator Meaning Description
&& AND Returns true if and only if both sides of the && are true.
|| OR Returns true if one or the other side of the || is true (or if both sides are true).
! NOT Changes a true relation to false or a false relation to true.


The logical operators are sometimes called the compound relational operators because they combine the action of two or more relations.

definition

Input validation ensures that the user entered an appropriate value.

Assume that the user was supposed to enter a value between 1 and 5 that represented his or her department number. How can you ensure that the user enters a value within the range of 1 to 5? You can perform input validation before moving on. Consider the following if:


cout << "What is your department number? ";

cin >> dept;   // Get a department number

if (dept < 1 || dept > 5)

  {

    cout << "You did not enter a correct department number!" << endl;

    return;   // Return to QuickWin

  }

else

  {

    // Put the correct department code here

  }

The || inside the if statement tells Visual C++ to check that the user's input falls within the range of 1 to 5. If the user enters a value less than 1 or more than 5, the error message prints and the program terminates early. If the user's value falls within the proper range, the user doesn't see the error message and the appropriate department code executes.



Watch Operator Precedence

The logical operators as well as the relational operators appear in the operator precedence table. Visual C++ interprets the if in the preceding code like so



if ( (dept < 1) || (dept > 5) )

because relational operators have higher precedence than logical operators. For clarity, include the extra parentheses as shown here.

Often, there are several ways to write the same program. The preceding code used an || (OR) operator to make sure that the user's entered value fell within the expected range. You can use an && (AND) logical operator to perform a test with the same results. Look at this difference:


cout << "What is your department number? ";

cin >> dept;   // Get a department number

if ((dept >= 1) && (dept <= 5))

  {   // Put the correct department code here }

else

  { cout << "You did not enter a correct department number!" << endl;

return;   // Return to QuickWin early

}

This if tells Visual C++ the following:

"If the user's value is greater than or equal to 1 and if the user's value is less than or equal to 5, accept the input. Otherwise, print an error message and exit the program."

Without the logical operators, you would have to use a nested if to perform the same check, and a nested if isn't as easy to read. Here's the same code with a nested if:


cout << "What is your department number? ";

cin >> dept;   // Get a department number

if (dept >= 1)

  {

     if (dept <= 5)

       {

          // Put the correct department code here

       }

     else

       {

          cout << "You did not enter a correct department number!" << endl; }

          return;   // Return to the IDE early

       }

  }

else

  {

     cout << "You did not enter a correct department number!" << endl; }

  }


Note carefully the indentation of the braces and statements. There are various styles of indentation in C++. The style in this example is the easiest to follow and allows you to quickly see that you have put in all the matching levels of braces correctly.

The nested if requires that both of the first two ifs be true before the first block of code executes. An else is required for both ifs in this code because if either the user's value is less than 1 or the user's value is more than 5, the error should print. As you can see here, a simple logical operator keeps your programming clearer.

The ! (NOT) operator isn't used much because logic is easier to write and maintain if you keep it positive. Virtually any relational test that uses a ! operator is easier to understand if you reverse the logic and remove the !. For example, the if


if (!(c >= b))

is identical to


if (c < b)

The second statement is easier to read and write. There is at least one good use for the ! operator, and you'll read about it in Lesson 9.

Visual C++ contains a short-circuiting feature that sometimes hurts more than it helps. If the left side of an || test is true, Visual C++ doesn't bother evaluating the right side in order to save run time. In other words, if the following if's amt is more than 70


if ((amt > 70) || (amt < 100))

Visual C++ doesn't bother to check whether amt is less than 100. There's no need to. The || requests that Visual C++ evaluate the if as true if either side of the || is true. If the left side is true, the if is true no matter what the right side evaluates to.

Visual C++ also short-circuits && operators if the left side is false. Therefore, a statement such as


if ((value <= 10) && (value >= 0))

takes a shortcut if value is more than 10. There's no need for Visual C++ to spend the execution time looking at the right side of the && if the left side is false; && requires that both sides be true before the if expression can be true. If the left side is false, the if is false no matter how the right side evaluates.

The short-circuiting feature is fine for efficiency, but make sure that you don't write tricky code that relies on both sides of the logical operator to execute. Consider the following statement:


if ((sales > 1000) && (inventoryFlag = 1))

If you were to code such an if statement (obviously, the bodies of some of these sample if statements are missing), Visual C++ would allow this as valid, but it is probably not what was intended. Do you see it? An assignment appears to the right of the &&, not an equality relational operator, ==, as was probably intended. Visual C++ goes ahead and compiles your program.

What you are seeing is the results of C++ being derived from C. In C, the language was designed to allow very efficient code, related to processor instructions. Because processors often have an instruction to "assign and test the result," the idea of a C if statement allowing both testing and assignment seems very sensible. However, compiler technology has moved forward from the days when C was designed, and the C++ compiler will often "rewrite" the simple code the programmer writes into optimized code without the need for the programmer to be aware of the best instructions to use. Modern programmers recognize that the costs of unreadable and error-prone code outweigh the advantages of small efficiency gains. You will find that C++ allows very complicated single statements. However, most C++ programmers do not take advantage of the flexibility because it makes the code too hard to understand.

To bring the point home, let's look closely at how Visual C++ handles the statement. If you leave this statement in your program, and if the sales are more than 1,000, Visual C++ will go ahead and look at the right side of the &&. Visual C++ then stores a 1 in the variable named inventoryFlag because of the assignment. The result of the assignment is 1, and 1 is true (any nonzero value in Visual C++ is considered to be true).

Let us assume that the intention is to test the value. If the inventoryFlag is zero and the sales are greater than 1,000, the program both assigns 1 into inventoryFlag and then finds the value to be true. This statement always executes the body of the if statement when sales are greater than 1,000 regardless of the status of the flag.

If the programmer really wants the assignment to work when the sales are greater than 1,000, the following code is much clearer:


if (sales > 1000)

  {

    inventoryFlag = 1;

    // Rest of if's body goes here

  }

The program in Listing 8.4 contains a regular if, an if with an else, and an if with logical operators.



Use if for a simple decision, if-else if you need to determine one of two courses of action, and logical operators if you need to combine two or more relational operators.

Input Listing 8.4. There are different ways to handle data combinations.

 1:  // Filename: LOGICALS.CPP

 2:  // A program with an if, an if-else,

 3:  // and a logical operator

 4:  #include <iostream.h>

 5:  void main()

 6:  {

 7:     int numCusts;

 8:     float totalSales;

 9:

10:     cout << "How many customers were in yesterday? ";

11:     cin >> numCusts;

12:

13:     cout << "What were the total sales? ";

14:     cin >> totalSales;

15:

16:     // A simple if

17:     if (numCusts > 25)

18:       { cout << "Order more snacks for tomorrow." << endl; }

19:

20:     // An if-else

21:     if (totalSales >= 2000.00)

22:       {

23:         cout << "Reorder stock." << endl;

24:         cout << "Give sales staff a raise." << endl;

25:       }

26:     else

27:      { cout << "Replace the sales staff." << endl; }

28:

29:     // An if with a logical test

30:     if ((numCusts >= 50) && (totalSales >= 5000.00))

31:       {

32:         cout << "Take a day off!" << endl;

33:         cout << "Remodel the store." << endl;

34:       }

35:     return;

36:  }

Output


How many customers were in yesterday? 13

What were the total sales? 675.45

Replace the sales staff.

How many customers were in yesterday? 43

What were the total sales? 1982.34

Order more snacks for tomorrow.

Replace the sales staff.

How many customers were in yesterday? 54

What were the total sales? 9045.67

Order more snacks for tomorrow.

Reorder stock.

Give sales staff a raise.

Take a day off!

Remodel the store.

Analysis

As you can see from the three runs shown in the output, very different messages print depending on the combination of the user's input. The if and the logical operators help ensure that every possible option is covered. The if on line 17 prints a message only if the number of customers exceeds 25. Whether that message prints or not, line 21 contains the first line of an if-else that prints a message based on the quantity of the total sales. Line 31 controls the printing that prints a message only if both the number of customers and the total sales exceed certain limits.

Homework



General Knowledge


  1. Why don't the relational operators do any math?

  2. What values do the relational operators return?

  3. Would the following assignment store a 1 (true) or a 0 (false) in answer? (This is trickier than it first appears!)


    
    answer = (4 == 4 == 4);
  4. What is input validation?

  5. What's the difference between an if and an if-else statement?

  6. Which logical operator works on a single relational value?

  7. Why are braces suggested around all if bodies, even if the body of the if contains only a single statement?

  8. How do the logical operators differ from the relational operators?

  9. Determine which of the following tests are true and which are false based on the following variable definitions:

    
    int a = 0;
    
    int b = 1;

  10. A. (a < b || b < a)

    B. !b

    C. !a

    D. (!(a == b))

    E. (a != b)

    F. (a && b)

    G. (a || b)

  11. What is the short-circuiting feature of the logical operators?

  12. Does the word Hi appear always or sometimes given the following if statement?

    
    if (9 > 3);
    
      { cout << "Hi" << endl; }
  13. True or false: You should use the ! operator as often as possible.

  14. True or false: if-else lets your program choose from among many possible actions.

  15. True or false: A nested if statement lets your program choose from among many possible actions.

  16. True or false: The short-circuiting feature helps improve your program's efficiency.


    What's the Output?


  17. This uses that tricky ! you were told to stay away from. (You'll understand why when you see this problem.) Will the following cout execute?

    
    if (!1)
    
      { cout << "This is tricky!" << endl; }

    Find the Bug


  18. What's wrong with the following if statement?

    
    if age == 18
    
      { cout << "You can vote" << endl;  }

  19. What's wrong with the following if statement?

    
    if (amt < 2);
    
      { flag = 1;
    
        cout << "Everything is not all well..." << endl;
    
      }

    Write Code That. . .


  20. Rewrite the following code to remove the ! but keep the same if logic:

    
    if (!(sales != oldSales))
  21. Write a program that computes pay and overtime pay based on the following conditions:

    A. Pay $5.65 for each hour up to and including 40 hours worked.

    B. Pay time and a half for any hours worked from over 40 to 50.

    C. Pay double time for any hours worked over 50.

    Extra Credit


  22. Rewrite question 20 so that a special tax of $.02 per hour is deducted from all employees working fewer than 40 hours to help pay for their added training needs.

  23. Write a program for a health food store that calculates price from the following table based on the number of vitamins sold:
Number Sold Cost Per Vitamin
25 or fewer $.05 per vitamin
26 to 49 $.04 per vitamin over 25
50 or more $.03 per vitamin over 49

Previous Page Page Top TOC Next Page