What if we want to perform more than one instruction if an expression evaluates to true (or false)?
If |
True |
False |
|---|---|---|
| Kettle has boiled | Put coffee in mug | Come back later |
| Pour boiled water into mug | ||
| Stir | ||
| Drink |
If we want to perform more than one instruction after an if or else statement, then we group the instructions we want to perform within curly brackets {, } So that the compiler knows all the instructions need to be carried out. It looks like this:
if( expression )
{
First Instruction
Second Instruction
etc..
}
else
{
First instruction
Second instruction
etc..
}
Even if we only want one instruction carried out we can still group it in curly brackets
if( expression )
{
Only Instruction
}
But if we have more than one instruction we must use them:
if( expression) |
||
First Instruction |
||
Second Instruction |
This instruction will be carried out regardless of whether the expression evaluated to true or false, because we didn't use curly brackets. |
This task is similar to the previous task, with the frog starting on either the left or right of the screen. However in order to get the frog home, we will have to perform more than one instruction after we have found which side it started on. First we test if the frogs position is equal to zero, and that will tell us which side it is starting on. Then we perform a number of instructions depending on how the expression evaluates
if( frogX() == 0 )
{
frogDown(4);
frogRight(8);
frogUp(4);
}
else
{
etc.
}
Fill in the missing code, and run the program several times to make sure it works no matter which side the frog starts on
Try keeping the program exactly the same except with the curly brackets removed just to see what happens