Download presentation
Presentation is loading. Please wait.
1
Karel J Robot Chapter 6
2
Iteration (Loops) Loops repeat a set of instructions
Two types of loops: Definite loops ( for ) perform instructions explicit number of times Indefinite loops ( while ) perform instructions an indefinite number of times (until a certain test fails) Chapter 6
3
for Loops General form: for ( <initialize variable>; <test>; <increment> ) { <instruction set> } Chapter 6
4
for Loops (cont.) <initialize variable> sets a variable/identifier to a certain value (variable is usually count, i, j) <test> is a test that is evaluated each time the body is about to be executed (when false, loop is exited) <increment> changes the loop control variable (usually x++ or x--) Chapter 6
5
for Loops (cont.) Example: for (int x=1; x<=5; x++) { karel.move(); } This causes karel to move 5 times Chapter 6
6
for Loops (cont.) Flow of for loops: Initialization statement executes
If test is true, proceed to step 3; if test is false, go to step 6 Instructions in body of loop are executed Increment statement executes Return to step 2 Program proceeds to statements after loop Chapter 6
7
while Loops General form: while ( <test> ) { <instruction list> } Loop continues until test is false Chapter 6
8
while Loops (cont.) Example: while (karel.frontIsClear ()) { karel.move (); } Causes karel to move continuously until there is a wall in front of it Chapter 6
9
while Loops (cont.) Flow of while loops
If test is true, proceed to step 2; if test is false, go to step 4 Instructions in body of loop are executed Go to step 1 Statements after loop are executed Chapter 6
10
Building a While Loop Step 1 – Identify what is true when the loop is finished (this is always easier than determining what is false while it is still executing) Step 2 – Use the opposite form of step 1’s result as the <test> for the loop. You just need to negate the entire thing. Chapter 6
11
Building a While Loop (cont’d)
Step 3 – make progress toward the goal (completion of the loop) within the loop Step 4 – Do whatever is required before and/or after the loop to ensure that we solve the given problem Example: Pick all beepers from a corner without knowing how many there are. Chapter 6
12
Infinite Loops In a for or while loop, it is possible for the test to never be false When this happens, the loop continues infinitely Depending on the compiler, application, and other circumstances, an error may occur or the app may crash Chapter 6
13
Chapter 6
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.