Cpp Conditional

Embed Size (px)

Citation preview

  • 8/13/2019 Cpp Conditional

    1/36

    71

    Chapter 5

    Conditional Execution

    All the programs in the preceding chapters execute exactly the same statements regardless of the input, ifany, provided to them. They follow a linear sequence: Statement1, Statement2, etc. until the last statement

    is executed and the program terminates. Linear programs like these are very limited in the problems they

    can solve. This chapter introduces constructs that allow program statements to be optionally executed,

    depending on the context (input) of the programs execution.

    5.1 Type bool

    Arithmetic expressions evaluate to numeric values; a Boolean expression, sometimes called a predicate,

    evaluates totrueor false. While Boolean expressions may appear very limited on the surface, they are

    essential for building more interesting and useful programs.

    C++ supports the non-numeric data type bool, which stands for Boolean. The term Boolean comes

    from the name of the British mathematician George Boole. A branch of discrete mathematics called

    Boolean algebra is dedicated to the study of the properties and the manipulation of logical expressions.

    Compared to the numeric types, the bool type is very simple in that it can represent only two values:

    true orfalse. Listing5.1 (boolvars.cpp) is a simple program demonstrating the use of Boolean vari-

    ables.

    Listing 5.1:boolvars.cpp

    1 #include

    2

    3 using namespace std;

    4

    5 int main() {

    6 // Declare some Boolean variables

    7 bool a = true, b = false;

    8 cout

  • 8/13/2019 Cpp Conditional

    2/36

    5.2. BOOLEAN EXPRESSIONS 72

    Operator Meaning

    == Equal to

    < Less than

    > Greater than

    = Greater than or equal to

    != Not equal to

    Table 5.1: C++Relational operators

    15 cout

  • 8/13/2019 Cpp Conditional

    3/36

    5.2. BOOLEAN EXPRESSIONS 73

    Expression Value

    10 < 20 always true

    10 >= 20 always false

    x == 10 true only ifx has the value 10

    X ! = y true unlessx andy have the same values

    Table 5.2: Relational operator examples

    The relational operators are binary operators and are all left associative. They all have a lower prece-

    dence than any of the arithmetic operators; therefore, the expression

    x + 2 < y / 10

    is evaluated as if parentheses were placed as so:

    ( x + 2 ) < ( y / 1 0 )

    C++allows statements to be simple expressions; for example, the statement

    x == 15;

    may look like an attempt to assign the value 15 to the variable x, but it is not.

    The = operator performs assignment, but the == operator checks for relational

    equality. If you make a mistake and use == as shown here,VisualC++will issue a

    warning that includes the message

    warning C4553: == : operator has no effect; did you intend =?

    Recall from Section4.6.4that a compiler warning does not indicate a violation of

    the rules of the language; rather it alerts the programmer to a possible trouble spotin the code.

    Another example of an expression used as a statement is

    x + 1 5 ;

    This statement is a legal (but useless) C++statement, and the compiler notifies us

    accordingly:

    warning C4552: + : operator has no effect; expected operator with

    side-effect

    Why are expressions allowed as statements? Some simple expressions have side

    effects that do alter the behavior of the program. One example of such an ex-

    pression is x++. Listing4.13(prevspost.cpp) showed how x++ behaves both as astandalone statement and as an expression within a larger statement. A more com-

    mon example is the use of a function call (which is an expression) as standalone

    a statement. (We introduce functions in Chapter8.) In order to keep the structure

    of the language as uniform as possible, C++tolerates useless expressions as state-

    ments to enable programmers to use the more useful expression-statements. For-

    tunately, most compilers issue informative warnings about the useless expression-

    statements to keep developers on track.

    2013 Richard L. Halterman Draft date: September 5, 2013

    http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-
  • 8/13/2019 Cpp Conditional

    4/36

    5.3. THE SIMPLE IF STATEMENT 74

    5.3 The Simple if Statement

    The Boolean expressions described in Section 5.2at first may seem arcane and of little use in practical

    programs. In reality, Boolean expressions are essential for a program to be able to adapt its behavior at runtime. Most truly useful and practical programs would be impossible without the availability of Boolean

    expressions.

    The run-time exceptions mentioned in Section 4.6arise from logic errors. One way that Listing4.7

    (dividedanger.cpp) can fail is when the user enters a zero for the divisor. Fortunately, programmers can take

    steps to ensure that division by zero does not occur. Listing5.2(betterdivision.cpp) shows how it might be

    done.

    Listing 5.2:betterdivision.cpp

    1 #include

    2

    3 using namespace std;

    4

    5 int main() {6 int dividend, divisor;

    7

    8 // Get two integers from the user

    9 cout > dividend >> divisor;

    11 // If possible, divide them and report the result

    12 if (divisor != 0)

    13 cout

  • 8/13/2019 Cpp Conditional

    5/36

    5.3. THE SIMPLE IF STATEMENT 75

    determines if the single statement that follows the right parenthesis is executed. Ifdivisor is not zero,

    the message is printed; otherwise, the program prints nothing.

    Figure 5.1 shows how program execution flows through the if statement. of Listing 5.2 (betterdivision.cpp).

    do the division

    and print result

    Is

    divisor !0?

    yes

    no

    Figure 5.1: if flowchart

    The general form of theif statement is:

    if (condition )

    statement;

    The reserved wordif begins theif statement.

    The Boolean expressionconditiondetermines whether or not the body will be executed. The Boolean

    expression mustbe enclosed within parentheses as shown.

    Thestatementis the statement to be executed if the Boolean expression is true. The statement makes

    up the body of the if statement. Section5.4 shows how the body can be composed of multiple

    statements.

    Good coding style dictates the body should be indented to emphasize the optional execution and improve

    the programs readability. The indenting is not required by the compiler. Sometimes programmers will place

    a short body on the same time as the if; for example, the following if statement optionally assigns y:

    2013 Richard L. Halterman Draft date: September 5, 2013

    http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-
  • 8/13/2019 Cpp Conditional

    6/36

    5.3. THE SIMPLE IF STATEMENT 76

    if (x < 10)

    y = x ;

    and could be written as

    if ( x < 1 0 ) y = x ;

    but shouldnotbe written as

    if (x < 10)

    y = x ;

    because the lack of indentation hides the fact that the program optionally executes the assignment statement.

    The compiler will accept it, but it is misleading to human readers accustomed to the indentation convention.

    The compiler, of course, will accept the code written as

    if(x

  • 8/13/2019 Cpp Conditional

    7/36

    5.4. COMPOUND STATEMENTS 77

    5.4 Compound Statements

    Sometimes more than one statement must be optionally executed. Listing5.3(alternatedivision.cpp) shows

    how curly braces are used to group multiple statements together into one compound statement.

    Listing 5.3:alternatedivision.cpp

    1 #include

    2

    3 using namespace std;

    4

    5 int main() {

    6 int dividend, divisor, quotient;

    7

    8 // Get two integers from the user

    9 cout > dividend >> divisor;

    11 // If possible, divide them and report the result

    12 if (divisor != 0) {

    13 quotient = dividend / divisor;

    14 cout

  • 8/13/2019 Cpp Conditional

    8/36

    5.5. THE IF/ELSE STATEMENT 78

    The format of the following code

    if (x < 10)

    y = x ;z = x + 5;

    implies that both assignments are part of the body of the if statement. Since

    multiple statements making up the body must be in a compound statement within

    curly braces, the compiler interprets the code fragment as if it had been written

    if (x < 10)

    y = x ;

    z = x + 5 ;

    Such code will optionally execute the first assignment statement and alwaysexe-

    cute the second assignment statement.

    The programmer probably meant to write it as

    if ( x < 1 0 ) {y = x ;

    z = x + 5;

    }

    The curly braces are optional if the body consists of a single statement. If the body consists of only one

    statement and curly braces are not used, then the semicolon that terminates the statement in the body also

    terminates theif statement. If curly braces are used to delimit the body, a semicolon is not required after

    the bodys close curly brace.

    5.5 The if/else Statement

    One undesirable aspect of Listing5.2 (betterdivision.cpp) is if the user enters a zero divisor, the program

    prints nothing. It may be better to provide some feedback to the user to indicate that the divisor provided

    cannot be used. The if statement has an optional else clause that is executed only if the Boolean expres-

    sion is false. Listing5.4(betterfeedback.cpp) uses the if/elsestatement to provide the desired effect.

    Listing 5.4:betterfeedback.cpp

    1 #include

    2

    3 using namespace std;

    4

    5 int main() {

    6 int dividend, divisor;

    7

    8 // Get two integers from the user

    9 cout > dividend >> divisor;

    11 // If possible, divide them and report the result

    12 if (divisor != 0)

    13 cout

  • 8/13/2019 Cpp Conditional

    9/36

    5.5. THE IF/ELSE STATEMENT 79

    14

  • 8/13/2019 Cpp Conditional

    10/36

    5.5. THE IF/ELSE STATEMENT 80

    if ( condition)

    if statement;

    elseelse statement;

    The reserved wordif begins theif/else statement.

    Theconditionis a Boolean expression that determines whether or not the if statement or theelse

    statement will be executed. The condition must be in parentheses.

    The if statement is the statement to be executed if the condition is true. To make the if/else

    statement more readable, theif statementis indented more spaces than theif line. This part of the

    ifstatement is sometimes called the body of the if.

    The reserved wordelsebegins the second part of the if/elsestatement.

    The else statement is the statement to be executed if the condition is false. To make the if/else

    statement more readable, the else statementis indented more spaces than the else line. This part of

    theif/elsestatement is sometimes called the body of the else.

    The body of theelseclause of anif/elsestatement may be a compound statement:

    if (x == y)

    cout

  • 8/13/2019 Cpp Conditional

    11/36

    5.5. THE IF/ELSE STATEMENT 81

    Remember, if you wish to associate more than one statement with the body of

    theif or else, you must use a compound statement. Compound statements are

    enclosed within curly braces ({}).

    Due to the imprecise representation of floating-point numbers (see Listing4.3(imprecise10.cpp) in Sec-

    tion4.1), the equality operator (==) by itself should not be used when comparing floating-point expressions.

    Listing5.5(samedifferent.cpp) uses anif/elsestatement to demonstrate the perils of using the equality

    operator with floating-point quantities.

    Listing 5.5:samedifferent.cpp

    1 #include

    2 #include 3

    4 using namespace std;

    5

    6 int main() {

    7 double d1 = 1.11 - 1.10,

    8 d2 = 2.11 - 2.10;

    9 cout

  • 8/13/2019 Cpp Conditional

    12/36

    5.6. COMPOUND BOOLEAN EXPRESSIONS 82

    e1 e2 e1 && e2 e1 || e2 !e1false false false false true

    false true false true true

    true false false true false

    true true true true false

    Table 5.3: Logical operatorse1and e2are Boolean expressions

    5.6 Compound Boolean Expressions

    Simple Boolean expressions, each involving one relational operator, can be combined into more complex

    Boolean expressions using the logical operators && (and), || (or), and ! (not). A combination of two or

    more Boolean expressions using logical operators is called a compound Boolean expression.

    To introduce compound Boolean expressions, consider a computer science degree that requires, among

    other computing courses,Operating SystemsandProgramming Languages. If we isolate those two courses,

    we can say a student must successfully complete both Operating Systemsand Programming Languagestoqualify for the degree. A student that passes Operating Systemsbut not Programming Languageswill not

    have met the requirements. Similarly,Programming LanguageswithoutOperating Systemsis insufficient,

    and a student completing neither Operating Systemsnor Programming Languagessurely does not qualify.

    LogicalANDworks in exactly the same way. Ife1and e2are two Boolean expressions, e1&& e2is true

    only if e1 and e2 are both true; if either one is false or both are false, the compound expression is false.

    To illustrate logicalOR, consider two mathematics courses,Differential EquationsandLinear Algebra.

    A computer science degree requires one of those two courses. A student who successfully completes

    Differential Equationsbut does not take Linear Algebrameets the requirement. Similarly, a student may

    take Linear Algebrabut notDifferential Equations. It is important to note the a student may elect to take

    both Differential Equations and Linear Algebra (perhaps on the way to a mathematics minor), but the

    requirement is no less fulfilled.

    LogicalOR works in a similar fashion. Given our Boolean expressionse1 and e2, the compound ex-

    pression e1|| e2is false only ife1and e2are both false; if either one is true or both are true, the compound

    expression is true. Note that logicalOR is an inclusive or, not an exclusive or. In informal conversion we

    often implyexclusive orin a statement like Would you like cake or ice cream for dessert? The implica-

    tion is one or the other, not both. In computer programming theoris inclusive; if both subexpressions in

    anorexpression are true, the orexpression is true.

    Logical NOT simply reverses the truth value of the expression to which it is applied. If e is a true

    Boolean expression,!eis false; if eis false,!eis true.

    Table5.3 is called a truth table. It shows all the combinations of truth values for two simple expres-

    sions and the values of compound Boolean expressions built from applying the &&,||, and! C++logical

    operators.

    Both && and || are binary operators; that is, they require two operands, both of which must be Booleanexpressions. Logical not (!) is a unary operator (see Section 4.1); it requires a single Boolean operand

    immediately to its right.

    Operator ! has higher precedence than both && and ||. && has higher precedence than ||. && and ||

    are left associative;! is right associative. && and|| have lower precedence than any other binary operator

    except assignment. This means the expression

    x < = y & & x < = z

    2013 Richard L. Halterman Draft date: September 5, 2013

    http://-/?-http://-/?-http://-/?-http://-/?-
  • 8/13/2019 Cpp Conditional

    13/36

    5.6. COMPOUND BOOLEAN EXPRESSIONS 83

    is evaluated

    (x

  • 8/13/2019 Cpp Conditional

    14/36

    5.6. COMPOUND BOOLEAN EXPRESSIONS 84

    b = (x != 10 || y != 20); // assigns false to b

    Convince yourself that the following expressions are equivalent:

    (x != y)

    !(x == y)

    ( x < y | | x > y )

    In the expression e1 &&e2 both subexpressionse1 ande2 must be true for the overall expression to be

    true. Since the&& operator evaluates left to right, this means that ife1is false, there is no need to evaluate

    e2. Ife1is false, no value ofe2can make the expressione1&& e2true. The logicalandoperator first tests the

    expression to its left. If it finds the expression to be false, it does not bother to check the right expression.

    This approach is called short-circuit evaluation. In a similar fashion, in the expressione1 || e2, ife1 is

    true, then it does not matter what value e2 hasa logicalorexpression is true unless both subexpressions

    are false. The|| operator uses short-circuit evaluation also.

    Why is short-circuit evaluation important? Two situations show why it is important to consider:

    The order of the subexpressions can affect performance. When a program is running, complex ex-

    pressions require more time for the computer to evaluate than simpler expressions. We classify an

    expression that takes a relatively long time to evaluate as an expensive expression. If a compound

    Boolean expression is made up of an expensive Boolean subexpression and an less expensive Boolean

    subexpression, and the order of evaluation of the two expressions does not affect the behavior of the

    program, then place the more expensive Boolean expression second. If the first subexpression is false

    and && is being used, then the expensive second subexpression is not evaluated; if the first subex-

    pression is true and|| is being used, then, again, the expensive second subexpression is avoided.

    Subexpressions can be ordered to prevent run-time errors. This is especially true when one of the

    subexpressions depends on the other in some way. Consider the following expression:

    (x != 0) && (z/x > 1)

    Here, ifx is zero, the division by zero is avoided. If the subexpressions were switched, a run-time

    error would result ifx is zero.

    2013 Richard L. Halterman Draft date: September 5, 2013

  • 8/13/2019 Cpp Conditional

    15/36

    5.7. NESTED CONDITIONALS 85

    Arity Operators Associativity

    unary (post)++, (post)--,static_cast

    unary (pre)++, (pre)--,!,+,-

    binary *,/,% left

    binary +,- left

    binary leftbinary >,=,

  • 8/13/2019 Cpp Conditional

    16/36

    5.7. NESTED CONDITIONALS 86

    4

    5 int main() {

    6 int value;

    7 cout > value;9 if (value >= 0) // First check

    10 if (value

  • 8/13/2019 Cpp Conditional

    17/36

    5.7. NESTED CONDITIONALS 87

    5 int main() {

    6 int value;

    7 cout > value;

    9 if (value >= 0) // First check10 if (value

  • 8/13/2019 Cpp Conditional

    18/36

    5.7. NESTED CONDITIONALS 88

    31 cout

  • 8/13/2019 Cpp Conditional

    19/36

    5.7. NESTED CONDITIONALS 89

    The following shows a sample run of Listing 5.9(binaryconversion.cpp):

    Please enter an integer value in the range 0...1023: 8051100100101

    Figure5.3illustrates the execution of Listing5.9(binaryconversion.cpp) when the user enters 805.

    Figure 5.3: The process of the binary number conversion program when the user supplies 805 as the input

    value.

    Listing5.10(simplerbinaryconversion.cpp) simplifies the logic of Listing?? (BinaryConversion.java) at

    the expense of some additional arithmetic. It uses only one if statement.

    Listing 5.10:simplerbinaryconversion.cpp

    1 #include

    2

    3 using namespace std;

    4

    5 int main() {

    6 int value;

    7 // Get number from the user

    8 cout > value;

    2013 Richard L. Halterman Draft date: September 5, 2013

    http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-
  • 8/13/2019 Cpp Conditional

    20/36

    5.7. NESTED CONDITIONALS 90

    10 // Integer must be less than 1024

    11 if (0

  • 8/13/2019 Cpp Conditional

    21/36

    5.7. NESTED CONDITIONALS 91

    21 cin >> choice;

    22 if (choice == 'n') { // The switch is off, turn it on!

    23 cout

  • 8/13/2019 Cpp Conditional

    22/36

    5.7. NESTED CONDITIONALS 92

    Figure 5.4: Decision tree for troubleshooting a computer system

    The program directs the user to make the easier checks first. It progressively introduces more difficult

    checks as it continues. Based on your experience with troubleshooting computers that do not run properly,

    you may be able to think of many enhancements to this simple program.

    Note that in Listing 5.11(troubleshoot.cpp) curly braces are used in many places where they strictly

    are not necessary. Their inclusion in Listing5.11(troubleshoot.cpp) improves the readability of the pro-

    gram and makes the logic easier to understand. Even if you do not subscribe to the philosophy of using

    curly braces for every if/elsebody, it is a good idea to use them in situations that improve the codes

    readability.

    Recall the time conversion program in Listing 4.11 (timeconv.cpp). If the user enters 10000, the

    program runs as follows:

    Please enter the number of seconds:10000

    2 hours 46 minutes 40 seconds

    and if the user enters 9961, the program prints:

    Please enter the number of seconds:9961

    2 hours 46 minutes 1 second

    2013 Richard L. Halterman Draft date: September 5, 2013

    http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-
  • 8/13/2019 Cpp Conditional

    23/36

    5.7. NESTED CONDITIONALS 93

    Suppose we wish to improve the English presentation by not using abbreviations. If we spell out hours,

    minutes, and seconds, we must be careful to use the singular form hour, minute, or second when the

    corresponding value is one. Listing5.12 (timeconvcond1.cpp) uses if/else statements to express to

    time units with the correct number.

    Listing 5.12:timeconvcond1.cpp

    1 // File timeconvcond1.cpp

    2

    3 #include

    4

    5 using namespace std;

    6

    7 int main() {

    8 // Some useful conversion constants

    9 const int SECONDS_PER_MINUTE = 60,

    10 SECONDS_PER_HOUR = 60*SECONDS_PER_MINUTE; // 3600

    11 int hours, minutes, seconds;

    12 cout > seconds;

    14 // First, compute the number of hours in the given number

    15 // of seconds

    16 hours = seconds / SECONDS_PER_HOUR; // 3600 seconds = 1 hours

    17 // Compute the remaining seconds after the hours are

    18 // accounted for

    19 seconds = seconds % SECONDS_PER_HOUR;

    20 // Next, compute the number of minutes in the remaining

    21 // number of seconds

    22 minutes = seconds / SECONDS_PER_MINUTE; // 60 seconds = 1 minute

    23 // Compute the remaining seconds after the minutes are

    24 // accounted for

    25 seconds = seconds % SECONDS_PER_MINUTE;26 // Report the results

    27 cout

  • 8/13/2019 Cpp Conditional

    24/36

    5.7. NESTED CONDITIONALS 94

    Theif/elsestatements within Listing5.12(timeconvcond1.cpp) are responsible for printing the correct

    versionsingular or pluralfor each time unit. One run of Listing5.12(timeconvcond1.cpp) produces

    Please enter the number of seconds:10000

    2 hours 46 minutes 40 seconds

    All the words are plural since all the value are greater than one. Another run produces

    Please enter the number of seconds:9961

    2 hours 46 minutes 1 second

    Note the wordsecondis singular as it should be.

    Please enter the number of seconds:3601

    1 hour 0 minutes 1 second

    Here again the printed words agree with the number of the value they represent.

    An improvement to Listing5.12(timeconvcond1.cpp) would not print a value and its associated time

    unit if the value is zero. Listing5.13(timeconvcond2.cpp) adds this feature.

    Listing 5.13:timeconvcond2.cpp

    1 // File timeconvcond1.cpp

    2

    3 #include

    4

    5 using namespace std;

    6

    7 int main() {

    8 // Some useful conversion constants

    9 const int SECONDS_PER_MINUTE = 60,

    10 SECONDS_PER_HOUR = 60*SECONDS_PER_MINUTE; // 3600

    11 int hours, minutes, seconds;

    12 cout > seconds;

    14 // First, compute the number of hours in the given number

    15 // of seconds

    16 hours = seconds / SECONDS_PER_HOUR; // 3600 seconds = 1 hours

    17 // Compute the remaining seconds after the hours are

    18 // accounted for

    19 seconds = seconds % SECONDS_PER_HOUR;

    20 // Next, compute the number of minutes in the remaining

    21 // number of seconds

    22 minutes = seconds / SECONDS_PER_MINUTE; // 60 seconds = 1 minute

    23 // Compute the remaining seconds after the minutes are

    2013 Richard L. Halterman Draft date: September 5, 2013

    http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-
  • 8/13/2019 Cpp Conditional

    25/36

    5.7. NESTED CONDITIONALS 95

    24 // accounted for

    25 seconds = seconds % SECONDS_PER_MINUTE;

    26 // Report the results

    27 if (hours > 0) { // Print hours at all?

    28 cout

  • 8/13/2019 Cpp Conditional

    26/36

    5.8. MULTI-WAY IF/ELSE STATEMENTS 96

    Please enter the number of seconds:3601

    1 hour 1 second

    Here again the printed words agree with the number of the value they represent.

    Please enter the number of seconds:7200

    2 hours

    Another run produces:

    Please enter the number of seconds:601 minute

    Finally, the following run shows that the program handles zero seconds properly:

    Please enter the number of seconds:0

    0 seconds

    5.8 Multi-way if/else Statements

    A simple if/else statement can select from between two execution paths. Suppose we wish to choose

    one execution path from among several possible paths, as shown in Figure 5.5? Listing 5.8 (enhancedcheckrange.cpp)

    showed how to select from among three options. What if exactly one of many actions should be taken?

    Nestedif/elsestatements are required, and the form of these nested if/elsestatements is shown in

    Listing5.14(digittoword.cpp).

    Listing 5.14:digittoword.cpp

    1 #include

    2

    3 using namespace std;

    4

    5 int main() {

    6 int value;

    7 cout > value;

    9 if (value < 0)

    10 cout

  • 8/13/2019 Cpp Conditional

    27/36

    5.8. MULTI-WAY IF/ELSE STATEMENTS 97

    Figure 5.5: Flowchart with multiple optional execution pathways

    14 else

    15 if (value == 1)

    16 cout

  • 8/13/2019 Cpp Conditional

    28/36

    5.8. MULTI-WAY IF/ELSE STATEMENTS 98

    Listing5.14(digittoword.cpp) is formatted according to the conventions used in earlier examples. As

    a consequence, the mass of text drifts to the right as more conditions are checked. A commonly used

    alternative style, shown in Listing5.15(restyleddigittoword.cpp), avoids this rightward drift.

    Listing 5.15:restyleddigittoword.cpp

    1 #include

    2

    3 using namespace std;

    4

    5 int main() {

    6 int value;

    7 cout > value;

    9 if (value < 0)

    10 cout

  • 8/13/2019 Cpp Conditional

    29/36

    5.8. MULTI-WAY IF/ELSE STATEMENTS 99

    13 cout

  • 8/13/2019 Cpp Conditional

    30/36

    5.9. ERRORS IN CONDITIONAL STATEMENTS 100

    Please enter the month and day as numbers: 5 20

    May 20 or 20 de mayo

    5.9 Errors in Conditional Statements

    Consider Listing5.17(badequality.cpp).

    Listing 5.17:badequality.cpp

    1 #include

    2

    3 using namespace std;

    4

    5 int main() {

    6 int input;7 cout > input;

    9 if (input = 2)

    10 cout

  • 8/13/2019 Cpp Conditional

    31/36

    5.10. SUMMARY 101

    found in Listing5.7(newcheckrange.cpp). Confusing logicalandand logicaloris a common programming

    error. If you substitute|| for &&, the expression

    x > 0 || x 0 || x 1 0)

    /* Code to execute goes here . . . */

    A closer look at the condition reveals it can neverbe true. What number can be both less than zero and

    greater than tenat the same time? None can, of course, so the expression is a contradiction and a compli-

    cated way of expressing false. To correct this code fragment, replace the&& operator with||.

    5.10 Summary

    Thebooldata type represents the values true and false.

    The nameboolcomes from Boolean algebra, the mathematical study of operations on truth values.

    In C++the valuetrueis represented by the integer one, andfalseis represented by zero.

    Any integer value except zero is treated as true.

    Integers andbools are interchangeable and can be assigned to each other.

    Expressions involving the relational operators (==, !=, , =) evaluate to Boolean values.

    !is the unarynotoperator.

    Boolean expressions can be combined via&& (logicalAND) and|| (logicalOR).

    Theif statement can be used to optionally execute statements.

    A compound statement is a sequence of statements within a pair of curly braces.

    The if statement has an optionalelseclause to require the selection between two alternate paths

    of execution.

    Theif/elsestatements can be nested to achieve arbitrary complexity.

    2013 Richard L. Halterman Draft date: September 5, 2013

    http://-/?-http://-/?-
  • 8/13/2019 Cpp Conditional

    32/36

    5.11. EXERCISES 102

    The bodies ofif/else statements should be indented to aid human readers. Indentation doe not

    affect the logic of the program; when multiple statements are to be part of the body of an if or else,

    the statements must be part of a compound statement.

    Beware placing a semicolon immediately after the close parenthesis of anif statements condition.

    Complex Boolean expressions require special attention, as they are easy to get wrong.

    5.11 Exercises

    1. What values can a variable of typeboolassume?

    2. Where does the termbooloriginate?

    3. What is the integer equivalent totruein C++?

    4. What is the integer equivalent tofalsein C++?

    5. Is the value-16 interpreted as true or false?

    6. May an integer value be assigned to aboolvariable?

    7. Cantruebe assigned to an int variable?

    8. Given the following declarations:

    int x = 3 , y = 5 , z = 7 ;bool b1 = true, b 2 = false, b 3 = x = = 3 , b 4 = y < 3 ;

    evaluate the following Boolean expressions:

    (a) x == 3

    (b) x < y

    (c) x >= y

    (d) x = 0 && x < 10(h) x < 0 && x < 10

    (i) x >= 0 && x < 2

    (j) x < 0 || x < 10

    (k) x > 0 || x < 10

    (l) x < 0 || x > 10

    (m) b1

    2013 Richard L. Halterman Draft date: September 5, 2013

  • 8/13/2019 Cpp Conditional

    33/36

    5.11. EXERCISES 103

    (n) !b1

    (o) !b2

    (p) b1 && b2

    9. Express the following Boolean expressions in simpler form; that is, use fewer operators. x is an int.

    (a) !(x == 2)

    (b) x < 2 || x == 2

    (c) !(x < y)

    (d) !(x 20

    (f) x > 10 || x < 20

    (g) x ! = 0

    (h) x = = 0

    10. What is the simplest tautology?

    11. What is the simplest contradiction?

    12. Write a C++program that requests an integer value from the user. If the value is between 1 and 100

    inclusive, print OK; otherwise, do not print anything.

    13. Write a C++program that requests an integer value from the user. If the value is between 1 and 100

    inclusive, print OK; otherwise, print Out of range.

    14. Write a C++program that requests an integer value from the user. If the value is between 1 and 100

    inclusive,

    15. The following program attempts to print a message containing the the English word correspond-

    ing to a given integer input. For example, if the user enters the value 3, the program should print"You entered a three". In its current state, the program contains logic errors. Locate the

    problems and repair them so the program will work as expected.

    #include

    using namespace std;

    int main() {

    cout > value;

    // Translate number into its English word

    if (month == 1)cout

  • 8/13/2019 Cpp Conditional

    34/36

    5.11. EXERCISES 104

    cout

  • 8/13/2019 Cpp Conditional

    35/36

    5.11. EXERCISES 105

    if (input < 10) {

    if (input != 5)

    cout

  • 8/13/2019 Cpp Conditional

    36/36

    5.11. EXERCISES 106