Boolean Expr Conditionals L7

advertisement
Lecture 7
Conditionals &
Boolean Expressions
Richard Gesick
Figures from Lewis, “C# Software Solutions”, Addison Wesley
CSE 1301
Topics
•
•
•
•
•
•
CSE 1301
Flow of Control
Flow Diagram
bool definition
Relational Operators
if statements
else statements
A Flow Diagram
Did you break
anything?
Yes
Blame it on
someone else
Yes
No
Are you lying?
Yes
Have your
parents asked
about it?
No
Are you passing
your classes?
Yes
CSE 1301
No
No
Ask for $$
Lay low and
keep hidden
The Boolean
• A bool is a something that resolves to true or
false
• You can get Boolean values several different
ways
– Simple
– Complex
• These bools will be used (later) to make
decisions
CSE 1301
Relational Operators
(for primitive data types)
• Relational Operators
> greater than
< less than
== equals
!= not equal
>= greater than or equal
<= less than or equal
• Notice that all of these return us a true or false
value
CSE 1301
CSE 1301
Relational Operator Examples
• Literal Example
5 > 3
// true
6 != 6
// false
true == (4 <= 2) // false
‘c’ != ‘b’
// true
!false
// true
• Variable Example
int num1 = 5;
short num2 = 7;
bool result = num2 > num1;
//Note: result is now true
CSE 1301
&& and || Operators
• These operators check for multiple conditions
• && (AND) needs both the left and the right to be
true in order to return true
• || (OR) needs either one (or both) to be true to
return true
• Examples:
(
(
(
(
CSE 1301
(6
(6
(6
(6
>
>
>
>
5)
5)
5)
6)
&&
&&
||
||
(
(
(
(
‘c’
7 <
‘c’
‘c’
==
9)
==
==
‘b’) ) // false
)
// true
‘b’) ) // true
‘b’) ) // false
CSE 1301
CSE 1301
CSE 1301
int x, y ;
x = 4;
y = 6;
EXPRESSION
VALUE
x<y
x+2<y
true
x != y
false
x + 3 >= y
true
y == x
true
y == x+2
false
true
CSE 1301
CSE 1301
EXPRESSION
VALUE
7 == 7
true
13 < 100
true
-17.32 != -17.32
false
-3.0 == 0.0
false
13 <= 100
true
-18 < -15
true
4.2 > 3.7
true
13 <= 13
true
0.012 > 0.013
false
Suppose we have three ints x, y, and z, and we want
to test if x is less than both y and z. A common
error is to express the condition this incorrect
way:
x < y && z
// compiler error
Each operand of a logical operator must be a
boolean expression. This is correct:
x < y
CSE 1301
&&
x < z
Short-Circuit Evaluation
• For any logical operator, the operands are
evaluated left to right
• If the result of the logical operation can be
determined after evaluating the first
operand, the second operand is not
evaluated.
– If the first operand of an || is true, the result will
be true
– If the first operand of an && is false, the result
will be false
CSE 1301
int age = 75; bool test;
test = ( age > 18 && age < 65 );
C.O.Wln( age + " > 18 && " + age + " < 65 is " + test );
// short circuitry with AND
test = ( age < 65 && age > 18 );
C.O.Wln( age + " < 65 && " + age + " > 18 is " + test );
// short circuitry with OR
test = ( age > 65 || age < 18 );
C.O.Wln( age + " > 65 || " + age + " < 18 is " + test );
// AND has higher precedence than OR
test = ( age > 65 || age < 18 && false );
C.O.Wln( age + " > 65 || " + age + " < 18 " + " && false is " + test );
// use of parentheses to force order of execution
test = ( ( age > 65 || age < 18 ) && false );
C.O.Wln( "( " + age + " > 65 || " + age + " < 18 ) " + "&& false is " + test );
CSE 1301
What is the value?
float x = 3.0, y = 4.0, z = 2.0;
EXPRESSION
1. (x > z) && (y > z)
VALUE
true
2. (x + y / z) <= 3.5
false
3. (z > x) || (z > y)
false
4. !(y == z)
true
5. (x == 1.0) || (x == 3.0)
true
6. (z < x) && (x < y)
true
7. (x <= z) || (x >= y)
false
8. !(x > y) || y + z >= x – z
true
9. !((x > y) || ((y + z) >= (x – z)))
false
CSE 1301
Now Let’s Do Something!
• Using the if statement, we can decide whether
or not to execute some code
• Has format:
if (<boolean value>) {
// all the code that’s in here will only execute
// if and only if the boolean above is true
}
CSE 1301
“if” Example
class Skeleton {
public static void Main ( ) {
int start = 5;
int end = 19;
if (start < end ) {
Console.WriteLine ( “A” );
} // end if
Console.WriteLine ( “B” );
} // end Main
} // end class
CSE 1301
“if” Example
class Skeleton {
public static void Main ( ) {
int start = 5;
int end = 19;
if (start < end ) {
Console.WriteLine ( “A” );
} // end if
Console.WriteLine ( “B” );
} // end Main
} // end class
CSE 1301
A
B
“if” Example
class Skeleton {
public static void Main ( ) {
int start = 5;
int end = 19;
if (start > end ) {
Console.WriteLine ( “A” );
} // end if
Console.WriteLine ( “B” );
} // end Main
} // end class
CSE 1301
“if” Example
class Skeleton {
public static void Main ( ) {
int start = 5;
int end = 19;
if (start > end ) {
Console.WriteLine ( “A” );
} // end if
Console.WriteLine ( “B” );
} // end Main
} // end class
CSE 1301
B
The “else” statement
• if has a counterpart – the else statement
• If the if clause didn’t execute, the else clause will!
• Has format:
if (<boolean value>) {
// statements that execute if the boolean is true
}
else {
// statements that execute if the boolean is false
}
• Notice only one set of statements executes, no matter what
CSE 1301
“else” Example
class Skeleton {
public static void Main ( ) {
int start = 5;
int end = 19;
if (start > end ) {
Console.WriteLine ( “A” );
} // end if
else {
Console.WriteLine ( “B” );
} // end else
} // end Main
} // end class
CSE 1301
“else” Example
class Skeleton {
public static void Main ( ) {
int start = 5;
int end = 19;
if (start > end ) {
Console.WriteLine ( “A” );
} // end if
else {
Console.WriteLine ( “B” );
} // end else
} // end Main
} // end class
CSE 1301
B
“else” Example
class Skeleton {
public static void Main ( ) {
int start = 5;
int end = 19;
if (start < end ) {
Console.WriteLine ( “A” );
} // end if
else {
Console.WriteLine ( “B” );
} // end else
} // end Main
} // end class
CSE 1301
“else” Example
class Skeleton {
public static void Main ( ) {
int start = 5;
int end = 19;
if (start < end ) {
Console.WriteLine ( “A” );
} // end if
else {
Console.WriteLine ( “B” );
} // end else
} // end Main
} // end class
CSE 1301
A
else if’s
• Selecting one from many
• As soon as one is true, the rest are not considered
• Has format:
if (<boolean value>) {
// statements that execute
}
else if (<boolean value>){
// statements that execute
}
else if (<boolean value>){
// statements that execute
}
else {
// something that executes
}
CSE 1301
if the above boolean is true
if the above boolean is true
if the above boolean is true
if nothing matched above
Combining into “else if”s
(Selecting one from many)
class Skeleton {
public static void Main ( )
int start = 5; int middle
if (start < middle ) {
Console.WriteLine ( “A”
} // end if
else if (start < end) {
Console.WriteLine ( “B”
} // end else if
} // end Main
} // end class
CSE 1301
{
= 8; int end = 19;
);
);
Combining into “else if”s
(Selecting one from many)
class Skeleton {
public static void Main ( )
int start = 5; int middle
if (start < middle ) {
Console.WriteLine ( “A”
} // end if
else if (start < end) {
Console.WriteLine ( “B”
} // end else if
} // end Main
} // end class
CSE 1301
{
= 8; int end = 19;
);
);
A
else catch-all Example
class Skeleton {
public static void Main ( ) {
int start = 5; int middle = 8; int end = 19;
if (start > middle ) {
Console.WriteLine ("A");
} // end if
else if (start > end) {
Console.WriteLine ("B");
} // end else if
else {
Console.WriteLine ("C");
} // end else
} // end Main
} // end class
CSE 1301
else catch-all Example
class Skeleton {
public static void Main ( ) {
int start = 5; int middle = 8; int end = 19;
if (start > middle ) {
Console.WriteLine ("A");
} // end if
else if (start > end) {
Console.WriteLine ("B");
} // end else if
else {
Console.WriteLine ("C");
} // end else
} // end Main
} // end class
C
CSE 1301
Conclusion
• Boolean values can be generated several ways
• Use the if statement to decide which path to
take
• Use the else to take the alternate path
• The else-if statements allow for selecting one
from many
CSE 1301
Indentation
• The statement controlled by the if statement is
indented to indicate that relationship
• The use of a consistent indentation style makes a
program easier to read and understand
• Although it makes no difference to the compiler, proper
indentation is crucial
"Always code as if the person who ends up
maintaining your code will be a violent
psychopath who knows where you live."
-- Martin Golding
CSE 1301
Indentation 2
• Remember that indentation is for the human
reader, and is ignored by the computer
if (total > MAX)
C.O.Wln ("Error!!");
errorCount++;
Despite what is implied by the indentation, the
increment will occur whether the condition is
true or not
CSE 1301
Do not put a semicolon after the condition.
Doing so indicates that the true block is
empty and can cause a logic error at run
time.
CSE 1301
What went wrong?
This is only supposed to display “HEALTHY AIR” if the air
quality index is between 50 and 80.
But when you tested it, it displayed “HEALTHY AIR” when
the index was 35.
int AQIndex ;
AQIndex = 35 ;
if (50 < AQIndex < 80)
C.O.Wln(“HEALTHY AIR“) ;
CSE 1301
Analysis of Situation
AQIndex = 35;
According to the precedence chart, the expression
(50 < AQIndex < 80)
means
(50 < AQIndex) < 80
because < is Left Associative
(50 < AQIndex) is false
(false < 80) is ???
CSE 1301
Corrected Version
int AQIndex ;
AQIndex = 35 ;
if ( (50 < AQIndex) && (AQIndex < 80) )
C.O.Wln(“HEALTHY AIR“) ;
CSE 1301
What happens if you omit braces?
if ( (carDoors == 4 ) && (driverAge > 24) )
premium = 650.00 ;
C.O.Wln(“ LOW RISK “);
else
premium = 1200.00 ;
C.O.Wln(“ HIGH RISK ”);
monthlyPayment = premium / 12.0 + 5.00;
COMPILER ERROR OCCURS. The “if clause” is the
single statement following the if.
CSE 1301
Braces can only be omitted when
each clause is a single statement
if ( lastInitial <= ‘K’ )
volume = 1;
else
volume = 2;
C.O.Wln(“Look it up in volume # “
+ volume + “ of NYC phone book”;
CSE 1301
If-Then-Else for a mail order
Assign value .25 to discountRate and assign
value 10.00 to shipCost if purchase is over
100.00
Otherwise, assign value .15 to discountRate
and assign value 5.00 to shipCost
Either way, calculate totalBill
CSE 1301
These braces cannot be omitted
if ( purchase > 100.00 )
{
discountRate = .25 ;
shipCost = 10.00 ;
}
else
{
discountRate = .15 ;
shipCost = 5.00 ;
}
totalBill = purchase * (1.0 - discountRate) + shipCost ;
CSE 1301
Download