The simplest program lists commands one after another in a sequence, much like following the steps of a recipe. Follow a recipe step by step and you always create the same dish. If a program lists commands step by step, the computer always produces the same result.
In some cases, you may want a program to do the exact same thing over and over again, such as a simple program to display traffic signals. However for most programs, you want the computer to react to outside data. To make a computer respond in different ways, a program needs to offer two or more choices for the computer to follow.
When you quit a program, the program may ask, "Do you really want to exit?" At this point, the program is giving the computer a choice of two possible actions to take based on your answer.
If you answer Yes, the computer quits the program. If you answer No, the computer keeps running the program.
When a program gives the computer a choice of two or more commands to follow, that's called a branching or decision statement.
All branching statements work the same way:
A comparison operator (or a conditional expression) compares an expression (such as A > 45) to determine a True
or False
value.
The branching statement offers at least two groups of commands for the computer to follow based on whether its comparison is True
or False
.
The simplest branching statement is an IF-THEN
statement, which looks like this:
IF (Something is True or False) THEN Command
The IF-THEN
checks if something is True
or False
:
If something is True
, the IF-THEN
command tells the computer to run exactly one command.
If something is False
, the computer doesn't run this command.
An example of a simple IF-THEN
statement might occur while playing a video game, such as
IF (Player hit the Pause button) THEN Pause game
If the player hit the pause button (True
), you want the computer to pause the game. If the player doesn't hit the pause button (False
), you don't want to pause the game, as shown in Figure 4-1.
The simple IF-THEN
statement runs only one command if a certain condition is True
. What if you want to run two or more commands? In that case, you must define a list of commands to run. A group of commands is sometimes called a block of commands or just a block.
So if you want to run more than one command in an IF-THEN
statement, you must define a block of commands. In the curly bracket language family, such as C, you use curly brackets to define the beginning and end of a block of commands, such as
if (True or False) { command #1 command #2 . . command #3 )
The curly brackets tell the IF-THEN
statement to run the entire block of commands enclosed within the curly brackets.
In other languages, the IF-THEN
statement itself defines the start of a block and then you use an END IF
command to define the end of a block, such as this BASIC language example:
IF (True or False) THEN Command #1 Command #2 . . Command #3 END IF
Finally, some languages, such as Pascal, force you to explicitly declare the beginning and end of a block of commands with the begin
and end
keywords, such as
If (True or False) then Begin Command #1 Command #2 . . Command #3 End;
No matter what language you use, the idea is the same; you must define the beginning and end of all the commands you want the IF-THEN
statement to run.
The simple IF-THEN
statement either runs a command (or block of commands) or it doesn't. But what if you want the computer to take one action if something is True
and a completely different action if something is False
? In that case, you must use a variation — an IF-THEN-ELSE
statement.
The IF-THEN-ELSE
statement gives the computer a choice of two mutually exclusive choices, as shown in Figure 4-2.
Like the simple IF-THEN
statement, the IF-THEN-ELSE
statement can run a single command or a block of commands, such as
if (True or False) then { command #1 command #2 . . command #3 } else { command #1
command #2 . . command #3 )
The IF-THEN-ELSE
statement tells the computer, "Check if something is True
. If so, follow this set of commands. Otherwise, follow this second set of commands."
One problem with the IF-THEN-ELSE
statement is that it only checks a single condition. If that single condition is False
, it always runs its second set of commands, such as
IF (Salary > 100000) THEN TaxRate = 0.45 ELSE TaxRate = 0.30 END IF
In this BASIC language example, if the value of the Salary
variable is greater than 100000, the TaxRate
variable is always set to 0.45.
However, if the Salary
variable isn't greater than 100000 (it's less than or equal to 100000), the ELSE
portion of the IF-THEN-ELSE
statement always sets the TaxRate
variable to 0.30.
The IF-THEN-ELSE
always gives the computer a choice of exactly two, mutually exclusive choices. What if you want to give the computer three or more possible choices? Then you must use the IF-THEN-ELSEIF
statement.
The IF-THEN-ELSEIF
statement offers two advantages over the IF-THEN-ELSE
statement:
You can check a condition for each set of commands.
You can define three or more separate sets of commands for the computer to follow.
Not all programming languages, such as C/C++, offer the IF-THEN-ELSEIF
statement.
The IF-THEN-ELSEIF
statement only runs a command (or block of commands) if some condition is True
, as shown in Figure 4-3.
If every conditional expression is False
, the IF-THEN-ELSE
statement doesn't run any commands. Only if one of its conditional expressions is True
does the IF-THEN-ELSE
statement run exactly one set of commands, such as
IF (Salary > 100000) THEN TaxRate = 0.45 ELSEIF (Salary > 50000) THEN TaxRate = 0.30 END IF
In this example, the computer has three possible choices:
If Salary > 100000, set TaxRate = 0.45.
If Salary > 50000 (but less than 100000), set TaxRate = 0.30.
If Salary <= 50000, do nothing.
The first choice checks if the value of the Salary
variable is greater than 100000, such as 250000. If so, it tells the computer to set the TaxRate
variable to 0.45 and immediately exit out of the entire IF-THEN-ELSEIF
statement.
The second choice only checks if the value of the Salary
variable is greater than 50000. What happens if the Salary
value is 150000? In that case, the first choice runs (Salary > 100000), so this second choice would've never been checked at all.
So although the second choice might seem to run if the Salary
variable is greater than 50000, it really won't run unless Salary > 50000 and the first choice did not run, which means that the Salary
variable must be less than or equal to 100000.
If the value of the Salary
variable is equal or less than 50000, the third choice isn't to run any additional commands at all. Unlike the IF-THEN-ELSE
statement, which always runs at least one set of commands, it's possible for an IF-THEN-ELSEIF
statement to run zero commands.
The advantage of the IF-THEN-ELSEIF
statement is that you can check for multiple conditions and give the computer three or more possible commands (or block of commands) to follow.
To give the computer additional choices, you can just keep tacking on additional ELSEIF
statements, such as
IF (True or False) THEN Command ELSEIF (True or False) THEN Command ELSEIF (True or False) THEN Command END IF
This example now gives the computer three possible sets of commands to follow. If none of these conditions is True
, the IF-THEN-ELSEIF
statement may do nothing.
To keep checking for additional conditions, you have to add additional ELSEIF
statements, such as
IF (True or False) THEN Command ELSEIF (True or False) THEN Command ELSEIF (True or False) THEN Command
ELSEIF (True or False) THEN Command ELSEIF (True or False) THEN Command END IF
This example gives the computer five possible commands (or blocks of commands) for the computer to follow, although it's possible that the computer still follows zero commands.
The IF-THEN-ELSEIF
statement makes the computer run exactly zero or one command (or block of commands), no matter how many additional ELSEIF
statements you add on.
If you want to make sure the IF-THEN-ELSEIF
statement always runs one command (or block of commands), you can tack on the ELSE
statement at the very end, such as
IF (True or False) THEN Command ELSEIF (True or False) THEN Command ELSEIF (True or False) THEN Command ELSEIF (True or False) THEN Command ELSE Command END IF
The ELSE
statement at the end insures that the entire IF-THEN-ELSEIF
statement always runs at least one command. Notice that the ELSE
statement doesn't check a condition because it runs only if all preceding conditions are False
, such as in the following example:
IF (Age > 65) THEN Status = Retired ELSEIF (Age > 20) THEN Status = Working ELSE Status = Bum END IF
In this example, the IF-THEN-ELSEIF
statement gives the computer three possible choices:
Set Status = Retired only if Age > 65
Set Status = Working only if Age > 20 (and less than or equal to 65)
Set Status = Bum only if Age is less than or equal to 20 (which means the other two conditions are False)
To make a decision in an IF-THEN
statement, the computer must use a conditional expression that's either True
or False
. Simple conditional expressions might be
Age = 55 Salary <= 55000 Name <> "John Smith"
You can also use Boolean operators (AND, OR, NOT
, and XOR
) to calculate multiple conditions. Suppose you want to check if a variable falls within a range of values, such as being greater than 20 but less than 65:
In most programming languages, you can type a Boolean operator in lowercase (and), uppercase (AND), or a mix of both upper and lowercase (And). Whichever style you like best, use it consistently throughout your program.
(Age > 20) AND (Age <= 65)
Chapter 3 of this mini-book contains more information about how Boolean operators work.
Table 4-1 shows how different values for the Age
variable determine the value of the preceding Boolean expression.
Table II.4-1. Multiple Boolean Expressions Ultimately Evaluate to a Single True or False Value
Value of the Age Variable | Value of (Age > 20) Expression | Value of (Age <= 65) Expression | Value of Complete Boolean Expression |
---|---|---|---|
15 | False | True | False |
35 | True | True | True |
78 | True | False | False |
Because multiple Boolean expressions ultimately evaluate to a single True
or False
value, you can use multiple Boolean expressions in any IF-THEN
statements, such as
IF (Age > 20) AND (Age <= 65) THEN Status = Working ELSE Status = Bum END IF
There's no limit to the number of Boolean expressions you can combine with Boolean operators. The following is a perfect valid Boolean expression that ultimately evaluates to a single True
or False
value:
(Age > 20) AND (Age <= 65) OR (Age = 72) OR (Name = "John")
The more Boolean expressions you string together with Boolean operators, the more confusing everything gets so it's generally best to use no more than two Boolean expressions and a single Boolean operator (AND, OR, NOT
, or XOR
) at a time.
The IF-THEN-ELSEIF
statement can check multiple conditions and offer two or more choices for the computer to follow. However, the more choices available, the harder the IF-THEN-ELSEIF
statement can be to understand, as shown in the following example:
IF (Age = 65) THEN Status = Retired ELSEIF (Age = 21) THEN Status = Working ELSEIF (Age = 15) THEN Status = Student ELSE Status = Baby END IF
For two or three choices, the IF-THEN-ELSE
statement may be easy to understand, but after you need to offer four or more choices, the IF-THEN-ELSEIF
statement can start getting clumsy. As an alternative, most programming languages offer a SELECT CASE
statement:
SELECT CASE Variable CASE X Command #1 CASE Y Command #2 END SELECT
The SELECT CASE
statement examines a variable and if it's equal to a specific value, the computer follows a command (or block of commands). The preceding SELECT CASE
statement is equivalent to the following IF-THEN
-ELSEIF
statement:
If Variable = X THEN Command #1 ELSEIF Variable = Y THEN Command #2 END IF
The basic idea behind the SELECT CASE
statement is to make it easier to list multiple choices. Both an IF-THEN-ELSEIF
statement and a SELECT CASE
or switch
statement perform the same function; it's just that the SELECT CASE
statement is easier to read and understand.
Consider the following IF-THEN-ELSEIF
statement:
IF (Age = 65) THEN Status = Retired ELSEIF (Age = 21) THEN Status = Working ELSEIF (Age = 15) THEN Status = Student END IF
Rewriting this as a SELECT CASE
statement might look like this:
SELECT CASE Age CASE 65 Status = Retired CASE 21 Status - Working CASE 15 Status = Student END SELECT
As you can see, the SELECT CASE
statement is much less cluttered and easier to read and understand than the IF-THEN-ELSEIF
statement.
Instead of using a SELECT CASE
statement, curly bracket languages, like C, use a switch
statement. The equivalent SELECT CASE
statement written as a switch
statement in C looks like this:
switch (Variable) { case X: Command #1; break; case Y: Command #2; }
A SELECT CASE
statement in BASIC might look like this:
SELECT CASE Age CASE 65 Status = Retired CASE 21 Status - Working CASE 15 Status = Student END SELECT
The equivalent switch
statement in C might look like this:
switch (age) { case 65: status = retired; break; case 21: status = working; break; case 15: status - student; }
The most crucial difference between the SELECT CASE
statement in other languages and the switch
statement in the curly bracket languages is the use of the break
command. If you omit the break
command, the switch
statement doesn't know when to stop running commands.
In the preceding example, the break
command stops the computer from running the other commands stored in the rest of the switch
statement. So if the value of the age
variable is 65, the preceding C program does the following:
Set the status
variable to retired
.
Stop running the switch
statement.
Suppose you didn't include the break
command, as follows:
switch (age) { case 65: status = retired; case 21: status = working; case 15: status - student; }
If the value of the age
variable is 65, this is how this C program works:
Set the status
variable to retired
.
Set the status
variable to working
.
Set the status
variable to student
.
Without the break
command, the curly bracket languages, like C, simply run every command all the way through the switch
statement until it reaches the bottom, which probably isn't what you want.
When using the switch
statement in C (and other curly bracket languages), always use the break
command unless you specifically don't need it, as I explain in the following section.
One major limitation of the SELECT CASE
statement is that it only checks if a variable matches a single value, such as
SELECT CASE Age CASE 65 Status = Retired CASE 21 Status - Working CASE 15 Status = Student END SELECT
This SELECT CASE
statement doesn't do anything unless the value of the Age
variable is exactly 65, 21, or 15. If the value of the Age
variable is 66, 23, or 17, the preceding SELECT CASE
statement does nothing.
Matching exact values may be useful, but sometimes you may want to run the same command (or block of commands) if a variable matches one or more values. For example, rather than match the number 65 exactly, you might want the SELECT CASE
statement to match 65, 66, or 67. In that case, you can write the SELECT CASE
statement like this:
SELECT CASE Age CASE 65, 66, 67 Status = Retired CASE 21 Status - Working CASE 15 Status = Student END SELECT
With a switch
statement in a curly bracket language, like C, you can do the following:
switch (age) { case 67: case 66: case 65: status = retired; break; case 21: status = working; break; case 15: status - student; }
By not using the break
command if the value of the age
variable is 67 or 66, the computer just continues down, line by line, until it runs the command if the age
variable was 65. Then it hits the break
command directly under the status = retired
command and stops.
The switch
command can be easier to read because all the matching values (67, 66, 65, 21, and 15) appear in a vertical column. The equivalent SELECT CASE
statement can be slightly harder to read because all the values don't line up in a single vertical column.
The problem with the SELECT CASE
statement is that it needs to match a value exactly. Although you could type in all possible values to match, that can get clumsy, as in the following that sets Status = retired
if the Age
variable is between 65 and 75:
SELECT CASE Age CASE 65, 67, 68, 69, 70, 71, 72, 73, 74, 75 Status = Retired CASE 21 Status - Working CASE 15 Status = Student END SELECT
To avoid this problem, many languages let you check for a range of values. So if you want to check if a variable is equal or greater than 65 and less than or equal to 75, you could define the range of 65 TO 75 like this:
SELECT CASE Age CASE 65 TO 75 Status = Retired CASE 21 Status - Working
CASE 15 Status = Student END SELECT
The curly bracket languages, like C and C++, don't let you check for a range of values in a switch
statement.
Listing a range of values can be useful, but what if there's no upper (or lower) limit? For example, anyone over the age of 65 might be considered retired, so you need to use a comparison operator to check a variable with a value, such as Age >= 65.
To use a comparison operator in a SELECT CASE
statement, languages such as BASIC use the following syntax:
SELECT CASE Age CASE IS >= 65 Status = Retired CASE 21 TO 64 Status - Working CASE 15 Status = Student END SELECT
In this example, the first part of the SELECT CASE
statement tells the computer to check if the value in the Age
variable is (note the IS
keyword) >= 65.
The second part of the SELECT CASE
statement checks if the Age
variable falls within the range of 21 to 64.
The third part of the SELECT CASE
statement checks if the Age
variable is exactly equal to 15.
As you can see, each part of a SELECT CASE
statement can check a value by matching it exactly, checking a range of values, or using a comparison operator.
The curly bracket languages, like C and C++, don't let you use comparison operators in a switch
statement.
It's possible for a SELECT CASE
statement to run zero commands if the CASE
statement can't match a variable to any specific value, such as
SELECT CASE Age CASE 65 Status = Retired CASE 21 Status - Working CASE 15 Status = Student END SELECT
The preceding SELECT CASE
statement doesn't do anything if the Age
variable is 13, 25, or 81. To make sure the SELECT CASE
statement always runs at least one command, you must add the ELSE
statement, such as
SELECT CASE Age CASE 65 Status = Retired CASE 21 Status - Working CASE 15 Status = Student ELSE Status = Bum END SELECT
In this example, if the value of the Age
variable is 24
or 5
, it doesn't match any of the specific values, so the command under the ELSE
statement runs instead (Status = Bum
).
Instead of using the ELSE
statement, the curly bracket languages use a default
statement, such as
switch (age) { case 65: status = retired; break; case 21: status = working; break; case 15: status - student; break; default: status = bum; }
Both the ELSE
and default
statements force the SELECT CASE
(or switch
) statement to always do something.
As a general rule, use the IF-THEN
statements for making the computer choose one or more commands (or blocks of commands). If you need the computer to choose from three or more commands (or blocks of commands), the SELECT CASE
(switch
) statement may be easier to read and write instead.
Branching simply gives the computer multiple options to use when running. By accepting outside information and comparing its value, a branching
statement can help the computer choose an appropriate response out of many possible responses.