Solutions to Karel++ Practice Quiz

1 A -- watch for bad indentation that is there to trick you
2 C -- you loop 10 times, everytime, either the if clause or the else will be executed, but NEVER both
3 C -- while loops stop when the test condition becomes false
4 D -- same reason as above
5 A -- invariants are things that are true before each pass through the loop and right after, what happens within the loop does not matter

Problem 6

a) Correcting the errors

Watch for syntax errors (missing semi-columns, parentheses, curly braces).
*Each time you have a loop, while, if or else, you MUST have curly braces.
*Each time you see the name of an instruction, it should be followed by parentheses
*There is always a semi-column at the end of a class definition
During the test, keep a piece of code that you know is right next to you as a quick reference.

void SquareMaker :: extend_right()
{
        while (nextToABeeper())
        {
               move();
        }
        turnaround();
        move();
        turnaround();
        while (nextToABeeper())
        {
               move();
               putBeeper();
               turnLeft();
               move();
               turnLeft();
               move();
               turnaround();
        }
}

b) Invariants: facing East, same avenue (different street)

c) Position (*) after extend_right has been executed

|*
|1111
|1111
|1111
|____

d)
class SquareMaker : Robot
{
        void extend_right();
        void turnaround();
        void extend_top();
        void makeSquares(); };

void SquareMaker :: extend_top()
{
        // get in position for top
        move();
        turnaround();
        // put beepers on top row
        while (frontIsClear())
        {
               putBeeper();
               move();
        }
        putBeeper();
        // go back to the origin
        turnLeft();
        while(frontIsClear())
        {
               move();
        }
        turnLeft();
        // the robot is now at the origin, facing East
}

void SquareMaker :: makeSquares()
{
       // Handle the 1st beeper separately
       if (anyBeepersInBeeperBag())
       {
              putBeeper();
       }
       // Now empty the rest of the bag...
       while (anyBeepersInBeeperBag())
       {
              extend_right();
              extend_top();
       }
} task
{
       SquareMaker Karel (1, 1, East, 16);
       Karel.makeSquares();
       Karel.turnOff();
}