We are going to look at a longer form of the if statement. This form looks much like our first form, but with an extra set of curly brackets that make a block of code which runs when the Boolean statement is false. Remember, with the former, simpler if statement nothing happened when the Boolean statement was false; the program simply continued on. Now we will do things one way if the Boolean statement is true, and we do them another way if the Boolean statement is false. To work this way, we need one more keyword: else.
Here is a diagram that shows the flow of a program section that we will call an if, else statement. Note that in this if, else statement when the Boolean statement evaluates to true, then a certain job happens, but if it evaluates to false, then a different certain job happens. After one or the other job completes, the program continues on.
Here are a few examples of these type of decisions. A sample Boolean statement that might be used to model the situation is given for each.
To do all this in EZ Math Movie we need both the keyword if and another keyword, else. Below is some code that checks if x is equal to 2. If it is, this prints the text 'It is true.' If x is not 2, this prints 'It is false.' Note the parentheses around the Boolean statement and both pairs of curly brackets with the word else between them. The first set of curly brackets form what is often called the 'true block' or the 'true clause'. The second set, after else, form the 'false block' or 'clause'.
The upper part of our if, else statement (the part above else) looks exactly like the simpler if statement we have already covered. So, past the first close curly bracket, the one that closes the true block, we have:
This example is much like the previous one, except a false, or else block has been added to make an if, else statement.
Note that this program has a path if the Boolean statement is true (the true block), and it has a different path (the false block) if the Boolean statement is false.
Next tutorial: Nested if statements
Here is a link to a related article at EZ Programing Demos: