1 / 29

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.

amcknight
Download Presentation

Lesson 6 Boolean Data Type and IF Statements

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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.

  2. Example • if (work_hour > 40) { • 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. true work_hour > 40 overtime_hour = work_hour - 40; overtime_salary = overtime_hour * 45.0; false

  3. true <bool-expr> false <statement> • 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 conditionof an IF statement. • The <statement> here is called the then-partof the IF statement. It will only be executed when the condition is true.

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

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

  6. 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.

  7. 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.

  8. 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 T || F T ! F T F F F F F T T F T F T T T T

  9. bool expressions, e.g., d > 0 d > 0.0 && i >= 10 pretty && slender 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.)

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

  11. 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)

  12. 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++.

  13. 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.

  14. 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; BooleanIO You are old. (0 for false and 1 for true): 0 old is 0 old is false

  15. 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) ;

  16. a >= 0.0 true false sign = 1.0 sign = -1.0 • 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.

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

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

  19. 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 (n > 3) ok = true; //silly • else ok = false; if ( ok ) a = 1000; //better ok = (n > 3); //better

  20. Nested IF statements • IF statements may appear in the 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

  21. An else always matcheswith 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 1 a 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 1 a 0 1

  22. b -1 0 -1 a 0 • 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;

  23. 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;

  24. To compute grade and honors from score according to • grade honors • score  90 A true • 80  score < 90 B true • 70  score < 80 C false • 60  score < 70 D false • score < 60 F 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’;

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

  26. 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> //This part is optional • 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.

  27. 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; • }

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

  29. Reading Assignment • Chapter 7 of the Text, P. 381 - 413

More Related