Chapter 5 part 1

advertisement
Repetition Structures
Chapter 5 Part 1
Types of Repetition Structures


The Loop Instruction
The While Instruction
2
The Loop Instruction

Simple control structure allows
o
o
Instruction (or block of instructions) to be repeated
multiple times
Repeating fixed amount of times

A whole number
 No fraction of time
3
Using Loop Instruction
 Drag Loop instruction


from bottom of Method
Editor
It prompts you for
amount of times to loop
Creates empty slot
where instructions can
be placed
4
Loop Instruction


Uses an index variable to keep track of how many times
the loop is completed
The index variable is increased by one each time the loop
finishes
Set index to 0
Is
Index <
no. of loops?
T
Execute instructions
in loop
F
5
Example Loop Flowchart

Ex: on clock move hour hand every hour
Set index to 0
T
Index < 12?
Clock, hour roll
left 1/12th
revolution
wait one hour
Add 1 to index
F
6
Loop Index Calculation Methods



Fixed
Function
Variable
7
The Loop Instruction
Simplifies to:
Fixed number
8
Loop Controlled by Function Call

What if you want to loop according to what is in the
scene that is not a fixed number of repetitions?
o
o
o
Example: getting a ball to roll across into a goal regardless of
where the ball is initially placed
Use the soccerBall’s distance to function to calculate the
distance to the goal
Loop uses truncation: numbers to right of decimal point are
discarded

Examples: objects loop 4 times not 4.8 or 3 times not 3.4
9
Loop Controlled by Variable



Ask user for
amount of times a
lion should roar
Place value in
variable
Loop the amount of
times user entered
10
Infinite Loops

The loop that never stops
o


Use for objects that shouldn’t stop
If placed in consecutive order…the next instructions
will NEVER occur, since the loop NEVER ends!
Place an infinite loop into a Do Together structure with
other items.
11
Infinite Loop Continual Motion
Helicopter
blades are
turning while
helicopter
rescues diver
12
Infinite Loop Background Example



Infinite loops
are good for
moving
objects in
background
This example
simulates
moving water
by changing
texture of
water
Called from
main method
13
Checkpoint



What does the Loop instruction do?
What are four different types of loops?
What is an infinite loop?
14
Homework



Read chapter 5 section 1
Do tutorials 5-1 and 5-2
Due one week after assigned with 1 week grace
15
Download