In this task the frog will have to cross 2 lanes of traffic. The second lane of traffic is coming from the opposite direction to the first, and there is a corresponding instruction to test whether it is safe to cross:
| safeOnLeft() | Evaluates to true if there is no traffic approaching from the left |
You may think its acceptable to move into the road if theres no traffic from the right, then wait there until theres no traffic from the left, but if you attempt this youll see that the middle of the road is not a very safe place to stop and wait. What we need to do is move to the side of the road, then only cross when there is no traffic from the right and no traffic from the left at the same time.
This means that both expressions have to evaluate to true at the same time. To do this we use the symbol && two & signs back to back, which programmers call an 'And Operator' . An expression, followed by &&, followed by another expression, evaluates to true only if both expressions evaluate to true. If only one or neither of the expressions evaluates to true, the result will be false.
| First Expression | Operator | Second Expression | Result |
|---|---|---|---|
| Is the world round? | && | Is the sky blue? | true |
| Is the world round? | && | Is the sky green? | false |
| Is the world flat? | && | Is the sky blue? | false |
| Is the world flat? | && | Is the sky green? | false |
This program will look like the program from the last task, except the expression for the if statement (within the while loop) will look like this:
if( safeOnLeft() && safeOnRight() )
frogRight(3);
Write a program to guide the frog safely across 2 lanes of traffic