So far we have seen if and else statements. But what if we want to check multiple conditions? We can use the else if statement which has the form:
If (condition) { Action to perform if some condition is met } else if (second condition) { Action to perform if another condition is met } …
The …
at the next could be blank, an else statement, or another else if statement! Else if allows us to continue our checking of different conditions until one is met. An else statement provides actions to perform if no previous conditions are met.
For example, if we think about the weather:
If (It is sunny) { Bring sunglasses } else if (It is raining) { Bring an umbrella } else { Bring a sweater }
We can use else if statements to help Codey make more advanced decisions!
Instructions
There’s a lot going on here. Codey needs to go get the key, then get to the door, but there are at least 3 directions Codey must go in. Can you use if/else if/else
blocks to get Codey to the door?
Hint
Codey needs to go down when getting the key, and then line up with the door vertically or horizontally before turning again.
Solution
While program is running If Codey does not have key Move down Else if Codey's x position is < 8 Move right Else Move up