Transcript Chapter 5

If-Else statement
Control Flow
 The order of executing statements in a program.
What are the possibilities?
Statement 1
Statement 2
true
condition
false
condition
true
Statements 1
Statements 2
Statements
Statement 3
sequential
Selection/branching
Repetition/looping
false
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-ELSE statement
if ( expression )
{
statements;
}
else
{
statements;
}
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
salary =
= hour
hour *
* payRate;
payRate;
else
else
{
salary
salary =
= (
( hour
hour - 40
40 )
) *
* payRate
payRate
cout
cout <<
<< endl
endl <<
<< "You
"You have
have "
" <<
<< (
(
cout << "Your salary is " << salary
}
cout << "Your salary is " << salary
*
* 1.5
1.5 +
+ 40
40 *
* payRate;
payRate;
hour
hour - 40
40 )
) <<
<< "
" hours
hours overtime."
overtime." <<
<< endl;
endl;
<< endl;
<< 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;
How to find the MAX of three numbers?
cout << “The max value is ” << max << endl;
8
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;
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;
The Dangling else
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?
 else always look backwards for the closest if.
 How about
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';
Which is better?
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’;
cout << “Your Grade: ” << grade;
What is the problem?
Can we change the order?
Magic number!
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!
16
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!
18
Compare characters
Expression
‘M’ < ‘R’
'M' < 'm'
't' < 'm'
'a' >= '9'
'a' >= 9
'0' < 9
Comparing the ASCII codes!
Result
true
true
false
true
true
false
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: ! > && > ||
Truth Table
cond1
cond2
cond1 && cond2
cond1 || cond2
! cond1
T
T
T
T
F
F
F
F
F
T
T
F
F
T
F
F
T
F
T
T
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;
if ( num1 > num2 && num1 > num3 )
max = num1;
else if ( num2 > num3 )
max = num2;
else
max = num3;
cout << “The max value is ” << max << endl;
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;
Do we need braces?
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;
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
1
Y
N
2
2
3
4
A
3
4
C
D
4
C
3
4
4
3
4
4
A
C
C D B
B A C D
C
A
after class exercise:
try to combine conditions to compound conditions
4
B
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!