If…Then…Else

In the previous section we looked at the If…Then statement that is used for making a decision. When using the If…Then statement a section of code is performed only if the Boolean statement is true. If the Boolean statement is false, nothing happens. In some situations, if the Boolean statement is false and the section of code is not performed, you would like an alternative piece of code to be performed instead. In this case an optional Else statement can be used. The If…Then…Else statement (in most computer programming languages), takes the generic form of:

IF (Boolean expression) THEN
statements to be performed …
ELSE
alternate statements to be performed …
ENDIF

In the previous example of asking the user how many students were in the class, you might have noticed that the user was given no feedback if there were 30 or fewer students. This can add confusion for the user; they might be unsure if the program worked correctly.

An example of what this would look like using an If .. Then .. Else statement is shown below:

Top-Down Design for If…Then…Else statement

Top-Down Design for If…Then...Else statement

Flowchart for If…Then…Else statement

If…Then...Else flowchart

Pseudocode for If…Then…Else statement

GET number_of_students
IF (number_of_students > 30) THEN
SHOW “Too many students!”
ELSE
SHOW “Not too many students.”
ENDIF

Code for If…Then…Else statement

Example Output

Code example output