Professional Documents
Culture Documents
CS2311 Lec03 Condition
CS2311 Lec03 Condition
CS2311 Lec03 Condition
2
Exercises: Data Types
Complete the following steps, inside the main function
1. Declare a variable of type char, called "vChar1", and initialize it to store the
character A.
2. Declare another char variable, called "vChar2", and initialize it to store the character
0 (not the number 0).
3. Output the values of vChar1 and vChar2 using cout.
4. Increment the value of vChar1 by 1 and save the value still in vChar1.
5. Output the value of vChar1 now.
What is the output for step 3 and 5? Can you explain why the output looks like this?
3
Exercises: Data Types
5
Exercises: I/O
Expected Output:
For start time, please enter the following information:
Enter the start day (a number in range from 1 to 31): 1
Enter the start hour (a number in range from 0 to 23): 0
Enter the start minute (a number in range from 0 to 59): 0
Enter the start second (a number in range from 0 to 59): 0
For end time, please also enter the similar information:
Enter the end day (a number in range from 1 to 31): 2
Enter the end hour (a number in range from 0 to 23): 3
Enter the end minute (a number in range from 0 to 59): 4
Enter the end second (a number in range from 0 to 59): 5
• Switch statement
7
Logical Data Type: Bool
9. long double
• Takes only two values: true and false 8. double
• Numeric values are 1 (true) and 0 (false) 7. float
8
Logical Data Type: Bool
9. long double
• when a higher-ranked type is casted to bool, only 0 is
8. double
converted to false, all non-zero values are converted
7. float
to true
a Ox la is a Hexadecimal Number
bool x = 0, y = 3.14, z = 0x1100; 11 boo lx o 6. long long
bool //y 0 13114
cout << x << “ ” << y << “ ” << z << endl; 5. long
I
boo 2 0 1100
4. int
3. short
• different with demoted conversion of numeric types,
which is direct cut
2. char
short a = 0x11110011;
1. bool
cout << a; // 3
9
Comparative Operators
• Binary operators which accept two operands and compare them
10
Logical Operators: AND (&&) and OR (||)
• Used for combining two logical values and create x y x&&y
a new logical values true true true
• Logical AND (&&) true false false
• return true if both operands are true false true false
• otherwise return false false false false
• example: 18 < age && age < 60
x y x||y
• Logical OR (||) true true true
• return false if both operands are false true false true
• otherwise return true false true true
false false false
x !x
Logical Operator: NOT (!) true false
• Logical-NOT (!) is a unary operator that takes false true
one operand and inverts its value
Original Equivalent
Expression Expression
• ! (A && B) is the same as (!A) || (!B) !(x<y) x>=y
• ! (A || B) is the same as (!A) && (!B) !(x>y) x<=y
!(x!=y) x==y
!(x<=y) x>y
!(x>=y) x<y
!(x==y) x!=y
12
Logical Expressions
• Expressions that take comparative or logical operators
• x == 3
• y == x
• x >= 2
• x != y
• The value of a logical expression is bool, i.e., can be true or false only
13
DO NOT MIX: x=y VS x==y
int x = 0, y = 4, z = 8;
cout << x=y << endl; // This line will print 4, because:
// x=y is an assignment expression!
// It copies the value of y to x.
// The value of an assignment expression equals to
// the value of the right operand,
// i.e., 4 in this example
cout << y==z << endl; // This line will print 0 because:
// y==z is a logical expression!
// and y doesn’t equal to z
14
DO NOT MIX: a<x<b VS a<x && x<b
double a = 0.5;
True True True print 1
cout << 0<a && a<1 << endl; // will print 1, because:
// the value of 0 < a is true (0<0.5)
// the value of a < 1 is true (0.5<1)
// the operator && combines the two values
// and creates a new value
// which is true (printed as 1) in this example
Truest False print o
cout << 0<a<1 << endl; // will print 0, because:
// 0 < a < 1 is equivalent to (0 < a) < 1
// in this example, it’s equivalent to (0<0.5) < 1
// i.e., true < 1, which equals to false
// and printed as 0
Short Circuit Evaluation
• Evaluation of logical expressions containing && and || stops as soon as
the outcome true or false is known
16
Short Circuit Evaluation
É
• Example I:
For any 11 statement any
int x = 0, y = print
2;
I directly
False
True || y==1);
bool a = (x==0 print
// we know that a must equal to true after
// evaluating x==0 (which is true), it doesn’t
// matter if y equals to 1 or not
False False
bool b = (x!=0 && y==2); // we know that b must equals to false after
// evaluating x!=0 (which is false), it doesn’t
// matter if y equals to 2 or not
For statement
if statement false
any
print 0 directly 17
O
4 29
Short Circuit Evaluation
• Example II:
III
int a = 0, b = 0;
bool x = (a==0 || b=1);
cout << b << endl;
cout << x << endl;
// we know that x must equal to true after
// evaluating a==0 (which is true)
// in this case b=1 is not evaluated
// therefore, the value of b is still 0
18
Short Circuit Evaluation
• Example III:
int a = 0, b = 0; a 0 b I
bool x = (a!=0 && b=1);false skipped
cout << b << endl; // what value will be printed and why?
cout << x << endl;
19
Quick Summary
• Comparative operators
less than < not less than <=
greater than > not greater than >=
equal to == not equal to !=
• Logical operators
logical AND && logical OR && watch out to SHORT CIRCUIT!
logical NOT !
20
Today’s Outline
• Logical data type, operators and expressions
• If statement
• Simple
• Nested
• Switch statement
21
I red
Conditional Statements 2 green
• In decision making process, logical value can be used to determine the
actions to take if I then the car
lighten stop
if light 2 11 then the car can go
• Examples: if AC2 canteen is too crowded, then go to AC1/AC3 for lunch
22
Remark for simple if
if Statement: Basic Syntax statement it is bett
to add to allowy
simple if statement to check to logic flo
statement 0; eastier
if (logical expression) 11 if logical statement 0
statement 1; expression
statement 2; true statement I will be
excited andif (logical true
• statement 1 will be executed if then execute
expression)
logical expression is evaluated tostatement2 check if
true, for example false
if logical the statement 1
cin >> x; expression condition is
if (x < 0) false then true or not
x = -x; will skip
statement 2
if (i == 3)
a ++; The semi-colons belong
to the statements, not
else to the if else
a --;
25
if Statement: Some Syntax Notes
• Watch out to empty statements! if logic Expression
int x=5; int x=5;
if logicexpressio
false
if (x!=5); if youadd after itif (x!=5)
M
x=3; statementno matter the x=3; Afalse
condition is true true Skip
excute
x 3
cout << x; cout << x; x 3
or false no selection
/*output is 3*/action will be /*output is 5*/
taken
• An empty statement can be specified by a semi-colon ';'. Empty statement specifies that no
action should be performed.
• For program on the right, x=3 statement will NOT be executed if x equals to 5.
• For the program on the left, x=3 statement will be always executed.
26
if Statement: Inline Ternary
2 way condition
• Also known as inline if-then-else constructs
• Syntax if A
• expr1 ? expr2 : expr3 ; if express D Action A
elsepction B
• Semantics int a, b, c;
express
• expr1 is evaluated as the condition cin >> a;
• if the value of expr1 is non-zero/true, then cin >> b;
execute expr2;
else a>=b ? c=a : c=b;
• else execute expr3 cout << c;
express 3
27
if Statement: Inline Ternary
• The value of the whole inline ternary expression equals to the expression
evaluated at the end
• For example
int a, b, c;
cin >> a;
a b c
30
Compound if more than one statement inside
the if statement selection
• Group multiple statements into
one block using {} to be executedbodycompound statement using a pair of braces {}
We may group multiple statements to form a
• If the input mark is greater than or equal to 34, the yellow statement is
executed.
32
Compound if: Example 2
int mark;
cout << "What is your exam mark?\n";
cin >> mark;
if (mark >= 30) {
cout << "You passed the exam of CS2311!\n";
cout << “Congratulations!\n”;
} else
cout << “You failed CS2311 … \n”;
• Suppose the user inputs 40, what will be printed and why?
35
Beyond Two-way Condition
false if (logical
true
expression)
statements
Multi-way Condition: Construct
• In C++, multi-way condition can be constructed as,
if (logical expression 1) {
statements when expression 1 is true 11 if satisity logical expression
} I true executed
else if (logical expression 2) { 11 if not satisify logicalexpression 1 check
expression 2
statements when expression 1 is false and expression 2 is true
} if satisify logical expression 2 executed
else {
statements when both logical expression 1 and 2 are false
} if not satisity logical expression I and 2 executed
37
Multi-way Condition: An Example
• Input a mark, display grade according to
• A: [90, 100], B: [75, 90), C: [55, 75), D: [0, 55)
90 100 75 19.9 55 74.9 0 54.9
38
Multi-way Condition: An Example
• Input a mark, display grade according to
• A: [90, 100], B: [75, 90), C: [55, 75), D: [0, 55)
or
if (mark < 0 || mark > 100) condition CI is true
cout << “invalid mark \n”;
and
2 if (mark >= 90 && mark <= 100)
execute
A
a
b grade = ‘A’;
if 2 is true execute b
3 if (mark < 90 && mark >= 75) N
C if grade = ‘B’;
if 3 is true execute c
4 (mark < 75 && mark >= 55)
d if grade = ‘C’;
5 (mark < 55 && mark >= 0)
e grade = ‘D’; note only finding a
indepent condition only 39
it is not a multi condition
Multi-way Condition: An Example
• Input a mark, display grade according to
• A: [90, 100], B: [75, 90), C: [55, 75), D: [0, 55)
Condition Cl is true
not a malt
way condition
if (mark < 0 || mark > 100) I if (mark < 0 || mark > 100) if I
cout << “invalid mark \n”; a cout << “invalid mark \n”; is true
if (mark >= 90 && mark <= 100) 2 else if (mark >= 90) f
grade = ‘A’; b grade = ‘A’; executed
if (mark < 90 && mark >= 75) 3 else if (mark >= 75) a
grade = ‘B’; grade = ‘B’;
c t
if (mark < 75 && mark >= 55) 4 else if (mark >= 55) program
grade = ‘C’; d grade = ‘C’;
stopped
if (mark < 55 && mark >= 0) 5 else
grade = ‘D’; e grade = ‘D’;
40
Nested if
• An if-else statement is included within another if or else statement
statement1
if (expression1)
if (expression2)
statement2a
else
statement2b
statement3
41
Nested if the if selection body have another if
statement or else if statement or else
statement
• An if-else statement is included within another if or else statement
44
Nested if: An Example Input
• Check if a year is leap year
execute the
• A leap year is a calendar year that contains 20
an additional day added to February to keep
the calendar year synchronized with the
astronomical year or seasonal year
45
Nested if: An Example Input like 8
line9
line
eggante
line10
execute the
17
line 11
execute the
execute the 14 46
Today’s Outline
• Logical data type, operators and expressions
• If statement
• Simple
• Nested
• Switch statement
47
Motivation
• Is there a better way to organize the following code?
int day_of_week;
cin >> day_of_week;
Not logically
if (day_of_week < 1 || day_of_week ) correct as
cout << “invalid day\n”; they are in
if (day_of_week == 1) cout << “its Monday\n”; the same
if (day_of_week == 2) cout << “its Tuesday\n”; execution
if (day_of_week == 3) cout << “its Wednesday\n”;
if (day_of_week == 4) cout << “its Thursday\n”; block
if (day_of_week == 5) cout << “its Friday\n”;
if (day_of_week == 6) cout << “its Saturday\n”;
if (day_of_week == 7) cout << “its Sunday\n”;
48
switch: Syntax and Semantic
• Syntax
switch statement
check the express • Semantic
wheter meet some • Evaluate the expression which results in an
switch (expression) {
case integer type (int, long, short, char)
case constant-expr1:
statements • Go to the case label having a constant
break; // optional value that matches the value of expression;
... break statementstop the • when a break statement is encountered,
execution of the whole
case constant-exprN: terminate the switch
switch
statements statement • If there is no break statement, execution
break; // optional falls through to the next statement
default: // optional • if a match is not found, go to the default
statements label;
break; // optional • if default label does not exist, terminate
} the switch
49
switch: Example 1
int day_of_week;
cin >> day_of_week;
switch (day_of_week) {
case 1: cout << “Monday\n”; break;
If break statement
case 2: cout << “Tuesday\n”; break; executed jump out
case 3: cout << “Wednesday\n”; break; the body of the swith
case 4: cout << “Thursday\n”; break; statement
Removing the break
case 5: cout << “Friday\n”; break;
case 6: cout << “Saturday\n”; break; statement will not change
case 7: cout << “Sunday\n”; break; the equuilence of theprogr
default: cout << “Invalid\n”; break;
} // end switch
execute lineoutside if case I to case
switch if possible 7 not meet 50
switch: Example 1
// What happens there is no break ??
int day_of_week;
Input is an integer which satisity the
cin >> day_of_week; day of week expression
switch (day_of_week) { No break statement not jump out the swith
body after executing each case
case 1: cout << “Monday\n”; case2 7 and default
case 2: cout << “Tuesday\n”; will be executed if theinputis 2
case 3: cout << “Wednesday\n”; case 3 7 and default will be executed
case 4: cout << “Thursday\n”; if the input is 3
case 5: cout << “Friday\n”;
case 6: cout << “Saturday\n”;
case 7: cout << “Sunday\n”;
default: cout << “Invalid\n”; i
} // end switch
51
switch: Example 1
// What happens there is no break ?? • Semantic
int day_of_week;
• Evaluate the expression which results in an
cin >> day_of_week; integer type (int, long, short, char)
switch (day_of_week) {
• Go to the case label having a constant
case 1: cout << “Monday\n”; value that matches the value of expression;
case 2: cout << “Tuesday\n”; • when a break statement is encountered,
case 3: cout << “Wednesday\n”; terminate the switch
case 4: cout << “Thursday\n”; • If there is no break statement, execution
case 5: cout << “Friday\n”; falls through to the next statement
case 6: cout << “Saturday\n”; • if a match is not found, go to the default
case 7: cout << “Sunday\n”; label;
default: cout << “Invalid\n”; • if default label does not exist, terminate
} // end switch the switch
52
switch: Example 1
// What happens there is no break ?? • Semantic
int day_of_week;
• Evaluate the expression which results in an
cin >> day_of_week; integer type (int, long, short, char)
switch (day_of_week) {
• Go to the case label having a constant
case 1: cout << “Monday\n”; value that matches the value of expression;
case 2: cout << “Tuesday\n”; • when a break statement is encountered,
case 3: cout << “Wednesday\n”; terminate the switch
case 4: cout << “Thursday\n”; • If there is no break statement, execution
case 5: cout << “Friday\n”; falls through to the next statement
case 6: cout << “Saturday\n”; • if a match is not found, go to the default
case 7: cout << “Sunday\n”; label;
default: cout << “Invalid\n”; • if default label does not exist, terminate
} // end switch the switch
53
switch: Example 2 while ((c = getchar()) != EOF) { /* get a char */
switch (c) {
case ‘0’: case ‘1’: case ‘2’: case ‘3’: case ‘4’:
case A B case C
case case ‘5’: case ‘6’: case ‘7’: case ‘8’: case ‘9’:
is equvilent to digit_count++;
if CA 11 B11 C executed if break;
meet caseo mustbetrue
case 9 case ‘ ’: case ‘\n’: case ‘\t’:
white_character_count++;
recited't break;
9890
default:
other_character_count++;
f
break;
} n
}
54
Exercises A
Expected Output:
Write a program that prompts
Example 1 Example 2 the user to enter an integer
Enter an Integer Number: 15
15 is divisible by 3 and 5.
Enter an Integer Number: 21
21 is divisible by 3 only.
and determines whether it is
a) divisible by 3 and 5
Example 3 Example 4
b) divisible by 3 only
Enter an Integer Number: 40 Enter an Integer Number: 23
40 is divisible by 5 only. 23 is not divisible by 3 or 5. c) divisible by 5 only
d) not divisible by 3 or 5
55
Exercises B
• Write a program that reads 3 integer values (> 0) from the user. The 3
values are interpreted as representing the lengths of the three sides of a
triangle. The program prints a message saying whether the triangle is
Equilateral (all sides equal), Isosceles (only 2 sides equal), Scalene (all
sides unequal), or Impossible (can't form a triangle). A triangle can be
formed only if the sum of the length of any 2 sides is greater than the
length of the 3rd side and the length of all the sides of the triangle are
positive.
• Hint: The order of checking may affect the complexity of your code
(although it still works). You may wish to check for impossible cases
first, and identify the scalene case last.
56
Exercises B
Expected Output:
Example 1 Example 2
Enter the value of A, B and C: Enter the value of A, B and C:
3 3
4 3
5 3
Scalene Equilateral
Example 3 Example 4
Enter the value of A, B and C: Enter the value of A, B and C:
5 1
5 2
2 10
Isosceles Impossible
Example 5 Example 6
Enter the value of A, B and C: Enter the value of A, B and C:
0 1
2 -2
10 10
Impossible Impossible
57
Exercise C
• Police captured four suspects, among whom one is a thief
• Consider the following statement of the suspects
• A: I’m not the thief Not lying A is not the thieft
• B: C is the thief Not lying B is the thief
• C: D is the thief lying C is the thief
• D: C is lying Not lying D is not the thief
• If we know that there is only one liar, then who is the thief?
59