- Introduce Karel's world as on Page 2 of the document.
- Discuss the example on page 8 of the document.
- Discuss how the code can become large and hard-to-read. How abstractions through function definitions can help --- turnRight and turnAround. Why these abstractions? Why not moveAndTurnLeft? Intuitiveness, generality.
- Discuss pothole example on page 14 where a beeper needs to be placed to fill the pothole.
- Discuss the case where we do not know if a beeper is already present or not. Introduce conditions like beeperPresent(), frontisClear().
- Discuss how other conditions can be implemented using these conditions. e.g., leftIsClear() involves turnLeft(); ret = frontIsClear(); turnRight(); return ret;.
- Introduce the notion of a variable.
ret
is a variable in the example above.
- Similarly introduce constants TRUE and FALSE. Implement
noBeeperPresent()
using beeperPresent()
.
- Introduce
if-then-else
construct and show its example usage to implement the case where you fill the pothole only if a beeper is not already present.
- Formalize the meaning of
if-then-else
a bit more using arbitrary statements as follows:
if (cond) {
S1;
S2;
} else {
S3;
S4;
}
S5;
S6;
If cond
is TRUE, then S1;S2;S5;S6;
get executed.
If cond
is FALSE, then S3;S4;S5;S6;
get executed.
if
can appear without else
:
if (cond) {
S1;
S2;
}
S5;
S6;
What happens if cond
is TRUE? What happens if cond
is FALSE?
- Now consider the case where we need to repeatedly fill potholes in the road; All potholes are equidistant at distance 1 from each other.
- One option is to write the code multiple times. e.g., if there are 5 potholes, write the code 5 times. What if there are one million potholes?
- Motivate the need for a construct that allows repitition of a given program/instructions:
for
loop.
- For loop: allows repeating up to "
count
" number of times, i.e., count
iterations:
for (i = 0; i < _count_; i++)
{
S1;
S2;
}
- Only the
count
can be changed by the user in this loop. This loop says that make i
count from 0 to count-1
.
- Can write the code as:
numPotholes = 5
for (i = 0; i < numPotholes; i++) {
fillNextPothole();
}
- Graphically show the state after every loop iteration for this example.
- Show the semantics of this loop for general instructions S1 and S2 in the body.
- Discuss another program where Karel wants to keep walking till it hits the wall. Can this be done with the for loop? One option is: if we know the maximum length of a street or an avenue, we can use that count, and use an if condition in the body. But this is unsatisfactory because how will we know the maximum length? Overestimation = bad because inefficient. Underestimation = very bad because incorrect.
- Discuss while loop:
define moveTillClear()
{
while (frontIsClear())
{
move()
}
}