So far all the programs youve seen have been a simple sequence of instructions, carried out one after the other. But there will often be times when you want to perform an instruction only under certain circumstances. The circumstances must be clearly defined to the compiler using something called Boolean logic. In Boolean logic, questions are phrased in such a way that the answer can only ever be yes or no.
Boolean logic |
Not Boolean logic |
|---|---|
| Is the sky blue? | What colour is the sky? |
| Is today Saturday? | What day is it? |
| Is 10 one number greater than 9? | Which number is one greater than 9? |
| Is the opposite of true, false? | What is the opposite of true? |
In programming, the question you ask is called an expression. If the answer to the question is yes, we say the expression evaluates to true, and if the answer is no, we say the expression evaluates to false. The result of the expression can only ever be true or false. If we put something else in the expression that cannot be evaluated to true or false, the compiler will tell us there is an error.
When we want to ask a question in our program, we use the keyword if, followed by the question we want to ask in brackets, then followed by the instruction we want to perform if the expression evaluates to true. It looks like this:
if( question )
instruction
Optionally, we might want to perform a different instruction if the expression evaluates to false:
If |
True |
False |
|---|---|---|
| It is cold | Wear a jumper | Wear a T-shirt |
| Hard disk has enough space | Save file | Give user an error message |
We achieve this using the keyword else, which can only ever be used straight after an if statement. It looks like this:
if( question )
instruction
else
instruction
In this task, we have to get the frog to its home, but the frog is going to be positioned on either the left or the right of the screen. This will be done randomly whenever the program starts. That means that we will have to move the frog right if its on the left of the screen, and left if it starts on the right.
To find out where the frog is, we will use the statement frogX(). This stands for a number which represents which column the frog is currently in. We will then test that number to see if it is equal to Zero. If it is, the frog must be on the left of the screen, and therefore we will have to move it right.
if( frogX() == 0 )
frogRight(8);
The symbol == means is the number on the left the same as the number on the right? It is composed of 2 equal signs back to back. Its a common mistake to type only one = sign when you meant to type two, so you will need to be careful. If frogX() == 0 evaluates to false, you will need to move the frog left.
Fill in the missing code. You will need to use an if statement, followed by an else statement.
Run the program several times to make sure it works no matter which side the frog starts on.