CHAPTER 7

Conditional
Statements

Chapter Objectives

By the end of the chapter, readers will be able to:

images  Create and recognize well-formed conditions using both relational and logical operators.

images  Understand the truth tables associated with logical operators.

images  Develop solutions using standard C++ conditional statements.

images  Discuss the issues dealing with scope.

images  Understand and write C++ selection statements.

images  Use the ternary conditional operator.

Introduction

In this chapter we will introduce constructs that conditionally execute one or more statements. Up to this point our programs have almost exclusively executed sequentially, starting at main and executing line by line until the end of the program. However, in the development of many algorithms, it is necessary to perform a specific task if a particular condition occurs. To handle this situation, conditionals need to be used. In this chapter we will also introduce and discuss the operators required to build valid conditions, which determine the statement(s) that will be executed.

7.1 Conditional Expressions

Conditions compare the values of variables, constants, and literals using one or more of the relational operators found in Table 7.1.1. These are binary operators, which means that a variable, a constant, or a literal must appear on each side of the operator. The comparison determines whether the expression is true or false.

Relational Operator Description
== Equality (be sure to use two equals signs)
!= Inequality
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to

Table 7.1.1 Relational operators

7.1.1 Relational Operators

Table 7.1.1 shows the operators used in creating conditions. All of these operators return a Boolean value, either true or false.

Example 7.1.1 illustrates the use of various relational operators.

images

7.1.2 Logical Operators

Logical operators, as shown in Table 7.1.2, are used to combine multiple relational operators into a larger composite condition.

The || (OR) and && (AND) are binary operators, whereas the ! (NOT) is a unary operator. The && results in a true value only if the conditions on both sides of the operator are true. The || results in a false value only if the conditions on both sides of the operator are false. The ! operator reverses the logic of the single condition.

Tables 7.1.3 and 7.1.4 show the truth tables that are the result of combining various logical operators.

Logical Operator Description
&& AND
|| OR
! NOT

Table 7.1.2 Logical operators

Condition 1 Condition 2 && Result || Result
true true true true
true false false true
false true false true
false false false false

Table 7.1.3 Logical AND and OR truth table

Condition ! Result
true false
false true

Table 7.1.4 Logical NOT truth table

The order of precedence gives the && operator a higher level of importance than the || operator; therefore, it is evaluated before the || operator when both appear in the same expression. Interestingly enough, the ! operator has the highest level of precedence of all the logical operators and even places higher than the relational operators.

If more than one logical operator of the same level of precedence appears in a condition, they are evaluated from left to right. Parentheses not only change the precedence, as we've seen in mathematical expressions, but also help clarify and simplify any complicated conditions for the programmer reading the code.

As soon as the outcome of the condition can be determined, the evaluation terminates. Therefore, some conditions may not be evaluated. This is called short-circuit evaluation. For example, if the first part of an && expression is false, there is no need to proceed because the result must be false. In the case of an || expression, if the first condition is true, the final result must also be true. The code provided in Example 7.1.2 illustrates the use of various logical operators.

images

images

The concept of short-circuit evaluation is important because if used correctly, it can help improve the efficiency of your program. To help facilitate this, you should place the most common condition first. In essence you are saying, in the case of &&, “If this condition is false, do not go any further.”

STYLE NOTE Do not forget the old saying, “Just because you can do something, doesn't mean you should.” Just because you can make very complicated conditions by chaining multiple logical operators doesn't mean you should. Make the conditions more readable by using parentheses to help clarify the condition and to avoid any unnecessary confusion and uncertainty. Be careful not to make overly complicated conditions by combining a series of logical operators.

Section 7.1 Exercises

Assume the following declarations for the exercises that follow:

int int_exp1 = 0, int_exp2 = 1;

char char_exp = ‘B’;

Evaluate the following conditions. For the ones that are incorrect, describe what is wrong with them and show their corrected forms.

1. int_exp1 => int_exp2

2. int_exp1 = int_exp2

3. int_exp1 =! int_exp2

4. char_exp == “A”

5. int_exp1 > char_exp

6. int_exp1 < 2 && > -10

7.2 The if Statement

The if statement uses conditions to determine whether a specific action will be executed. It is similar to saying, “If this condition is true, execute this statement.”

The general form for the if statement is shown here:

images

The <condition> represents any valid expression, built either from the relational and logical operators or from the evaluation of a single variable. So how can a float variable be evaluated as true or false? To the computer, zero is considered false while any nonzero value is considered true.

The <action> in the preceding syntax example represents any valid C++ statement. Let us emphasize: any single statement. If more than one statement needs to be executed, you must enclose multiple statements in curly braces { }. The braces create a block of statements, thus allowing the if statement to control the execution of the action block. Example 7.2.1 illustrates both a single-line and a multiple-line action block.

images

Notice in Example 7.2.1 that there are no semicolons after the condition components of the if statements. Although it is syntactically correct to include them, the results will leave you scratching your head. Since a semicolon is used to terminate a statement, if it is used after the condition, the if statement will be terminated at that point. In other words, the action block will be separated from the if statement. Therefore, any statements in the action block will always be executed, regardless of the condition's results.

STYLE NOTE The physical position of the opening curly brace has long been debated. Some programmers like to put it on the same line as the if statement. Others put it on the next line under the if statement, as shown in Example 7.2.1. It is not the intention of this book to waste the reader's time debating this issue. However, our personal preference is to follow the style illustrated in Example 7.2.1.

Another difference in style relates to the usage of curly braces when only a single statement is associated with a control statement, such as an if statement. Some programmers prefer to use curly braces even if there is only a single statement, while others don't. It is our preference to use curly braces only when the action contains multiple statements.

One point most, but not all, programmers agree on is indentation. The statements associated with the if statement are indented, three or four spaces, to show that the action statements are associated with a specific if statement. Fortunately, the default tab size of most development tools and editors is three or four spaces, although they can be customized.

In relation to style issues, it basically comes down to two things:

1.  Follow the style guide of the organization for which you are programming. As a student, you are programming for your instructors, and therefore you need to follow their style.

2.  Be consistent. If your organization doesn't have a preference, choose the style you feel looks the best, and stick with that style.

7.2.1 The else Statement

The else statement is an optional part of the if statement. It cannot stand alone; it always has to be associated with an if statement.

images

The else statement has no condition or expression associated with it, relying instead on the results of the condition associated with the if statement. The else statement executes its action only if the condition is false. In other words, “If the condition is true, execute action 1; otherwise, execute action 2.” As previously noted, an action block can contain one or more statements, but if there is more than one statement, the action must be enclosed in curly braces. In Example 7.2.2, the variable pass will be set to true only if the value in the variable grade is greater than or equal to 60.

images

7.2.2 The else if Statement

Often the need will arise to check another condition when the if statement fails. To do this, we embed another if statement in the action block of the else statement. Notice in Example 7.2.3 how a second condition is embedded within the else statement.

images

In C++, there isn't a reserved word representing an else if statement. That is not true with all languages, however. Both Ada and Visual Basic, just to name two, have specific reserved words to represent an else if statement.

As you can see in Example 7.2.3, the indentation could cause the code to become difficult to read once several else if statements are added. Therefore, it is a common practice to move the if statement to the same line as the else statement, as shown here.

images

The checking of the individual conditions stops when the first true condition is evaluated or the action associated with the final else statement is executed. So, “If condition 1 is true, execute action 1; otherwise, check condition 2. If condition 2 is true, execute action 2; otherwise, evaluate condition 3. If all of the conditions are false, execute the last action.” Note that only one action block will be executed for a given if control structure. However, it is possible to not have any action block executed if there isn't the optional, final else statement.

Using else if statements is much more efficient than using a number of separate if statements. Study Example 7.2.4 and count how many unique comparisons need to be evaluated if the contents of the variable avg are equal to 80.

images

images

Since all if statements need to be assessed, a total of eight conditions are evaluated. In fact, no matter what the value of avg is, eight individual conditions are evaluated. Now, how many conditions are evaluated in Example 7.2.5 if the contents of avg equal 80?

images

Since the evaluation stops after the first true condition in Example 7.2.5, a total of two conditions are evaluated. Even better, if the contents of avg happen to be 90, only a single comparison is made. Since comparisons are processor intensive, this is potentially a significant time saver.

Added efficiency can also be gained if the most commonly true condition is placed higher in the else if list. Doing so would increase the probability that the first or second condition would be evaluated as true, thus terminating the evaluation.

The flow associated with an if-else if-else statement is illustrated in Figure 7.2.1. The flowchart graphically illustrates Example 7.2.5.

images

Figure 7.2.1 if statement flow

Another form of the if statement uses a series of nested if statements to do multiple comparisons. In Example 7.2.6, the action(s) taken will be determined by a combination of true and false conditional expressions.

images

When using the format illustrated in Example 7.2.6, remember that you must map your most nested if statement with the nearest unmatched else statement. Assuming your GPA is 3.76 and your credits are 19, the value of the variable scholarship would become 1000. Clearly you can see the importance of consistent indentation and use of curly braces to clarify a complicated set of statements as shown in the example. While the compiler doesn't care about indentation, the more readable code would definitely make your teacher, boss, and teammates much happier. Be careful that you don't get carried away with the number of levels of nesting. Try to keep things as clean and concise as possible.

Section 7.2 Exercises

Examine the following code fragments for errors. If there is an error, identify the type of error (syntactical, logical, runtime) and how you would fix it. If you are unsure or wish to confirm your evaluation, type it into your compiler and run it!

images

Section 7.2 Learn by Doing Exercise

1.  Write the program to determine the level of membership for a local credit union. There are four levels: Platinum, Gold, Silver, and Copper. If members have $25,000 or more, they are Platinum members. If they have more than $10,000 but less than $25,000 and have two different types of accounts, checking and savings, they are Gold members. If they have more than $10,000 but only have one type of account, they are Silver members. Those members with $10,000 or less are Copper members. Prompt for the amount of money as well as a character representing whether they have checking or savings accounts. For output, display the membership level.

7.3 Variable Scope

There are two central concepts associated with variables:

images  What code has the right to access or change the variable?

images  How long will the variable exist, or live?

 

In programming, this concept is often referred to as the scope of the variable. In its most elementary form, the scope of a variable is what determines where, within your code, the variable can be referenced and used.

In Example 7.3.1, var_a and var_b are both defined within the scope of our block indicated by the curly braces. As you can see, var_a and var_b are both accessible within the block where they are defined. However, in the final line of code we would receive an error message from the compiler because var_b is not defined; its scope is only within the block in which it was declared.

images

As a result of the physical location of the variable declarations, their scope is only within that section of code—the code enclosed by the curly braces. Any code outside of this block will not have access to the variables because they don't exist outside the block.

In Example 7.3.1, the lifetime of var_a and var_b began when the variables were declared within that section of code. When the execution of the program leaves that block of code, var_a and var_b will no longer exist, they will have indeed reached the end of their lifetimes.

Example 7.3.2 illustrates additional aspects associated with the concept of scope. Notice the physical placement of our constant PI along with the variable called global_area at the top of our source code. Because of their placement, outside of any function, they are said to be placed at the global level. All code within the entire source file, including from within the function main, can access them. Global variables are to be avoided because of their ability to be changed from anywhere within your code. This leads to instability and vulnerability to incorrect values within the variables. Variables declared within braces are considered to have local scope.

images

In the future, we will place only our constants at the global level. All of our variables will always be defined within the specific scope where they are used or needed. We will have a lot more to say about the scope of variables later in the text.

One difference between local and global variables is that global variables are automatically initialized. The initial value of all global variables is set to zero.

7.4 The switch Statement

Another form of a conditional statement is the switch statement, sometimes called a selection statement. Unlike if statements, which allow for very complicated conditions, the switch statement only checks for equality and only for one variable. This statement works well when you want to check the contents of a variable for a rather limited set of values. Also, the switch statement only works with ordinal data types. Ordinal data types are those that can be translated into an integer to provide a finite, known number set. Some examples of ordinal data types are int, bool, char, and long. The general form of the switch statement follows:

images

When the first line in the switch statement is encountered, the value of the variable is determined. The execution of the program then jumps to the case that corresponds to the value of the variable being examined. The execution of the switch statement then continues line by line until either a break statement is encountered or the end of the switch statement is reached. Example 7.4.1 illustrates a valid switch statement with all necessary break statements included.

images

Be careful, however; if a break is erroneously left out of the entry case, the action for that case will execute and continue until a break is encountered. Although the break statement is not specifically part of the switch statement, many programmers believe it is poor programming to use a break anywhere outside the context of a switch statement.

The optional default statement is only executed if the value of the variable doesn't match any of the previous cases. Think of default as a type of catchall or “case else.” Also, notice that since default in Example 7.4.2 is the last case, a break statement isn't required because the end of the switch statement will be encountered after all of the statements associated with default are executed.

In Example 7.4.2, the switch statement evaluates the contents of the variable named menu_item. If the value of menu_item is 1, the cout associated with case 1 will execute. If the value of menu_item is 2, the cout associated with case 2 will execute, and so on. If the value doesn't match any of the cases, the cout associated with the default case will execute.

images

images

Even though leaving a break out of a case is a common mistake, it is sometimes done intentionally. This would allow a programmer to simulate a logical OR using a switch statement. Notice in Example 7.4.3 that the text “Stop!” and “Proceed when light is green.” will be displayed if the value in the variable light_color is either 1 or 2.

images

Also note that a single character can be used for case values. When using a single character, the case values are surrounded with single quotation marks to designate a character literal. This is demonstrated in Example 7.4.4.

images

Although there are many uses for the switch statement, one of the most common is in the creation of menu-driven programs. A sample menu for a student grade application is shown in Example 7.4.5.

images

STYLE NOTE Because of the inclusion of the break statement in the switch, it is unnecessary to surround multiple statements inside a specific case with curly braces.

Section 7.4 Exercises

Use the following code fragment for the exercises that follow:

images

images

What is the output generated by the program when the following inputs are provided? Try it first and then prove your results by actually running the code fragment.

1.  0

2.  −1

3.  4

4.  2

5.  1

Section 7.4 Learn by Doing Exercises

1.  Write the program that generates the menu shown in Example 7.4.5. In addition, repeat back to the user which option was selected from the menu using a switch statement.

2.  Claude owns a gas station and wants you to write a program to determine the type of fuel, depending on the octane level. Assume the following values: 87—Regular Unleaded; 89—Unleaded Plus; and 92—Premium. If the octane entered is any other value, the fuel type to be displayed is Diesel.

7.5 Conditional Operator

When we discussed mathematical operators in Chapter 6, we noted the differences between unary and binary operators. The conditional operator is considered a ternary operator, meaning that it has three operands. A few other languages such as Java and C#, whose roots are in C++, also have a ternary operator. The conditional operator is sometimes called an “inline if ”, and the basic syntax is shown here.

<condition> ? <true expression> : <false expression>

In the preceding syntax, one of the expressions is returned based on the evaluation of the condition. In Example 7.5.1, we are finding the larger of two numbers and storing the largest value in a variable called larger.

images

To help clarify what is happening with the conditional operator in Example 7.5.1, Example 7.5.2 accomplishes the same thing using an if statement.

images

Another use of the conditional operator is shown in Example 7.5.3. We use this ternary operator to ensure that each portion of the printed-out time consists of two digits. Inspect the example closely. We hope you will enjoy the added challenge.

images

Did you notice the empty quotation marks in Example 7.5.3? These tell cout to print nothing. In other words, if the condition is false (i.e., the hour is 10 or greater), print nothing.

Section 7.5 Exercises

1.  What is wrong with the following code fragment?

int a = 0;

(a == 0) : cout << “Zero” ? cout << “Non-Zero”;

2.  Use the following code fragment for the exercises that follow:

images

What is the output when age equals the following values?

a. 11

b. 18

c. 75

d. 30

7.6 Problem Solving Applied

Problem statement: You recently got a part-time job working for one of your teachers on campus. She has asked for your help in writing a program that can be used to determine the grade assigned to an individual student based on the results of three exam scores. You will need to ask the user for the student's ID—a five-digit number created by the school—and the scores for each of the three exams. Once you have all the necessary input, please calculate the individual student's overall average and letter grade. The cutoffs for the letter grades are as follows:

A >= 92.0 B >= 84.0 C >= 75.0 D >= 65.0 F < 65.0

Requirement Specification:

Input(s):

Input Type Data Source
Integer student_id Keyboard
Decimal exam_1 Keyboard
Decimal exam_2 Keyboard
Decimal exam_3 Keyboard

Output(s):

Output Type Data Destination
Integer student_id Screen
Decimal exam_1 Screen
Decimal exam_2 Screen
Decimal exam_3 Screen
Decimal overall_average Screen
Character letter_grade Screen

Constants:

Type Data Value
Decimal A_GRADE 92.0
Decimal B_GRADE 84.0
Decimal C_GRADE 75.0
Decimal D_GRADE 65.0

Design:

images

7.7 C—The Differences

The only difference between C and C++ in this chapter is that C doesn't have a Boolean data type. This also means that there isn't a predefined true or false as part of the C language. Because of the lack of the Boolean data type, all relational operators return either a zero for false or a nonzero value—usually one—for true. C programmers often create their own Boolean data type, as shown in Example 7.7.1.

images

Although the C99 version of the ANSI standard includes a Boolean data type, at this time it is not supported by Visual Studio.

7.8 SUMMARY

This chapter introduced the concept of control statements. A control structure is a statement that controls, or alters, the flow of the program. You will see many other ways of controlling the flow of a program in the following chapters. However, most of these statements rely on the basic constructs just discussed.

We have explored three different control structures: the if statement, the switch statement, and the ternary conditional operator. Each statement offers some specific benefits over the others. At times, choosing the right statement will be obvious. At other times, you will need to give it some careful thought. Use the correct tool for the job—that is, choose the best option for your situation. For example, the switch statement tends to lend itself well to use within menu-related code sections, while the if is a much more flexible option.

The bottom line is to always remember to keep your code easy to read and modify. To aid in the readability of your program, avoid complex compound expressions in your program and use a consistent indentation style.

7.9 Debugging Exercise

Download the following file from this book's website and run the program following the instructions noted in the code.

images

images

7.10 Programming Exercises

The following programming exercises are to be developed using all phases of the development method. Be sure to make use of good programming practices and style, such as constants, whitespace, indentation, naming conventions, and commenting. Make sure all input prompts are clear and descriptive and that your output is well formatted and looks professional.

1.  Write a program that accepts two integers that represent the numerator and denominator of a fraction. Display the fraction in an acceptable form in regard to negative signs. Also, if the numerator is larger than the denominator, display the number as a mixed fraction.

2.  Write a program that accepts both the interest rate and the amount of a loan. Check to make sure the interest rate of the loan is between 1% and 18% and that the amount of the loan is between $100 and $1000. If the data fails either of these conditions, display an appropriate error message and end the program. Determine the cost of the loan fees. If the amount of the loan is between $100 and $500, there is a fee of $20. If the loan is more than $500, the fee is $25. Calculate the amount of interest paid on the loan, and display the requested amount of the loan, the interest rate, and the sum of the interest and fees.

3.  Given a quadratic equation in the form of ax2 + bx + c = 0, solve for the roots of the equation using the following formula:

images

Be sure to verify that it is a valid quadratic equation by checking a to make sure it is not zero. If it is zero, display an appropriate error message. Also, if the discriminant—the expression in the square root—is less than zero, display an error message stating that the roots will be complex, imaginary numbers. If the discriminant is zero, the roots will be the same, so display the root and the fact that the roots are identical. Hint: You will need to use the square root math function to solve this problem.

Extra Challenge: Instead of just displaying an error message if the roots are complex, display the complex roots in the correct format for complex numbers.

4.  Write a program that converts 24-hour military time to standard time. Accept the hours, minutes, and seconds from the user, and verify that the inputs are correct. If any of the inputs are invalid, display an error message and end the program. Otherwise, display the output so that each portion of the time is displayed with two digits and the appropriate AM or PM. Use the conditional operator to both display the time as well as determine whether to use AM or PM.

5.  Display a menu to the user that has the following options:

—Main Menu—

1. Calculate Area

2. Calculate Volume

Write a switch statement that handles the user's choice. For each of the main menu options, display a submenu that has the following options.

—Area Menu— —Volume Menu—
a. Rectangle a. Cylinder
b. Circle b. Sphere
c. Right Triangle  

Write nested switch statements to handle each of the submenus. For all of the switch statements, use the default case to handle any incorrect menu options. If you are unsure of the correct formulas, research them on the Internet or in your math books. Display the results of each of the calculations based on the appropriate user input.

7.11 Team Programming Exercise

An old buddy of yours, Marcus, has three children now. He wants to create a program that helps his kids learn some basic number manipulations. Although he used to be a pretty awesome programmer back in the day, he has been in management so long that his skills are more than a little rusty. He started the program but got frustrated and asked you to help him out. Here is what he has so far:

images

As you can see, he didn't get very far before he gave up. To help him out, convert Marcus's if statements to a more efficient switch statement. Also, complete the necessary number manipulations. Remember, even though you are jumping into the middle of a program that is already written (well, almost), don't forget the development process. Treat each menu item as a separate solution, and perform all phases of the development process before moving on to the next menu item. By the way, after looking at his code, Marcus's supervisor informed him that he will be getting a promotion—to keep him away from programming even more.

7.12 Answers to Chapter Exercises

Section 7.1

1.  The symbols in the operator are reversed.

Corrected: int_exp1 >= int_exp2

2.  Should have a double = sign.

Corrected: int_exp1 == int_exp2

3.  The symbols in the operator are reversed.

Corrected: int_exp1 != int_exp2

4.  You can't compare a string literal using relational operators. To designate a character literal, you must use single quotation marks.

Corrected: char_exp == ‘A’

5.  Everything is correct. The integer will be compared to the ASCII value of the character.

6.  Relational operators are binary operators and therefore require an operand on each side of the operator.

Corrected: int_exp1 < 2 && int_exp1 > -10

Section 7.2

1.  Error type: logical

Fix: Remove the semicolon after the condition of the if statement.

2.  Error type: logical

Fix: There is a single = in the condition where there should be two. (A single = is used for assignments, while the == is required when checking for equality.)

3.  Error type: logical

Fix: Should be an && instead of an ||.

4.  Error type: logical

Fix: If you want both statements to execute if the condition is true, enclose the statements in curly braces.

5.  Error type: syntactical

Fix: Put a space between the else and the if.

6.  Error type: syntactical

Fix: There is never a condition associated with the else statement.

7.  Error type: none

Fix: None needed, indentation is for the programmer, not the compiler.

Section 7.4

1.  Zero

2.  Invalid guess entered.

3.  Four

4.  Two

Three

Four

5.  One

Two

Three

Four

Section 7.5

1.  The : and the ? are reversed. Also, it would be better to embed the conditional operator in the cout rather than the cout in the conditional operator. The correct syntax follows.

cout < < (a == 0 ? “Zero” : “Non-Zero”);

2.  a. Pre-Teen

b. Teen

c. Senior

d. Adult

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.101.81