Lesson 6 Boolean Data Type and IF Statements

Lesson 6 Boolean Data Type and IF Statements Ø In daily life, we often do (or do not do) something, depending on a condition. Eg, ØIf it rains, bring an umbrella. ØIf typhoon signal No. 8 is hoisted, go home. ØIf she knows C++, date her. Ø We can attach a condition to a statement. If the condition is true, execute the statement. Otherwise, skip to next statement. 1

Ø Example if (work_hour > 40) { overtime_hour = work_hour - 40; overtime_salary = overtime_hour * 45. 0; } true work_hour > 40 false overtime_hour = work_hour - 40; overtime_salary = overtime_hour * 45. 0; The assignment statements ( then-part ) will only be executed when the condition ( work_hour > 40) is true. 2

Ø Syntax of a simple IF statement if (<bool-expr>) <statement> Ø <bool-expr> stands for boolean expression whose value is either true or false. It is called the condition of an IF statement. Ø The <statement> here is called then-part of the IF statement. It will only be executed when the condition is true. <bool-expr> false true <statement> 3

Ø A compound statement consists of zero or more statements wrapped in a pair of braces, ‘{’ and ‘}’. Eg, { } t = a; a = b; b = t; <bool-expr> false true <comp-stat> Ø The then-part of an If statement can be a single statement or a compound statement 4

Ø Examples of statements a = b + c; cout << "Radius = " << r; cin >> age; print_board(); if (b == c) cout << “O. K. ”; //Assignment //Output //Invocation of a function //Simple IF statement if (b < c) //IF statement with a comp-stat in then-part { a = 0; cout << c; } if (age >= 65) //Nested IF statements: an IF statement { a = b + c; //appears in then-part of an outer IF if (weight > 80) cout << “A fat senior”; 5 }

Ø A boolean value (true or false) is resulted in the comparison of numbers or characters using relational operators: ==, !=, <, <=, >, >=. Ø Similar to arithmetic operators, relational operators are overloaded. Eg, == may mean comparing two integers or comparing two doubles, depending on the types of the operands. Ø Let i be an int variable and d be a double variable. E. g. , i<1 //pure mode, int comparison fabs(d) < 1. 0 //pure mode, double comparison i >= d //mixed mode, the value of i is converted //to double before the comparison. 6

George Boole, English, 1815 -1864 Mathematician and logistician who developed ways of expressing logical processes using algebraic symbols, creating a branch of mathematics known as symbolic logic. 7

Ø Same as int and double, bool is a primitive data type for denoting boolean values Ø Declaration of bool variables bool slim, rich; bool pretty = true; //pretty is initialized to true Ø bool constants: true , false. Ø Logical operators: && (AND) , || (OR) , ! (NOT) A logical operator applies on bool values. The result is of type bool. && F F F T F T || F F F T T T ! F T T F 8

Ø bool expressions, e. g. , d>0 d > 0. 0 && i >= 10 pretty && slender && ( (age < 28) || wealthy) Ø We can compare bool values with == or !=. Eg, if (thin == pretty) fast(); Ø Although allowed, it does not make much sense to compare bool values with <, <=, >, >=. (The result of such a comparison is machine dependent. ) 9

Ø Operator Precedence Highest ++, -- Priority ! Unary +, -, Casting (int), (double) *, /, % +, - Relational <, <=, >, >=, Relational = =, != AND && OR || Lowest Assignment = 10

Ø Association rules Most operators of same precedence are evaluated from left to right Examples a-b*c means a - (b*c) (int) d / 2. 0 means ((int) d) / 2. 0 a < b != c <= d+1 means (a<b) != (c<=(d+1)) slim == a > b - 2 / d means slim == (a > (b - (2 / d))) u || v && slim || !x && y means (u || (v && slim)) || ((!x) && y) 11

Ø bool assignments, <bool_var> = <bool_expr>; pretty = false; slender = (weight < 105) && (height >=163); Ø Avoid writing complicated expressions. Ø Use extra parentheses to clarify the execution order in a complicated expressions. Ø Sort the operators, { * , != , || , <=, && , (int) , ! }, in descending order of execution priority in C++. 12

Ø In C++, a bool value is represented by an int value internally. false is 0. true is any value different from 0, usually 1. Ø Similar to int and double, bool values can be output using cout. However, only the int value that represents true (or false) is printed, instead of the word “true” (or “false”). Ø We may use cin to read a value for a bool variable. The value provided shall be an int value. 0 for false and 1 for true. 13

Ø I/O of bool values. . bool old; cout << "You are old. (0 for false and 1 for true): "; cin >> old; cout << "old is " << old << endl; //A better way cout << "old is "; if (old) cout << "true"; else cout << "false"; cout << endl; Boolean. IO You are old. (0 for false and 1 for true): 0 old is false 14

boolean handsome, wealthy, tender, caring, old, pregnant; double asset; handsome = false; wealthy = false; tender = true; cout << (handsome || wealthy && tender) ; handsome = true; wealthy = false; tender = false; cout << (handsome || wealthy && tender) ; handsome = false; asset = -100000. 0; caring = true; cout << (handsome || asset > 1000000. && caring) ; old = true; asset = -100000. 0; pregnant = true; cout << (old && asset == 0. && pregnant) ; 15

Ø IF-ELSE statement if (a >= 0. 0) sign = 1. 0; else sign = -1. 0; An if-else statement consists of a condition, a then-part and an else-part. The else-part is executed when the condition is false. a >= 0. 0 true sign = 1. 0 false sign = -1. 0 16

Ø Similar to a simple IF statement, then-part and the else-part can be a compound statement. E. g. , if ( (n <= 3) && ok) { cout << n; x = 1; } else { n = n - 1; cout << endl; } //then-part //else-part 17

Are there any syntax errors in the following? if (false) { } cout << “Young is terrific. " ; if (false) ; else cout << “Old is wonderful. " ; 18

Ø Adequate alignments and indentations significantly improve the clarity of a program. Eg, the following is difficult to understand. if ( (n <= 3) && ok) { cout << n; x = 1; } else { n = n - 1; cout << endl; } Ø Avoid writing silly IF statements, e. g. , if (ok == true) a = 1000; //silly if ( ok ) a = 1000; //better if (n > 3) ok = true; else ok = false; //silly ok = (n > 3); //better 19

Ø Nested IF statements may appear in then-part or else-part of an outer IF statement recursively. Confusions may occur. Ø Consider if (a > 0) if (b > 0) c = 1; else c = 2; Does the else associate with the first IF or the second IF? Let c originally equal to 0. What are the values of c for various a and b after the execution? b 0 1 0 a 1 20

Ø An else always matches with the nearest preceding unmatched IF. Thus, the above IF statement really means if (a > 0) { //This pair of braces is optional. if (b > 0) c = 1; else c = 2; } b 0 a 1 0 1 Ø In case that the else belongs to the outer IF, write if (a > 0) { //This pair of braces is required. if (b > 0) c = 1; } else c = 2; b 0 a 1 0 1 21

Ø Give the values of c after the execution of the following code for various combinations of a’s and b’s values specified in the table. c = 1; if (a >= 0) if (b >= 0) c = 2; else c = 3; b -1 0 -1 a 0 22

Ø Write an IF-statement that checks the value of an int variable, n. It prints the word even if n is an even number. Otherwise, it prints odd. Ø The output of the following program is ___. int a = 0, b = 0, c = 0; if (a > 0) if (b > 0) c = 1; else c = 2; cout << c; 23

Ø To compute grade and honors from score according to score 90 80 score < 90 70 score < 80 60 score < 70 score < 60 grade A B C D F honors true false int score; char grade; bool honors; cin >> score; honors = (score >= 80); if (score >= 90) grade = ‘A’; else if (score >= 80) grade = ‘B’; else if (score >= 70) grade = ‘C’; else if (score >= 60) grade = ‘D’; else grade = ‘F’; 24

Ø switch statements switch (score / 10) { case 9: grade = break; case 8: grade = break; case 7: grade = break; case 6: grade = break; default: grade = break; } //Assume that score’s value is betw 0 & 99. // score/10 is either 9, 8, 7, 6, 5, 4, 3, 2, 1 or 0 ‘A’; score/10 ==9 grade=‘A’ score/10 ==8 grade=‘B’ score/10 ==7 grade=‘C’ score/10 ==6 grade=‘D’ ‘B’; ‘C’; ‘D’; ‘F’; grade=‘F’ 25

Ø The syntax of a switch statement switch (<expr>) { case <const-1>: <statements> break; case <const-2>: <statements> break; . . . case <const-n> <statements> break; default: <statements> break; } First evaluate <expr>. If the result equals <const-1>, execute the statements followed. Jump out of the switch block when the break statement is executed. Otherwise, try <const-2>, <const-3>, …, <const-n> one by one. If none of the cases is triggered, execute the statements after default. // //This part is optional // 26

Ø The <expr> shall be of type int or char. Ø If the break statement in the end of each case group is missing, execution continues into the succeeding group. Ø The default group is optional. Ø Another example, switch (grade) { case ‘A’ : cout << “Excellent”; break; case ‘B’ : cout << “Very Good”; break; case ‘C’ : cout << “Good”; break; case ‘D’ : cout << “Fair” ; break; case ‘F’ : cout << “Poor” ; break; default: cout << “Wrong grade”; break; } 27

Ø Re-write the following using IF statements. switch (a) { case 1: break; case 2: b = a; break; default: b = -1; } 28

Reading Assignment Ø Chapter 7 of the Text, P. 381 - 413 29
- Slides: 29