Sometimes we want the same set of instructions to be performed more than once.   If we want the frog to move down 1 square, then right 1 square, and we want to do that 10 times over, we could write:

frogDown(1);
frogRight(1);
frogDown(1);
frogRight(1);
frogDown(1);
frogRight(1);
etc.

This would certainly work, but there is a quicker and more effective way of achieving the same result.   To repeat the same set of instructions a number of times we use the ‘while’ keyword, followed by an expression that must evaluate to true if we want to keep repeating, followed by the instructions we want to repeat.

while( expression )
{
   First Instruction
   Second Instruction
   etc.
}

This is called a loop.   When the program reaches the while keyword, the expression is evaluated.   If the expression evaluates to false, the program continues immediately after the } and therefore the contents of the loop are never performed.   But if the expression evaluates to true, the contents of the loop are performed, and the expression is evaluated a second time.   If this second time the expression evaluated to false, the program continues immediately after the }.   If the expression was true, the contents of the loop are performed again.   This process continues until the expression evaluates to false.

In this task we have to get the frog home by performing a sequence of very repetitive instructions.   Because the task can be completed by repeating the same instructions until the required result is achieved, we will use a while loop.   To know when to stop looping use the statement frogNotHome().   This will evaluate to false when the frog is home, causing the loop to stop.

Tasks: