Upload
others
View
9
Download
0
Embed Size (px)
Citation preview
Alice Control Statements: Introduction
• Control structures/statements allow you to change the order in which state-ments are executed in a program
• The order is sometimes referred to as flow of control
• We’ve already seen two such structures:
1. do in order
2. do together
• do in order represents sequential control or processing
– Statements are executed one after the other, in the order they are listed
• do together represents parallel control or processing
– Statements are executed at the same time, in tandem
• This chapter introduces two types of control statements:
1. Selection
2. Iteration (repetition, looping)
• To help visualize flow of control, flow charts are used
– A flow chart is made of symbols, each with a special meaning
– By following the arrows through the chart, you see the order in whichstatements are executed
– A few flow chart symbols:
1
Alice Control Statements: Introduction (2)
– The flow chart for sequential control is
– The flow chart for parallel control is
2
Alice Control Statements: Boolean Expressions
• The Boolean data type has two values:
1. true
2. false
• Alice variables can be of type Boolean, and they are assigned Boolean expres-sions
– A Boolean expression is one that evaluates to true/false
• Types of Boolean expressions:
1. Boolean literal (true/false)
2. Boolean variable
3. Relational expression
– constructed from relational operators:
==, !=, <, >, >=, <=
4. Logical expression
– Logical expressions are constructed from three logical operators:
(a) && (and)
(b) || (or)
(c) ! (not)
– Arguments must be Boolean
– Semantics are represented by truth tables:Graphical way of expressing value of boolean expression
A B A && B A || B !A
true true true true false
true false false true false
false true false true true
false false false false true
3
Alice Control Statements: Boolean Expressions (2)
• Boolean variables
– Often have names like isDone, isZero, isValid
– This also holds for Boolean functions (those returning boolean values)
• Cautions
1. English does not translate directly to Boolean expressions
– ”If the color is red or blue, ....”
– Wrong: color == RED OR BLUE ...
– Right: (color == RED) OR (color == BLUE)
2. Strings cannot be compared with the relational operators; they use specialfunctions (p 143)
– str1.contentEquals(str2)
– str1.equalsIgnoreCase(str2)
– str1.startsWith(str2)
– str1.endsWith(str2)
– str1.contains(str2)
4
Alice Control Statements: Selection
• Selection deals with making a choice
• If/Else is the basic selection statement
• Syntax:
if <boolean_expression>
<if_statements>
else
<else_statements>
• Semantics:
– if Boolean expression is true, execute if statements after if
– if Boolean expression is false, execute else statements following else (if theelse is included)
5
Alice Control Statements: Selection (2)
• To add to program:
1. Drag from control statement list in editor window
2. Select a condition (Boolean expression)
– This value can be replaced by a Boolean expression of your choice later
3. If there is nothing to do when the condition is false, simply add nothing tothe else part
6
Alice Control Statements: Selection - Nested If/Else Statements
• If/Else statements can be nested
• This is done by just dropping if statement in the drop statement here locationof another if
7
Alice Control Statements: Selection - To Nest or Not to Nest If/Else Statements?
• Example:
• Proper use of nested if-else:
if (avg >= 90)
grade = "A"
else
if (avg >= 80)
grade = "B"
else
if (avg >= 70)
grade = "C"
else
if (avg >= 60)
grade = "D"
else
grade = "F"
– Improper use of nested if-else:
if (age >= 65)
exemptions = exemptions + 1;
else
if (spouseAge >= 65)
exemptions = exemptions + 1;
else
if (dependents > 0)
exemptions = exemptions + dependents;
else
if (married AND (filingStatus == 2))
exemptions = exemptions + 1;
else
NULL
NOTE: NULL means no statement; it is NOT an Alice3 statement
8
Alice Control Statements: Selection - Issues When Writing Nested If/ElseStatements (2)
– Proper version of above - do not nest:
...
if (age >= 65)
exemptions = exemptions + 1;
else
NULL
if (spouseAge >= 65)
exemptions = exemptions + 1;
else
NULL
if (dependents > 0)
exemptions = exemptions + dependents;
else
NULL
if (married AND (filingStatus == 2))
exemptions = exemptions + 1;
else
NULL
This is an example of sequential if/else statements
• Usage rules of thumb:
– Use sequences of ifs for independent situations
– Use nested ifs for dependent, mutually-exclusive situations
9
Alice Control Statements: Iteration - Introduction
• Iteration/repetition/looping: Executing a sequence of instructions multi-ple times
• Loop components:
– Condition: determines whether loop should continue
– Body (process): instructions being repeated
– Loop control variable (LCV): Variable whose value determines when loopstops
• Basic steps of loop control:
Initialize Process
Initialize LCV
BEGIN LOOP
Update Process
Update LCV
END LOOP
10
Alice Control Statements: Iteration - Loop Control
• Main issue with loops is loop control
– Determining
1. How many times the loop body should execute, and
2. The methods for controlling this
• 2 general types of loop control:
1. Definite iteration:
– Loop executes a fixed number of times
2. Indefinite iteration:
– Loop executes an indeterminate number of times
11
Alice Control Statements: Iteration - Definite Iteration
• Sometimes called count-controlled iteration
• Body will execute a fixed number of times
• LCV is an example of a variable called a counter
– It counts how many times something occurs
• Example:
– count is the LCV
– count is a counter variable
12
Alice Control Statements: Iteration - Definite Iteration (2)
• Alice 3 uses a count control structure for implementing definite iteration
– It appears as a for loop in the code when the programming language pref-erence is set to Java
– Dragging count from the control structure list will create a for loop with asystem-generated LCV (whose name can be changed with a right-click)
– You will be asked what value to count to
– Note that it counts from zero
– If you have added variables to your code (or parameters), you have theoption of using one of them as the value to count to
13
Alice Control Statements: Iteration - Definite Iteration (3)
– What the count loop can’t do:
∗ Start at a value other than zero
∗ Count by increments other than one
∗ Count backwards
14
Alice Control Statements: Iteration - Indefinite Iteration
• Used when don’t know ahead of time how many times loop should execute
• Types of control:
1. Count controlled: Stop when an event has occurred a predefined numberof times
2. Sentinel: Stop when a particular value (or value from a set of values) isencountered
• Count controlled
– Iterations determined by occurrence of some event a specified number oftimes
– Loop may need to iterate more than this number
– Example:
15
Alice Control Statements: Iteration - Indefinite Iteration (2)
• Sentinel control
– Sentinel is one or more values that signal the end of iteration
– They are frequently values that are outside of range of acceptable valuesused for processing
∗ For example:
1. Temperatures below absolute 0
2. Ages below 0
3. Numeric grades below 0
4. Letter grades other than A, B, C, D, F
– Example:
– Requires initialization of the LCV prior to entering loop
– A Boolean variable that is used for sentinel control is sometimes called aflag
16
Alice Control Statements: Iteration - While Loops
• Pretest loop
• Most general loop construct
– All other loop types can be written as while loops
• General structure:
17
Alice Control Statements: Iteration - While Loops in Alice
• These are created like any other control structure
• The while loop in Alice works exactly as described above
• Example:
• When initially added to a program, you select an initial condition
• Afterwards, you can construct as complicated Boolean expression as you likeby dragging and dropping
– The expressions are constructed in the same way as they are for if/elsestatements
• The following for and while are equivalent
18
Alice Control Statements: Iteration - Potential Problems
1. Infinite loop
• Loop that never ends
• Can result due to many reasons:
– Failure to initialize LCV
– Failure to update LCV properly
– Poor choice of termination condition
– Failure to update process
2. Off-by-one error
• Count-controlled loop that iterates one too many or one too few times
19
Alice Control Statements: Iteration - Nested Loops
• Can place one loop inside of another
• Must make sure that initializations and updates occur for each loop and in theappropriate places
• Example:
20