Download presentation
Presentation is loading. Please wait.
1
Conditionals & Boolean Expressions
Lecture 3B Conditionals & Boolean Expressions Richard Gesick Figures from Lewis, “C# Software Solutions”, Addison Wesley
2
Topics Conditional Operator Comparing Floating point numbers Objects
Strings Conditional Operator
3
Comparing Floating-Point Numbers
With IEEE 754 floating-point representation, minor rounding errors can occur in calculations We compute 11 * .1 two ways 1. Multiplying 11 * .1, the result is 1.1 2. Adding times, the result is … These values will not compare as equal using the equality operator (==) We get similar results when assigning the same value to a float variable and to a double variable, then comparing the values.
4
// Part 1: Compute 11 * .1 two ways
double d1 = .0; // add .1 to 0 eleven times d1 += .1; // 1 d1 += .1; // 2 d1 += .1; // 3 d1 += .1; // 4 d1 += .1; // 5 d1 += .1; // 6 d1 += .1; // 7 d1 += .1; // 8 d1 += .1; // 9 d1 += .1; // 10 d1 += .1; // 11 double d2 = .1 * 11; cout<< "d1 = " + d1 <<endl; cout<<"d2 = " + d2 <<endl; if ( d1 == d2 ) cout<<"d1 and d2 are equal" <<endl; else cout<< "d1 and d2 are not equal" <<endl; // Part 2: Compare float and double with same value float piF = f; double piD = ; cout<< "\npiF = " + piF <<endl; cout<<"pid = " + piD <<endl;; if ( piF == piD ) cout<< "piF and piD are equal"<<endl; cout<<"piF and piD are not equal"<<endl;
5
Output d1 = d2 = 1.1 d1 and d2 are not equal piF = pid = piF and piD are not equal
6
Solution Choose a small threshold value -- how close should the values be to be considered equal? If the difference between the two values is less than the threshold value, then we will consider the two floating-point numbers to be equal. Hint: use the fabs function to compute the difference.
7
// Part 1: Same as last example cout<< "d1 = " + d1<<endl; cout<< "d2 = " + d2 <<endl; if ( fabs( d1 - d2 ) < ) cout<< "d1 and d2 are considered equal"<<endl; else cout<< "d1 and d2 are not equal"<<endl; // Part 2: Compare float and double with same value float piF = f; double piD = ; cout<< "\npiF = " + piF<<endl; cout<< ( "piD = " + piD <<endl; if ( fabs( piF - piD ) < ) cout<< "piF and piD are considered equal"<<endl; cout<< "piF and piD are not equal"<<endl;
8
Output d1 = d2 = 1.1 d1 and d2 are considered equal piF = pid = piF and piD are considered equal
9
Comparing Floats Problematic given rounding/precision
Pick a tolerance, and if the difference between the numbers is less than this tolerance, consider the numbers equivalent if ( fabs( d1 - d2 ) < THRESHOLD) cout<< "d1 and d2 are considered equal"; else cout<< "d1 and d2 are not equal";
10
Comparing Characters What does it mean to “compare” 2 characters?
Is ‘a’ < ‘b’? Is ‘A’ > ‘z’?
11
Lexicographic Ordering
Because all characters are “encoded” using the Unicode encoding scheme, Unicode values are compared. Lexicographic ordering is not strictly alphabetical when uppercase and lowercase characters are mixed
12
Comparing Objects The equality operator ( == ) compares object references. Example: If d1 and d2 are two Date object references, then ( d1 == d2 ) evaluates to true only if d1 and d2 point to the same object, that is, the same memory location. The equality operator does not compare the data (month, day, and year) in those objects.
13
Comparing Object Data With d1 and d2 Date object references:
d1.equals(d2); Returns true if the month, day, and year of d1 equals the month, day, and year of d2. Return type Method name and argument list boolean equals( Object obj ) returns true if the data of the object obj is equal to the data in the object used to call the method 5-13 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
14
// instantiate two Date objects with identical data Date d1 = new Date( 4, 10, 2006 ); Date d2 = new Date( 4, 10, 2006 ); // assign object reference d1 to d3 Date d3 = d1; // d3 now points to d1 // instantiate another object with different data Date d4 = new Date( 12, 1, 2006 ); Do not use the equality operators (==, !=) to compare object data; instead, use the equals method.
15
Comparing Date Objects
16
// compare references using equality operator if ( d1 == d2 ) cout<< "d1 and d2 are equal\n" <<endl; else cout<< "d1 and d2 are not equal”<<endl; if ( d1 == d3 ) cout<< "d1 and d3 are equal\n" ; cout<< "d1 and d3 are not equal\n" ; // compare object data using the equals method if ( d1.equals( d2 ) ) cout<< "d1 data and d2 data are equal\n" ; cout<< "d1 data and d2 data are not equal\n" ; if ( d1.equals( d4 ) ) cout<< "d1 data and d4 data are equal" <<endl; cout<< "d1 data and d4 data are not equal" <<endl; Bad Good
17
The Conditional Operator (?:)
The conditional operator ( ?: ) contributes one of two values to an expression based on the value of the condition. Some uses are handling invalid input outputting similar messages. Syntax: ( condition ? trueExp : falseExp ) If condition is true, trueExp is used in the expression If condition is false, falseExp is used in the expression
18
Equivalent Code The following statement stores the absolute value of the integer a into the integer absValue. int absValue = ( a > 0 ? a : -a ); The equivalent statements using if/else are: int absValue; if ( a > 0 ) absValue = a; else absValue = -a;
19
The Conditional Operator
Another example: cout<< "Your change is " << count << ((count == 1) ? "Dime" : "Dimes")); If count equals 1, then "Dime" is printed If count is anything other than 1, then "Dimes" is printed
20
Nested if Statements if statements can be written as part of the true or false block of another if statement. Typically, you nest if statements when more information is required beyond the results of the first if condition The compiler matches any else clause with the most previous if statement that doesn't already have an else clause. You can use curly braces to force a desired if/else pairing.
21
Example if ( x == 2 ) if ( y == x ) cout<< "x and y equal 2" <<endl ; else cout<< "x equals 2 but y does not”<<endl ; The else clause is paired with the second if , that is: if ( y == x )
22
Another Example if ( x == 2 ) { if ( y == x ) cout<< "x and y equal 2" <<endl ; } else cout<< "x does not equal 2" <<endl ; With curly braces added, the else clause is paired with the first if , that is: if ( x == 2 )
23
The "Dangling else" A dangling else is an else clause that cannot be paired with an if condition if ( x == 2 ) if ( y == x ) cout<< "x and y equal 2" <<endl ; else // paired with ( y == x ) cout<< "y does not equal 2" <<endl ; else // paired with ( x == 2 ) cout<< "x does not equal 2" <<endl ; else // no matching if! cout<< "x and y are not equal" <<endl ; Generates the compiler error: 'else' without 'if'
24
In the absence of braces,
an else is always paired with the closest preceding if that doesn’t already have an else paired with it.
25
Bad Example has output: FAIL
float average; average = 100.0; if ( average >= 60.0 ) if ( average < 70.0 ) cout<< “Marginal PASS” <<endl ; else cout<< “FAIL” <<endl ; WHY? The compiler ignores indentation and pairs the else with the second if. 100.0 average
26
To correct the problem, use braces
float average; average = 100.0; if ( average >= 60.0 ) { if ( average < 70.0 ) cout<< “Marginal PASS” <<endl ; } else cout<<“FAIL” <<endl ; 100.0 average
27
The switch Statement Sometimes the switch statement can be used instead of an if/else/if statement for selection. Requirements: we must be comparing the value of a an integral type (e.g. char, int, etc…) expression to constants of the same types
28
The switch Statement switch (control_expression) {
case constant: statement(s); break; [ case constant: statement(s); […] ] [ default: statement(s); ] } Break statements are not required; without a break statement execution ‘runs through’ other case labels. Copyright © 2012 Pearson Education, Inc.
29
Operation of switch The expression is evaluated, then its value is compared to the case constants in order. When a match is found, the statements under that case constant are executed in sequence until either a break statement or the end of the switch block is reached. Once a match is found, if other case constants are encountered before a break statement, then the statements for these case constants are also executed.
30
Some Finer Points of switch
The break statements are not required. Their job is to terminate execution of the switch statement. The default label and its statements are optional. They are executed when the value of the expression does not match any of the case constants. The statements under the case constant are also optional, so multiple case constants can be written in sequence if identical operations will be performed for those values. You cannot perform relational checks with a switch statement
31
Example char ch; int ecount=0, vowels=0, other=0; cin.get(ch); while(!cin.eof()) { switch(ch) { case ‘e’: ecount++; case ‘a’: case ‘i’: case ‘o’: case ‘u’: vowels++; break; default: other++; } //end switch } //end while cout << ecount << ‘,’ << vowels << ‘,’ << other << endl;
32
Example: a Simple Calculator
Prompt user for two doubles (num1, num2) and a char (operation), which can be 'a' for addition or 's' for subtraction switch ( operation ) { case 'a': result = num1 + num2; break; case 's': result = num1 - num2; }
33
A Case-Insensitive Calculator
switch ( operation ) { case 'a': case 'A': result = num1 + num2; break; case 's': case 'S': result = num1 - num2; }
34
float weightInPounds = 165.8 f; char weightUnit ;
// user enters letter for desired weightUnit switch ( weightUnit ) { case ‘P’ : case ‘p’ : cout<<weightInPounds + “ pounds “<<endl ; break ; case ‘O’ : case ‘o’ : cout<< 16.0 * weightInPounds + “ ounces “<<endl ; case ‘K’ : case ‘k’ : cout<< weightInPounds / “ kilos “<<endl ; case ‘G’ : case ‘g’ : cout<< * weightInPounds + “ grams <<endl ; default : cout<<“That unit is not handled! “ <<endl ; }
35
More Examples // Determine average life expectancy of a standard light bulb. switch (watts) { case 25: life = 2500; break; case 40: case 60: life = 1000; case 75: case 100: life = 750; default: life = 0; } // end switch cout<<“Life expectancy of “ + watts + “-watt bulb: “ + watts <<endl;
36
Now It’s Your Turn Time for some group work!!!
37
Write an expression for each
age is from 18 to 21 inclusive. water is less than 1.5 and is also greater than 0.1. year is divisible by 4 speed is not greater than 55. Write a logical assignment statement for each of the following: assign a value of true to between if n is in the range of -k to +k, inclusive; otherwise assign a value of false. assign a value of true to uppercase is ch is an uppercase letter; otherwise, assign a value of false. assign a value of true to divisor if m is a divisor of n; otherwise assign a value of false.
38
Write If-Then or If-Then-Else for each
If taxCode is ‘T’, increase price by adding taxRate times price to it. If code has value 1, calculate and display taxDue as the product of income and taxrate. If A is strictly between 0 and 5, set B equal to 1/A, otherwise set B equal to A.
39
Some Answers if (taxCode == ‘T’) price = price + taxRate * price; if ( code == 1) { taxDue = income * taxRate; C.O.Wln(taxDue); }
40
Remaining Answer if ( ( A > 0 ) && (A < 5) ) B = 1/A; else B = A;
41
What’s the output? and Why?
int age; age = 20; if ( age = 16 ) { cout<<“Did you get driver’s license?” <<endl; }
42
What’s the output? and Why?
int age; age = 30; if ( age < 18 ) cout<<“Do you drive?”; cout<<“Too young to vote”;
43
What’s the output? and Why?
bool code; code = false; if ( ! code ) cout<<“Yesterday”; else cout<<“Tomorrow”;
44
What’s the output? and Why?
if (x > y) x = x ; cout<<“x bigger” ); else cout<<“x smaller” ; cout<<“y is “ + y ;
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.