Lecture 4-1
Lecture 4-1
Branches:
a) if Statement
Branches: “if” Statement 9
false if ( condition )
condition
statement 1
statement 2
true
...
statement end
group
Branches: “if - else” Statement 10
Example: Create a script file and type the following code:
11
Example: 12
Check each element in x in this example all elements
give true 13
In false case
BRANCHES (if-STATEMENT) 15
statement
Optional group 1 true condition false
2
statement statement
group 2 group 3
Example:
16
Branching Examples
17
Example: Assigning letter grades
Range Grade
100 grade > 95 A
95 grade > 86 B
86 grade > 76 C
76 grade > 66 D
66 grade > 0 F
Branches:
b) switch Statement
BRANCHES (switch-STATEMENT)
The switch statement syntax is a means of conditionally
25
executing code. In particular, switch executes one set of
statements selected from an arbitrary number of alternatives.
Optional
BRANCHES (switch-STATEMENT)
26
Remarks:
The case expression could be more than one enclosed by {}
At most one code block can be executed. If the switch_exp matches more
than case_exp the first one is executed.
BRANCHES (switch-STATEMENT) 27
Example:
Switch statement is an
alternative for if statement:
Example
>>mygame
Guess a number(0-10):5
Guess a number(0-10):7
Guess a number(0-10):2
You failed, Try again(Y/N)? % player enter ’Y’ if ‘N’ quit a
game
Guess a number(0-10):9
Yes, you got it!!!