Chapter 4: Selection Statements chauvtn@hcmut.edu.vn... References Deitel and Harvey Deitel, Prentice Hall, 2012... Introduction ended with a semicolon ; stretched on multiple lines
Trang 1Chapter 4: Selection Statements
chauvtn@hcmut.edu.vn)
Trang 3References
Deitel and Harvey Deitel, Prentice Hall, 2012
– Brian W Kernighan and Dennis M Ritchie, Prentice Hall, 1988
3
Trang 5Introduction
ended with a semicolon (;)
stretched on multiple lines with a backslash \ at the end
able to be grouped in the brackets {}
not consider spaces
specified by {} with no semicolon after the right brace
contains as many statements as required
is a compound statement, syntactically equivalent to a single statement
Trang 6double minNumber = positiveNumber[0];
iteration = iteration + 1;
} } }
Block Single statement
Trang 8double minNumber = positiveNumber[0];
iteration = iteration + 1;
} } }
Control Statements for Selection
Trang 12Print “Passed” if grade >= 5.0
Otherwise, print “Failed”
Trang 14if else statements
Which one do you prefer: conditional expressions or if else statements?
Trang 15Nested if /if else statements
Trang 16Nested if /if else statements
Trang 17Nested if /if else statements
17
Trang 18Nested if /if else statements
Trang 19Nested if /if else statements
Trang 20switch (<expression>) {
case <case 1>: <Statements 1>; break;
case <case 2>: <Statements 2>; break;
of a number of constant
integer values, and branches accordingly
Trang 21switch case statements
21
switch (<expression>) {
case <case 1>: <Statements 1>; break;
case <case 2>: <Statements 2>; break;
…
case <case N>: <Statements N>; break;
[default: <Default>]
}
if (<expression> == <case 1>) <Statements 1>
else if (<expression> == <case 2>) <Statements 2>
Trang 22switch case statements
enumerated data, characters
of the aforementioned types
through to the next unless an explicit action is
taken to escape
break (return) statement
Trang 23true (0) true (0) false (0) false (0) false (0)
Trang 24switch (<expression>) {
case <case 1>: <Statements 1>
case <case 2>: <Statements 2>
Trang 25switch case statements
25
switch (<expression>) {
case <case 1>: <Statements 1>
case <case 2>: <Statements 2>
Trang 26true (0) true (0) false (0) false (0) false (0)
switch case statement with “fall-through” property
Trang 2727
Trang 29Put them all together
week Input a day in a week and output its corresponding activities
int strcmp(const char *str1, const char *str2)
< 0 if str1 < str2 (less than)
> 0 if str1 > str2 (greater than)
= 0 if str1 = str2 (equal)
char *strcpy(char *destination, const char *source)
29
Trang 30Add more codes to make such an input valid (?!)
Trang 31according to a “TRUE” ( 0) value of a
condition (expression)
in programming
31
Trang 32Chapter 4: Selection Statements