P - 1
Iteration
P - 2
Tail Recursion FlashBack
A tail recursive solution:
public void goToWallRec() { if (!isFacingWall()) { forward(); goToWallRec(); } }
goToWall
P - 3
JEM
WallBuggle wendy = new WallBuggle(); wendy.goToWallRec(); if (!isFacingWall()) { foward(); goToWallRec(); }
goToWallRec run
Execution Land
this wendy
ww wb1
this
wb1 if (!isFacingWall()) { foward(); goToWallRec(); }
goToWallRec
this
wb1 if (!isFacingWall()) { foward(); goToWallRec(); }
goToWallRec
this
wb1 if (!isFacingWall()) { foward(); goToWallRec(); }
goToWallRec
this
wb1 if (!isFacingWall()) { foward(); goToWallRec(); }
goToWallRec
this
wb1 position heading color brushDown
true WallBuggle
wb1 red
WallWorld
ww EAST
Object Land
x
Point 5
y
1
pt1 pt1
P - 4
Iteration
Suppose we want to execute a series of statements repeatedly... until some condition is met:
statement1; statement2; statement3;
P - 5
“While” Construct
How it works:
- 1. Evaluate boolean expression
- 2. If true → execute body of while and then goto step 1
- 3. If false → go to statements after while loop
Syntax of while loop:
while (boolean expression) { statement1; statement2; statement3; }
P - 6
How to exit from a while loop?
Syntax of while loop:
while (boolean expression) { statement1; statement2; statement3; }