Lecture 7 - If-Else (Selection)


Home > Lectures > Lecture07

Objectives

Contents


1. Sequence Revisited

So far the problems encountered have required an algorithm that specified a sequence of steps, which were performed one after the other from top to bottom. An example of this is the algorithm for calculating the best value item at a supermarket.

Problem: Electricity Usage

The ABC Electricity Company requires a program to calculate the bills for electricity usage. The following cost structure is used: All customers are charged a $50 access fee regardless of usage. Customers are charged $0.20 per kilowatt (kW) of electricity used. Write a program to allow a user to input the electricity used by a customer in kilowatts and then display the amount owed by the customer.

Example Runs

Run
Electricity Used (kW) ? 100
Amount Owed = $70

A solution is:

Check understanding

Electricity Used = 100.   AmountOwed = $50 + 100 * $0.20 = $50 + $20 = $70

Defining Diagram

Inputs Processing Outputs
electricityUsed Input electricityUsed
Calculate amountOwed
Display amountOwed
amountOwed

Pseudo Code

calcElectrictyCost()
    Input electricityUsed
    amountOwed = 50 + electricityUsed * 0.20
    Display amountOwed
STOP

Data Dictionary

Name Data Type Description
amountOwed Double The amount owed by the customer in $
electricityUsed Double The amount of electricity used by the customer in kilowatts (kW)

The above logic is a sequence of instructions, as shown below. The instructions are from the top to the bottom, one after the other, with each instruction executed once.

2. Selection using IF

However...

The government decides that heavy users of electricity should contribute towards to a fund to help reduce green house gases. The program must be changed to have a surcharge of $80 for customers that use 1000kW or more.

New Problem Description

The ABC Electricity Company requires a program to calculate the bills for electricity usage. The following cost structure is used: All customers are charged a $50 access fee regardless of usage. Customers are charged $0.20 per kilowatt (kW) of electricity used. If customers use 1000kW or more, then they must pay a surcharge of $80. Write a program to allow a user to input the electricity used by a customer in kilowatts and then display the amount owed by the customer and the surcharge if there is one.

Example Runs

Run
Electricity Used (kW) ? 100
Amount Owed = $70
Run
Electricity Used (kW) ? 1000
Surcharge = $80
Amount Owed = $330

This problem can no longer be solved as a sequence of instructions.

This problem requires different operations to be performed depending on some condition. Therefore simply performing a sequence of operations one after would not be suitable. The surcharge is to be applied only under some circumstances. Therefore in the algorithm this circumstance must be detected and different processing occur in this case. This is called Selection - there is more than one possible logic path.

Check understanding

Conditional Part:

electricity Usage < 1000 kW no surcharge
electricity Usage >= 1000 kW $80 surcharge

Non Conditional Part:

Equally important to the conditional parts of the problems are the non-conditional parts - under all circumstances the electricity used is input, the $50 access fee is charged, $0.20 per kilowatt is charged and the amount owed is displayed.

Calculations

Electricity Used = 100.  
AmountOwed = $50 + 100 * $0.20 = $50 + $20 = $70

Electricity Used = 1000. 
AmountOwed = $50 + 1000 * $0.20 + $80 = $50 + $200 + $80 = $330

Defining Diagram

The only difference here is the calculation of the surcharge. The main actions required are listed under processing, the fact that the surcharge only happens under some circumstances is not relevant - at this level of detail only the main actions are necessary.

Inputs Processing Outputs
electricityUsed Input electricityUsed
Determine surcharge
Calculate amountOwed
Display surcharge, amountOwed
amountOwed
surcharge

Outline the Solution

This step hasn't been necessary for earlier problems as they have been too simple. Defining Diagrams show a high level outline of the processing required. Further detail on the processing required can be specified in this step, such as conditions and repetition.

It can be useful to represent conditions as a table. This helps determine the relationship between values, and to check that all possible values have been catered for. In the table below it can be seen that the surcharge can be determined solely from the usage, and it is also easy to check that all possible values of usage and surcharge are catered for.

The following table shows the relationship between electricity usage and the surcharge.

  electricityUsage
 < 1000 >= 1000
surcharge $0 $80

The condition could be represented diagrammatically as follows:

Pseudo Code

calcElectrictyCost()
    Input electricityUsed
    amountOwed = 50 + electricityUsed * 0.20
    IF electricityUsed >= 1000 THEN
        surcharge = 80
        Display surcharge 
        amountOwed = amountOwed + surcharge
    ENDIF
    Display amountOwed
STOP

Data Dictionary

Name Data Type Description
amountOwed Double The amount owed by the customer in $
electricityUsed Double The amount of electricity used by the customer in kilowatts (kW)
surcharge Integer The surcharge amount in $

Desk Check

1  calcElectrictyCost
2      Input electricityUsed
3      amountOwed = 50 + electricityUsed * 0.20
4      IF electricityUsed >= 1000 THEN
5          surcharge = 80
6          Display surcharge 
7          amountOwed = amountOwed + surcharge
8      ENDIF
9      Display amountOwed
10 STOP

Inputs: electricityUsed = 100. Correct Results: amountOwed = $70

Line Number amountOwed electricityUsed surcharge Conditions Input/Output
1          
2   100     electricityUsed ? 100
3 50 + 100 * 0.20 = 70        
4       100 >= 1000 ? is F  
8          
9         amount Owed = 70
10          

Inputs: electricityUsed = 1000. Correct Results: Surcharge = 80; amountOwed = $330

Line Number amountOwed electricityUsed surcharge Conditions Input/Output
1          
2   1000     electricity Used ? 1000
3 50 + 1000 * 0.20 = 250        
4       1000 >= 1000 ? is T  
5     80    
6         surcharge = 80
7 250 + 80 = 330        
8          
9         amount Owed = 330
10          

Discussion

4      IF electricityUsed >= 1000 THEN
5          surcharge = 80
6          Display surcharge 
7          amountOwed = amountOwed + surcharge
8      ENDIF

The condition on line 4 is either True or False depending on the value of electricityUsed.
If the result of the condition is True (e.g. electricityUsed was 1000kW) then lines 5-8 are executed and a surcharge applies.
If the result of the condition is False (e.g. electricityUsed was 100kW) then execution jumps to line 8 (everything between the THEN and ENDIF is skipped.

Pseudo Code for IF-ENDIF Statements

Everything between the THEN and ENDIF is to be executed if the condition is True, otherwise the operations between THEN and ENDIF are skipped. The ENDIF is needed to show the end points of the statements that are conditional. Everything inside the IF is indented (spaced in) to make it easier to see what statements are part of the IF, and to highlight that the statements will only be executed some of the time.

Format

IF condition THEN
    statement
    statement
    ...
ENDIF
 
Example

IF lineNumber > 50 THEN
    Display ""
    Display "Student Number", "Student Name"
    lineNumber = 0
ENDIF

The logic of an IF (without an ELSE) can be represented diagrammatically as follows:

Write the Program

' Name: calcElectricityCost
' Purpose: Calculate the cost of electricity for a customer
' Author: Tim Whitfort
Option Compare Database
Option Explicit
Sub Main()

    ' Declare variables
    Dim amountOwed As Double       ' Cost of the electricity in $
    Dim electricityUsed As Double  ' Amount of electricity used in kW
    Dim surcharge As Long          ' Surcharge if too much electricity is used  

    ' Input the amount of electricity used in kW
    electricityUsed = InputBox("Electricity used (kW) ? ")

    ' Calculate the standard amount owed by the customer
    amountOwed = 50 + electricityUsed * 0.20
    ' Add the surcharge on (if applicable)
    If electricityUsed >= 1000 Then
        surcharge = 80
        Debug.Print "Surcharge = $"; surcharge 
        amountOwed = amountOwed + surcharge
    End If

    ' Display the amount owed by the customer for electricity
    Debug.Print "Amount Owed = $"; Format(amountOwed, "0.00")

End Sub

Basic Code for If-End If Statements

Format

If condition Then
    statement
    statement
    ...
End If

Example

If lineNumber > 50 Then
    Debug.Print ""
    Debug.Print "Student Number", "Student Name"
    lineNumber = 0
End If
 

3. Comparison Operators

Comparison operators are used to compare two values. The comparison operators used in conditions for both Pseudo Code and Basic are:

Operator Meaning Example
= Equal to custName = "Anne"
<> Not equal to i <> 0
< Less than count < 10
<= Less than or equal to a <= b
> Greater than length > width
>= Greater than or equal to x1 >= x2

4. Detecting Selection

When reading the problem note whether a decision needs to be made in the logic. Phrases that indicate choice like "if ...", "under some circumstances", "occasionally", "else", "otherwise", "sometimes", "optionally" or suggest alternatives such as "this or that" or different things happening depending on the value of an input indicate that a choice (selection) is taking place. Examine how many alternatives are involved - does each value (or range of values) require different actions? Are the conditions dependent on more than one variable? Is a table presented suggesting alternatives that must be considered in processing? Roughly outline a solution and test whether it covers the cases/situations mentioned in the problem.

5. Selection Using IF-ELSE

The above problem required something special to be done if the condition was True, and nothing to be done when the condition was False.

Some problems require different something to be done if the IF condition is True, and something else to be done if the condition is False.

Problem Description

Calculate the fees payable on a credit card purchase. A fee of 4% of the purchase price is charged for transactions under $100 and 3% of the purchase price for transactions of $100 or more.

Example Runs

Run
Purchase price ($) ? 10
Fees = $0.40  Total cost = $10.40
Run
Purchase price ($) ? 100
Fee = $3.00  Total cost = $103.00

Check understanding

Conditional Part:

 

 

Non Conditional Part:

 

 

Example calculations

 

 

Defining Diagram

Inputs Processing Output
 

 

 

 

   

Outline the Solution

 

 

 

 

 

Pseudo Code

 

 

 

 

 

 

Data Dictionary

Name Data Type Description
     
     
     

Desk Check

Inputs: purchasePrice = 10; Correct Results: transactionFee = 0.40; totalCost = 10.40

Line Number purchasePrice transactionFee totalCost Conditions Input/Output
           
           
           
           
           
           
           
           

Inputs: purchasePrice = 100; Correct Results: transactionFee = 3.00; totalCost = 103.00

Line Number purchasePrice transactionFee totalCost conditions Input/Output
           
           
           
           
           
           
           
           
           

Discussion

 

 

 

 

 

Pseudo Code for an IF-ELSE-ENDIF Statements

Format

IF condition THEN
    statement
    statement
    ...
ELSE
    statement
    statement
    ...
ENDIF

Example

IF mark >= 50 THEN
    Display "pass"
    grade = "P"   

ELSE
    Display "fail"
    grade = "N"   

ENDIF

The logic of an IF-ELSE can be represented diagrammatically as follows:

Write the Program

' Name: calcFees
' Purpose: Calculate the transaction fee on a credit card purchase
' Author: Tim Whitfort

Option Compare Database
Option Explicit

Sub Main()

    ' Declare variables
    Dim purchasePrice As Double ' The purchase price of the item in $
    Dim transactionFee As Double ' The cost of the purchase including the fee, in $
    Dim totalCost As Double ' The transactions fee payable on the purchase in $

    ' Input the purchase price
    purchasePrice = InputBox("Purchase price ($) ? ")

    ' Calculate the transaction fee on the purchase
    If purchasePrice < 100 Then
        transactionFee = purchasePrice * 4 / 100
    Else
        transactionFee = purchasePrice * 3 / 100
    End If
    totalCost = purchasePrice + transactionFee

    ' Display formatted to 2 decimal places
    ' Underscore used to continue statement over more than one line
    Debug.Print "Fee $"; Format(transactionFee, "0.00"); _
    " Total cost $"; Format(totalCost, "0.00")

End Sub

Basic Code for If-Else-End If Statements

Format

If condition Then
    statement
    statement
    ...
Else
    statement
    statement
    ...
End If

Example

If mark >= 50 Then
    Debug.Print "Pass"
    grade = "P"   

Else
    Debug.Print "fail"
    grade = "N"   

End If


Key Points

Further Reading


Previous Lecture | Lecture Index | Next Lecture | Tutorial
Last modified 04-Jan-2005 by Tim Whitfort.
Copyright © 2003-2005
Tim Whitfort