Bools & Ifs
Control Structures Normal execution is sequential Control structures Selection (branching): making a choice Repetition (iteration): looping
Relational Operators Relational operators : Binary operators – compare two values Evaluate to true or false
Examples Samples: Notes: 8 < 15 evaluates to true 6 != 6 evaluates to false 2.5 > 5.8 evaluates to false 5.9 <= 7.5 evaluates to true Notes: ! means "not" < or > always before = (no => operator)
True/False C++ bool type Two values: true (1) & false (0) bool enrolled = true; //same as = 1 cout << enrolled;
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: bool enrolled = 3.2; //true bool enrolled = 23; //true bool enrolled = -4; //true bool enrolled = 2 - 2; //false
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)
Relational Operators Conditional statements: only executed if certain conditions are met if( score is greater than or equal to 90 ) print "Grade is A"
One-Way Selection One-way selection syntax: Expression true execute statement Expression false skip statement
If Example Indent statement! Example: int grade; //read grade if(grade < 60) cout << "F"; Indent statement!
Evil Error 1 if(grade < 60); cout << "F"; Always prints F If grade < 60 do empty statement (;) No matter what, print F
Evil Error 2 if (x = 5) cout << "Is 5" << endl;
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))
Evil Error 2 Yoda style (constant first) prevents this error: if (5 == x) cout << "Is 5" << endl;
Two-Way Selection Two-way selection syntax: Expression true execute statement1 Expression false execute statement2 Only 1 of the 2 statements executes
If Example Example: int grade; //read grade if(grade < 60) cout << "F"; else cout << "Pass";
Compound (Block of) Statements Compound statement (block of statements): Surrounded by { } Acts as one statement
If Example Indent statements! Example: int grade; double credits; //read grade if(grade < 60) cout << "F"; else { credits += 4; cout << "Pass"; } Indent statements!
Bad Block Example: Need { } to group instructions: if(grade < 60) credits += 0; cout << "F"; //always executes Need { } to group instructions: if(grade < 60) { credits += 0; cout << "F"; }
Block Guides When in doubt, use { } Same line { prevents accidental ; if(grade < 60) { cout << "F"; //this is fine } Same line { prevents accidental ; if(grade < 60); { cout << "F"; //always happens }