Presentation is loading. Please wait.

Presentation is loading. Please wait.

Bools & Ifs.

Similar presentations


Presentation on theme: "Bools & Ifs."— Presentation transcript:

1 Bools & Ifs

2 True/False C++ bool type Two values: true & false

3 True/False C++ bool type Two values: true & false Printed as 1 and 0

4 True/False C has no bool C++ converts numbers to bools in same way:
Uses integers : 0 = false, all others = true C++ converts numbers to bools in same way:

5 Relational Operators Relational operators :
Binary operators – compare two values Evaluate to true or false

6 Relational Evaluation
Can store result of relational operator: bool result = 5 < 9; cout << result; Outputs 1 (true) bool result = 5 == 9; cout << result; Outputs 0 (false)

7 Control Structures Normal execution is sequential Control structures
Selection (branching): making a choice Repetition (iteration): looping

8 Conditional If syntax: if( expression ) statement;

9 If Example Indent statement!
int grade; //read grade if(grade < 60) cout << "F"; Indent statement!

10 Evil Error 1 if(grade < 60); cout << "F";

11 Evil Error 1 if(grade < 60); cout << "F"; Always prints F
If grade < 60 do empty statement (;) No matter what, print F

12 Evil Error 2 if (x = 5) cout << "Is 5" << endl;

13 Evil Error 2 if (x = 5) cout << "Is 5" << endl;
Changes x to 5 Value of assignment is 5  true Linux Hack Attempt: if ((options == (__WCLONE|__WALL)) && (current->uid = 0))

14 Evil Error 2 Yoda style (constant first) prevents this error: if (5 == x) cout << "Is 5" << endl;

15 Two-Way Selection Two-way selection syntax:
if( expression ) statement1; else statement2; Exactly one statement executes

16 Example int grade; //read grade if(grade < 60) cout << "F"; else cout << "Pass";

17 Evil Error 3 if(grade >= 60); cout << "Pass"; else cout << "You shall not pass"; cout << "try again";

18 Evil Error 3 Always prints "try again" if(grade >= 60);
cout << "Pass"; else cout << "You shall not pass"; cout << "try again"; Always prints "try again" Else only applies to next statement!

19 Compound (Block of) Statements
Compound statement (block of statements): Surrounded by { } Acts as one statement

20 If Example Indent statements! Else with multistatement block
int grade; double credits; //read grade if(grade < 60) cout << "F"; else { credits += 4; cout << "Pass"; } Indent statements!

21 Example Use { } with if/else to group statements:
if(grade < 60) creditsEarned = 0; cout << "F"; //always executes Need { } to group instructions: if(grade < 60) { credits += 0; cout << "F"; }

22 Block Guides Never hurts to put { } around if/else body:
if(grade < 60) { cout << "F"; //this is fine }


Download ppt "Bools & Ifs."

Similar presentations


Ads by Google