So far, we only had one kind of loop, which
provided us a way of executing an instruction a given number of times.
However, there was no way of saying "repeat this for as long as a certain condition is true".
This is not a problem anymore now that you know "while loops".
while ( condition)
{
// instructions
}
Example:
// This instruction will make the robot put beepers until its beeper
// bag is empty
void myRobot :: emptyBeeperBag()
{
while (anyBeepersInBeeperBag())
{
putBeeper();
}
}
void myRobot :: nextToWestBoundary()
{
faceWest();
while (frontIsClear())
{
move();
}
}
These are things that are true before and after each loop iteration. For example, they could be the number of beepers in bag or the direction the robot is facing.
Make sure that your loop will always terminate. Check the condition you are testing to see if you should go through the body of the while loop one more time. This condition should become false at some point, otherwise you will loop forever.
A BAD Example: (ie what not to do...)
void myRobot :: infiniteloopexample()
{
if (nextToABeeper())
{
pickBeeper();
while (anyBeepersInBeeperBag())
{
turnLeft();
}
}
}
The only time you can have a condition that will always evaluate to true is when you have an if statement THAT HAS A CONDITION THAT WILL BECOME TRUE AT SOME POINT whithin the while loop, and that has a RETURN instruction so that you leave the while loop (and the function). It could also have a turnOff instruction instead of the return.
Basically, make sure there will always be a way of getting out of the loop. Otherwise, you will run into trouble. Infinite loops are relatively easy to find with Karel++, since you can see how the robot behaves, but they are going to be much more difficult to fix when we get to C++.
Here is an example:
Don't ask me why anyone would want a function doing that...
// returns true only if picked beeper, the Robot faces East when the function returns true
// otherwise, returns false
Boolean myRobot :: uselessfunction()
{
if (nextToABeeper())
{
pickBeeper();
while (anyBeepersInBeeperBag())
{
turnLeft();
if (facingEast())
{
return true;
}
}
}
return false;
}