Pages 2

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

3.

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

Algorithm 3.1: An if-statement

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.

3.3. The If-Else Statement

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

(a) Sequential Flow Chart (b) If-Statement Flow Chart

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

Figure 3.2.: An if-else Flow Chart

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.

3.4. The If-Else-If Statement

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

Algorithm 3.2: An if-else Statement

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.

1 if (month ≥ January) And (month ≤ May) then


2 semester ← “Spring”
3 else if (month > May) And (month ≤ July) then
4 semester ← “Summer”
5 else
6 semester ← “Fall”
7 end

Algorithm 3.3: Example 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.

1 if (hcondition 1i) then


2 Code Block A
3 else if (hcondition 2i) then
4 Code Block B
5 else if (hcondition 3i) then
6 Code Block C
7 ...
8 else
9 Code Block
10 end

Algorithm 3.4: General If-Else-If Statement

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

Algorithm 3.5: If-Else-If Statement With a Bug

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

(decibel > 50) And (decibel ≤ 70)

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.

3.5. Ternary If-Else Operator

Another conditional operator is the ternary if-then-else operator. It is often used to


write an expression that can take on one of two values depending on the truth value of a
logical expression. Most programming languages support this operator which has the
following syntax:

E ? X : Y

Here, E is a Boolean expression. If E evaluates to true, the statement takes on the


value X which does not need to be a Boolean value: it can be anything (an integer,
string, etc.). If E evaluates to false, the statement takes on the value Y .

A simple usage of this expression is to find the minimum of two values:

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

3.6.1. Meal Discount

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.

1 Prompt the user for a subtotal


2 subT otal ← read input from user
3 discountP ercent ← 0
4 Ask the user if they want to apply a discount
5 hasDiscount ← get user input if hasDiscount = “yes” then
6 Prompt the user for a discount amount
7 discountP ercent ← read user input
8 end
9 if discountP ercent > 100 then
10 Error! Discount cannot be more than 100%
11 end
12 discount ← subT otal × discountP ercent
13 discountT otal ← subT otal − discount
14 tax ← taxRate × discountT otal
15 grandT otal ← discountT otal + tax
16 output subT otal, discountT otal, tax, grandT otal to user

Algorithm 3.6: A simple receipt program

3.6.2. Look Before You Leap

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

Algorithm 3.7: Preventing Division By Zero Using an If Statement

83
3. Conditionals

This approach to programming is known as defensive programming. We are essentially


checking the conditions for an invalid operation before performing that operation. In
the example above, we simply chose not to perform the operation. Alternatively, we
could use an if-else statement to perform alternate operations or handle the situation
differently. Defensive programming is akin to “looking before leaping”: before taking a
potentially dangerous step, you look to see if you are at the edge of a cliff, and if so you
don’t take that dangerous step.

3.6.3. Comparing Elements

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.

1 if A’s last name < B’s last name then


2 output A comes first
3 else if A’s last name > B’s last name then
4 output B comes first
5 else
//last names are equal, so compare their first names
6 if A’s first name < B’s first name then
7 output A comes first
8 else if A’s first name > B’s first name then
9 output B comes first
10 else
11 Either ordering is fine
12 end
13 end

Algorithm 3.8: Comparing Students by Name

84
3.6. Examples

3.6.4. Life & Taxes

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).

AGI is over But not over Tax


0 $18,150 10% of the AGI
$18,150 $73,800 $1,815 plus 15% of the AGI in excess of
$18,150
$73,800 $148,850 $10,162.50 plus 25% of the AGI in excess of
$73,800
$148,850 $225,850 $28,925 plus 28% of the AGI in excess of
$148,850
$225,850 $405,100 $50,765 plus 33% of the AGI in excess of
$225,850
$405,100 $457,600 $109,587.50 plus 35% of the AGI in excess
of $405,100
$457,600 — $127,962.50 plus 39.6% of the AGI in excess
of $457,600

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

$1, 815 + 0.15 × ($35, 000 − $18, 150) = $4, 342.50

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

contain our initial tax liability.

1 if income ≤ 18, 150 then


2 tax ← .10 · income
3 else if income > 18, 150 And income ≤ 73, 800 then
4 tax ← 1, 815 + .15 · (income − 18, 150)
5 else if income > 73, 800 And income ≤ 148, 850 then
6 tax ← 10, 162.50 + .25 · (income − 73, 800)
7 else if income > 148850 And income ≤ 225, 850 then
8 tax ← 28, 925 + .28 · (income − 148, 850)
9 else if income > 225, 850 And income ≤ 405, 100 then
10 tax ← 50, 765 + .33 · (income − 225, 850)
11 else if income > 405, 100 And income ≤ 457, 600 then
12 tax ← 109, 587.50 + .35 · (income − 405, 100)
13 else
14 tax ← 127, 962.50 + .396 · (income − 457, 600)
15 end

Algorithm 3.9: Computing Tax Liability with If-Else-If

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.

1 if income ≥ 110, 000 then


2 credit ← 0
3 else if numberOf Children ≤ 3 then
4 credit ← numberOf Children ∗ 1, 000
5 else
6 credit ← 3000
7 end
//Now adjust the tax, taking care that its a nonrefundable credit
8 if credit > tax then
9 tax ← 0
10 else
11 tax ← (tax − credit)
12 end

Algorithm 3.10: Computing Tax Credit with If-Else-If

86

You might also like