In the following code below from the Cleanup Karel example, what is the purpose of If Statement #2?

// This program has Karel walk down the
// row and clean up all of the tennis balls
// on the way.
function main() {
while (frontIsClear()) {
// If statement #1
if (ballsPresent()) {
takeBall();
}
move();
}
// If statement #2
if (ballsPresent()) {
takeBall();
}
}

main();
JavaScript

To move the last time

To pick up the ball that is in the last spot

To pick up the ball that is in the last spot, if there is one

To take the ball from all of the positions that have a ball on them

1 answer

In the given Karel example, the purpose of If Statement #2 is:

To pick up the ball that is in the last spot, if there is one.

This is because the loop (while frontIsClear()) will move Karel until it can no longer move forward. When Karel exits the loop, it is indeed at the last position it can go to, and there may still be a ball there. The second if statement checks if there are balls present at that last position, and if so, Karel takes the ball.