Question: 24

In the following code, what would be a good Postcondition to write?

/* Precondition: Karel is on a spot with a tennis ball facing East
* Postcondition: ...
*/
function getOnTop() {
turnLeft();
move();
turnRight();
}
JavaScript

Karel is on a spot with a tennis ball facing north

Karel ends one spot above a tennis ball facing East.

Karel is on the same position but on top of a ball.

Karel is facing East.

1 answer

To determine a suitable postcondition for the provided code segment, let's break down what the function getOnTop() does step by step, given the precondition that "Karel is on a spot with a tennis ball facing East":

  1. Initial State: Karel is facing East at a position with a tennis ball.
  2. First Action - turnLeft(): Karel will now be facing North.
  3. Second Action - move(): Karel will move forward (in the direction he is facing, which is now North). This means Karel will move one spot above his original position.
  4. Third Action - turnRight(): Karel will turn to face East again.

From this analysis, the relevant postcondition should reflect Karel's final state after executing the function. Karel moves from the original spot (where the ball is) to the spot directly above it while facing East, where he will also be positioned over the ball.

The most accurate postcondition from the provided options is:

Karel is on the same position but on top of a ball.

This clearly indicates that after executing the function, Karel ends up on top of the tennis ball, while also maintaining the necessary condition that he is in the correct position.