Professional Documents
Culture Documents
Pages 2
Pages 2
Pages 2
Conditionals
just as one reads in English. Moreover, in most programming languages, each statement
executes completely before the next statement begins. A visualization of this sequential
control flow can be found in the control flow diagram in Figure 3.1(a).
However, it is often necessary for a program to “make decisions.” Some segments of code
may need to be executed only if some condition is satisfied. The if statement is a control
structure that allows us to write a snippet of code predicated on a logical statement.
The code executes if the logical statement is true, and does not execute if the logical
statement is false. This control flow is featured in Figure 3.1(b)
An example using pseudocode can be found in Algorithm 3.1. The use of the keyword
“if” is common to most programming languages. The logical statement associated with
the if-statement immediately follows the “if” keyword and is usually surrounded by
parentheses. The code block immediately following the if-statement is bound to the
if-statement.
1 if (hconditioni) then
2 Code Block
3 end
As in the flow chart, if the hconditioni evaluates to true, then the code block bound to
the statement executes in its entirety. Otherwise, if the condition evaluates to false, the
code block bound to the statement is skipped in its entirety.
A simple if-statement can be viewed as a “do this if and only if the condition holds.”
Alternatively, “if this condition holds do this, otherwise don’t.” In either case, once the
if-statement finishes execution, the program returns to the normal sequential control
flow.
An if-statement allows you to specify a code segment that is executed or is not executed.
An if-else statement allows you to specify an alternative. An if-else statement allows you
to define a condition such that if the condition is true, one code block executes and if
the condition is false, an entirely different code block executes.
The control flow of an if-else statement is presented in Figure 3.2. Note that Code
Block A and Code Block B are mutually exclusive. That is, one and only one of them is
executed depending on the truth value of the hconditioni. A presentation of a generic
if-else statement in our pseudocode can be found in Algorithm 3.2
76
3.3. The If-Else Statement
Statement 1
true Code
hconditioni
Block
Statement 2
false
Remaining
Statement 3 Program
Figure 3.1.: Control flow diagrams for sequential control flow and an if-statement. In
sequential control, statements are executed one after the other as they are
written. In an if-statement, the normal flow of control is interrupted and a
Code Block is only executed if the given condition is true, otherwise it is
not. After the if-statement, normal sequential control flow resumes.
77
3. Conditionals
true Code
hconditioni
Block A
false
Code
Block B
Remaining
Program
Just as with an if-statement, the keyword “if” is used. In fact, the if-statement is simply
just an if-else statement with the else block omitted (equivalently, we could have defined
an empty else block, but since it would have no effect, a simple if-statement with no
else block is preferred). It is common to most programming languages to use the “else”
keyword to denote the else block of code. Since there is only one hconditioni to evaluate
and it can only be true or false, it is not necessary to specify the conditions under which
the else block executes. It is assumed that if the hconditioni evaluates to false, the else
block executes.
As with an if-statement, the block of code associated with the if-statement as well as the
block of code associated with the else-statement are executed in their entirety or not at
all. Whichever block of code executes, normal flow of control returns and the remaining
program continues executing sequentially.
An if-statement allows you to define a “do this or do not” and an if-else statement allows
you to define a “do this or do that” statement. Yet another generalization is an if-else-if
statement. Using such a statement you can define any number of mutually exclusive
code blocks.
78
3.4. The If-Else-If Statement
1 if (hconditioni) then
2 Code Block A
3 else
4 Code Block B
5 end
To illustrate, consider the case in which we have exactly three mutually exclusive
possibilities. At a particular university, there are three possible semesters depending
on the month. January through May is the Spring semester, June/July is the Summer
semester, and August through December is the Fall semester. These possibilities are
mutually exclusive because it cannot be both Spring and Summer at the same time
for example. Suppose we have the current month stored in a variable named month.
Algorithm 3.3 expresses the logic for determining which semester it is using an if-else-if
statement.
Let’s understand how this code works. First, the “if” and “else” keywords are used
just as the two previous control structures, but we are now also using the “else if”
keyword combination to specify an additional condition. Each condition, starting with
the condition associated with the if-statement is checked in order. If and when one of the
conditions is satisfied (evaluates to true), the code block associated with that condition
is executed and all other code blocks are ignored.
Each of the code blocks in an if-else-if control structure are mutually exclusive. One
and only one of the code blocks will ever execute. Similar to the sequential control flow,
the first condition that is satisfied is the one that is executed. If none of the conditions
is satisfied, then the code block associated with the else-statement is the one that is
executed.
In our example, we only identified three possibilities. You can generalize an if-else-if
statement to specify as many conditions as you like. This generalization is depicted in
79
3. Conditionals
true
Code
if(hcondition 1i) hcondition 1i
Block A
false
true
Code
else if(hcondition 2i) hcondition 2i
Block B
false
true
Code
else if(hcondition 3i) hcondition 3i
Block C
false
.. ..
. .
false
true
Code
else if(hcondition ni) hcondition ni
Block N
false
Code
else
Block M
Remaining
Program
Figure 3.3.: Control Flow for an If-Else-If Statement. Each condition is evaluated in
sequence. The first condition that evaluates to true results in the corre-
sponding code block being executed. After executing, the program continues.
Thus, each code block is mutually exclusive: at most one of them is executed.
80
3.4. The If-Else-If Statement
Algorithm 3.4 and visualized in Figure 3.3. Similar to the if-statement, the else-statement
and subsequent code block is optional. If omitted, then it may be possible that none of
the code blocks is executed.
The design of if-else-if statements must be done with care to ensure that your statements
are each mutually exclusive and capture the logic you intend. Since the first condition
that evaluates to true is the one that is executed, the order of the conditions is important.
A poorly designed if-else-if statement can lead to bugs and logical errors.
As an example, consider describing the loudness of a sound by its decibel level in Algorithm
3.5.
1 if decibel ≤ 70 then
2 comf ort ← “intrusive”
3 else if decibel ≤ 50 then
4 comf ort ← “quiet”
5 else if decibel ≤ 90 then
6 comf ort ← “annoying”
7 else
8 comf ort ← “dangerous”
9 end
Suppose that decibel = 20 which should be described as a “quite” sound. However, in the
algorithm, the first condition, decibel ≤ 70 evaluates to true and the sound is categorized
as “intrusive”. The bug is that the second condition, decibel ≤ 50 should have come first
in order to capture all decibel levels less than or equal to 50.
Alternatively, we could have followed the example in Algorithm 3.3 and completely
81
3. Conditionals
specified both lower bounds and upper bounds in our condition. For example, the
condition for “intrusive” could have been
However, doing this is unnecessary if we order our conditions appropriately and we can
potentially write simpler conditions if we remember the fact that the if-else-if statement
is mutually exclusive.
E ? X : Y
min = ( (a < b) ? a : b );
If a < b is true, then min will take on the value a. Otherwise it will take on the value b
(in which case a ≥ b and so b is minimal). Most programming languages support this
special syntax as it provides a nice convenience (yet another example of syntactic sugar).
3.6. Examples
Consider the problem of computing a receipt for a meal. Suppose we have the subtotal
cost of all items in the meal. Further, suppose that we want to compute a discount
(senior citizen discount, student discount, or employee discount, etc.). We can then apply
the discount, compute the sales tax, and sum a total, reporting each detail to the user.
To do this, we first prompt the user to enter a subtotal. We can then ask the user if
there is a discount to be computed. If the user answers yes, then we again prompt them
for an amount (to allow different types of discounts). Otherwise, the discount will be
82
3.6. Examples
zero. We can then proceed to calculate each of the amounts above. To do this we’ll need
an if-statement. We could also use a conditional statement to check to see if the input
makes sense: we wouldn’t want a discount amount that is greater than 100%. The full
algorithm is presented in Algorithm 3.6.
Recall that dividing by zero is an invalid operation in most programming languages (see
Section 2.3.5). Now that we have a means by which numerical values can be checked, we
can prevent such errors entirely.
Suppose that we were going to compute a quotient of two variables x/y. If y = 0, this
would be an invalid operation and lead to undefined, unexpected or erroneous behavior.
However, if we checked whether or not the denominator is zero before we compute the
quotient then we could prevent such errors. We present this idea in Algorithm 3.7.
1 if y 6= 0 then
2 q ← x/y
3 end
83
3. Conditionals
Suppose we have two students, student A and student B and we want to compare them:
we want to determine which one should be placed first in a list and which should be
placed second. For this exercise let’s suppose that we want to order them first by their
last names (so that Anderson comes before Zadora). What if they have the same last
name, like Jane Smith and John Smith? If the last names are equal, then we’ll want to
order them by their first names (Jane before John). If both their first names and last
names are the same, we’ll say either order is okay.
Names will likely be represented using strings, so let’s say that <, = and > apply to
strings, ordering them lexicographically (which is consistent with alphabetic ordering).
We’ll first need to compare their last names. If equal, then we’ll need another conditional
construct. This is achieved by nesting conditional statements as in Algorithm 3.8.
84
3.6. Examples
Another example in which there are several cases that have to be considered is computing
an income tax liability using marginal tax brackets. Table 3.6 contains the 2014 US
Federal tax margins and marginal rates for a married couple filing jointly based on the
Adjusted Gross Income (income after deductions).
Table 3.6.: 2014 Tax Brackets for Married Couples Filing Jointly
In addition, one of the tax credits (which offsets tax liability) tax payers can take is the
child tax credit. The rules are as follows:
• If the AGI is $110,000 or more, they cannot claim a credit (the credit is $0)
• Each child is worth a $1,000 credit, however at most $3,000 can be claimed
• The credit is not refundable: if the credit results in a negative tax liability, the tax
liability is simply $0
As an example: suppose that a couple has $35,000 AGI (placing them in the second tax
bracket) and has two children. Their tax liability is
However, the two children represent a $2,000 refund, so their total tax liability would be
$2,342.50.
Let’s first design some code that computes the tax liability based on the margins and
rates in Table 3.6. We’ll assume that the AGI is stored in a variable named income.
Using a series of if-else-if statements as presented in Algorithm 3.9, the variable tax will
85
3. Conditionals
We can then compute the amount of a tax credit and adjust the tax accordingly by using
similar if-else-if and if-else statements as in Algorithm 3.10.
86