350 likes | 510 Views
Chapter 5. If-Else statement. Control Flow. The order of executing statements in a program. What are the possibilities?. condition. condition. true. false. Statement 1. true. Statement 2. false. Statements 1. Statements 2. Statements. Statement 3. sequential. Repetition/looping.
E N D
Chapter 5 If-Else statement
Control Flow • The order of executing statements in a program. What are the possibilities? condition condition true false Statement 1 true Statement 2 false Statements 1 Statements 2 Statements Statement 3 sequential Repetition/looping Selection/branching
IF statement int num1, num2; float quotient; cin >> num1 >> num2; quotient = float(num1) / num2; // Any possible issues? // What if num2 is zero? if (num2 != 0) quotient = float(num1) / num2;
IF statement if ( expression ) statement; if ( num2 != 0 ) quotient = float(num1) / num2; • Semantics • do computation only when num2 is not zero • the statement is skipped when num2 is zero • Syntax • condition inside () • != for not equal • Style • on separate lines • indent 3 spaces • a space before and after each character How to print an error message?
IF-ELSE statement if ( expression ) statement; else statement; if (num2 != 0) quotient = float(num1) / num2; else cout << "Error: divided by zero!" << endl; What if I also want to print the quotient if possible?
if ( expression ) { statements; } else { statements; } IF-ELSE statement if (num2 != 0) { quotient = float(num1) / num2; cout << "The quotient is" << quotient << endl; } else cout << "Error: divided by zero!" << endl; • Semantics • do different things when num2 is zero or not • Syntax • braces for multiple statements (statement block) • braces are optional for single statement • Style • braces on separate lines
Statement Block if (hour <= 40) salary = hour * payRate; else salary = ( hour - 40 ) * payRate * 1.5 + 40 * payRate; cout << endl << "You have " << ( hour - 40 ) << " hours overtime." << endl; cout << "Your salary is " << salary << endl; if (hour <= 40) salary = hour * payRate; else { salary = ( hour - 40 ) * payRate * 1.5 + 40 * payRate; cout << endl << "You have " << ( hour - 40 ) << " hours overtime." << endl; } cout << "Your salary is " << salary << endl; What will be the output if hour = 30 and payRate = 10? • Indentation and blank line is a style issue. It does not make a block. • Braces are required for block of multiple statements.
Example: Find the MAX of two numbers int num1, num2, max; cin >> num1 >> num2; if ( num1 > num2 ) max = num1; else max = num2; cout << “The max value is ” << max << endl; // Another way if ( num1 >= num2 ) max = num1; else max = num2; cout << “The max value is ” << max << endl; How to find the MAX of three numbers?
Nested IF statement int num1, num2, num3, max; cin >> num1 >> num2 >> num3; if ( num1 > num2 ) if ( num1 > num3 ) max = num1; else max = num3; else if ( num2 > num3 ) max = num2; else max = num3; cout << “The max value is ” << max << endl; if ( num1 > num2 ) if ( num1 > num3 ) max = num1; else max = num3; else if ( num2 > num3 ) max = num2; else max = num3;
The Dangling else • else always look backwards for the closest if. • How about ? max = 0; if ( num1 > num2 ) if ( num1 > num3 ) max = num1; else max = num3; max = 0; if ( num1 > num2 ) if ( num1 > num3 ) max = num1; else max = num3; suppose num1 = 10, num2 = 20, num3 = 4, what is the value of max? max = 0; if ( num1 > num2 ) { if ( num1 > num3 ) max = num1; } else max = num3; Use braces to change the pairing!
Multi-way branching using If-else if-else int score; char grade; cin >> score; if (score >= 90) grade = 'A'; else if (score >= 80) grade = 'B'; else if (score >= 70) grade = 'C'; else if (score >= 60) grade = 'D'; else // NO if here! grade = 'F'; cout << “Your Grade: ” << grade; if (score >= 90) grade = ‘A’; if (score >= 80 && score < 90) grade = ‘B’; if (score >= 70 && score < 80) grade = ‘C’; if (score >= 60 && score < 70) grade = ‘D’; if (score < 60) grade = ‘F’; Which is better? What is the problem? Magic number! Can we change the order? NO!
Order in If-else if-else int score; char grade; cin >> score; if (score >= 80) grade = ‘B'; else if (score >= 90) grade = ‘A'; else if (score >= 70) grade = 'C'; else if (score >= 60) grade = 'D'; else // NO if here! grade = 'F'; cout << “Your Grade: ” << grade; You will never get an ‘A’!
Debugging in HiC • Run set breakpoint • Run run • Run step over • Run watches • Run clear all breakpoints use debugging tool to observe the control flow!
Problem: Input range check • check whether the 2 integer inputs are both in the range [10, 50]. 10 <= num1 <= 50 AND 10 <= num2 <= 50 How to express it in C++?
Conditions if ( logical expression ) statement; • The value of a logical expression is either true or false. • The bool data type: true or false int x = 6, y = 5; bool result; result = ( x == y ); result = ( x != y ); result = ( x >= 7 );
Comparison Operators == != > >= < <= No Space between!
A common mistake int num; cin >> num ; if ( num = 10 ) cout << “num equals 10” << endl; else cout << “num doesn’t equals 10” << endl; • num = 10 is an assignment statement • num == 10 is a Boolean expression • conditions can only be Boolean expressions!
Comparison Operators != !> // NO! <= // Yes! ≤ // NO! <= // Yes!
Compare characters Expression • ‘M’ < ‘R’ • 'M' < 'm' • 't' < 'm' • 'a' >= '9' • 'a' >= 9 • '0' < 9 Result true true false true true false Comparing the ASCII codes!
Compare strings • You can compare • two string variables • a string variable and a string literal • You CANNOT compare two string literals! • ==: two strings are exactly the same • >,>=,<,<=: character by character check
Compare strings string myName = “Yan”; string herName = “Margaret”; string hisName = “Kyle”; Expression • myName < herName • myName == "Yan" • hisName > "Kevin" • "Zack" > "Kevin" • herName >= "Margareta" • myName < "Zack" + hisName Result false true true ERROR false true
Logical (Boolean) operators • AND && • OR || • NOT ! • logical operators are used to connect multiple conditions into one compound condition. • the operands MUST be of bool data type! • precedence: ! > && > ||
Short-circuit evaluation • Evaluation proceeds from left to right • Evaluation stops as soon as the computer knows the value of the whole expression. • AND: if a sub-expression is false • OR: if a sub-expression is true • Example: • 10 * 2 - 5 > 0 || 5 / 0 == 1 • 10 * 2 - 5 < 0 && 5 / 0 == 1 • 10 * 2 - 5 > 0 || !5 true false ERROR
Operator Precedence ( ) !, Unary +, Unary – *, /, % +, - <, <=, >, >= ==, != && || =
De Morgans's Laws • ! ( cond1 && cond2 ) == ! cond1 || ! cond2 • ! ( cond1 || cond2 ) == ! cond1 && ! cond2
Exercise char a = 'a', b = 'b'; string myName = "Yan"; int num1 = 3, num2 = 5; Expression • !(a == b) • !(a == b || a >= 97) • ! a != b • myName.length()<num1 && myName == "Yan" • num1 >= num2 && a != b • a && b Result true false ERROR false false ERROR
Example: MAX of three numbers int num1, num2, num3, max; cin >> num1 >> num2 >> num3; if ( num1 > num2 ) if ( num1 > num3 ) max = num1; else max = num3; else if ( num2 > num3 ) max = num2; else max = num3; cout << “The max value is ” << max << endl; if ( num1 > num2 && num1 > num3 ) max = num1; else if ( num2 > num3 ) max = num2; else max = num3;
Examples: input range check • check whether the 2 integer inputs are both in the range [10, 50]. int num1, num2; cin >> num1 >> num2; if ( num1 >= 10 && num1 <= 50 && num2 >= 10 && num2 <= 50 ) cout << "Both inputs are in the range [10, 50]. " << endl; else cout << "One or more inputs are out of range. " << endl;
Examples: input range check (2) • check whether at least one of the 2 integer inputs is in the range [10, 50]. int num1, num2; cin >> num1 >> num2; if ( ( num1 >= 10 && num1 <= 50 ) || ( num2 >= 10 && num2 <= 50 ) ) cout << “One or more inputs are in the range [10, 50]. " << endl; else cout << “Both inputs are out of range. " << endl; Do we need braces?
Examples: input range check (3) • check input range: 2 integer inputs • are they both positive? • are they both negative? • are they one positive and one negative? • print out the answers to all three questions in the same order. How will you design the program? rangeCheck3.cpp
More Examples • couponCalc.cpp • compute the total charge after applying coupon code • decisionTree.cpp • get the result of a psychological test given the answers to a sequence of questions Y 1 N 2 2 3 3 3 3 4 4 4 4 4 4 4 4 A C D C A C C D B B A C D C A B after class exercise: try to combine conditions to compound conditions
Summary • IF • IF-ELSE • Nested IF-ELSE • The dangling else • Conditions • Comparison operators • Logical operators • Short-circuit evaluation • IF-ELSE IF-ELSE
After Class Exercise • write a program to find out whether the input is an odd or even number. • write a program to check if the input name belongs to a given list of names {Alex King, Alice Wonderland, John Smith}.
C++ Style Check List • Comment Block! • Constants should be before main(). • Do not indent constants! • Magic Number! (any number besides -1, 0, and 1) • Braces on separate lines! • Brace alignment! • Line should not be too long (<=74 characters). • Alignment of multi-line statements! • Indentation! • Space before and after operator! • No blank line before/after else! • No blank line before/after brace!