Lecture 14 - Repetition - Tables, Menus & Nested Control Structures


Home


Objectives

Contents


1. Displaying Tables of Values

Sometimes repetition is implied by the problem rather than explicitly stated. For example:

Problem Description

Display a table of values showing the balance of a bank account with interest compounding yearly.

Example Program Run

Run
Initial balance ($) ? 1000
Interest rate (%) ? 7

Year          Interest ($)  Balance ($)
 0                          1,000.00
 1              70.00       1,070.00
 2              74.90       1,144.90
 3              80.14       1,225.04
 4              85.75       1,310.79
 5              91.76       1,402.55
 6              98.18       1,500.73
 7             105.05       1,605.78
 8             112.40       1,718.18
 9             120.27       1,838.45
 10            128.69       1,967.14
Discussion

Is this repetition?

Look for any patterns:

Defining Diagram

Inputs Processing Output
initialBalance, interestRate Input initialBalance, interestRate
Calculate year
Calculate interest
Calculate balance
Display year, interest, balance
year, interest, balance

Outline the Solution

Pseudo Code

compoundingInterest()
    Input initialBalance, interestRate
    balance = initialBalance
    Display year, balance
    FOR year = 1 TO 10
        interest = balance * interestRate / 100
        balance = balance + interest     
        Display year, interest, balance
    ENDFOR
STOP

Data Dictionary

Name Data Type Description
balance Double The current balance of the account in $
initialBalance Integer The starting balance of the account in $
interest Double The interest earned in the current year
interestRate Double The interest rate payable on the account as a %
year Integer The current year number

Desk Check

Access Basic Code

' Name: compoundingInterest
' Purpose: Calculate the balance of an account with compounding interest
' Author: Tim Whitfort
 
Option Compare Database
Option Explicit
 
Sub Main()
 
    ' Declarations
    Dim balance As Double
    Dim initialBalance As Long
    Dim interest As Double
    Dim interestRate As Double
    Dim year As Long
 
    initialBalance = InputBox("Initial balance ($) ? ")
    interestRate = InputBox("Interest rate (%) ? ")
    balance = initialBalance
    
    ' Display column headings
    Debug.Print "Year", "Interest ($)", "Balance ($)"
    Debug.Print 0, , Format(balance, "#,0.00")

    ' Display table of values
    For year = 1 To 10
        interest = balance * interestRate / 100
        interest = Round(interest, 2) ' Round to 2 decimal places
        balance = balance + interest
        ' Format interest to 2 decimal places and right justify. Format balance to 2 decimal places
        Debug.Print year, Format(Format(interest, "0.00"), "@@@@@@@"), Format(balance, "#,0.00")
    Next

End Sub

2. Nested Control Structures

Calculations, assignment, Input, Display, IF, FOR, WHILE are known as statements. IF, FOR and WHILE are a special type of statement, known as control structures.

IF, FOR or WHILE statements can contain other statements including other IF, FOR or WHILE statements. A FOR loop inside a FOR loop is a called nested FOR loop.

Example 1: Menus

Menus are used to display a list of options from which the user can select one at a time and some appropriate action is performed. Simple menus can be implemented using a loop containing nested IFs.

The general logic for a menu is as follows:

menu()
    choice = ""
    WHILE menuChoice <> exitChoice
        Display menu
        Input choice
        IF menuChoice = choice1 THEN
            do something appropriate for choice 1
        ELSE
            IF menuChoice = choice2 THEN
                do something appropriate for choice 2
            ELSE
                IF menuChoice = choice-n THEN
                    do something appropriate for choice n
                ELSE
                    IF menuChoice <> exit-choice THEN
                        Display invalid option
                    ENDIF
                ENDIF
            ENDIF
        ENDIF
    ENDWHILE
STOP

Problem Description

Write a program that performs transactions on a bank account. The account balance if initially zero. The transactions are Balance (display the balance of the account), D (make a deposit to the account) and W (make a withdrawal from the account). X is used to indicate the user wishes to exit the program.

Example Program Run

Run
Transaction Menu
  B. Balance
  D. Deposit
  W. Withdraw
  X. Exit
Choice ? B

Balance = $0.00

Transaction Menu
  B. Balance
  D. Deposit
  W. Withdraw
  X. Exit
Choice ? D

Deposit amount ? 100

Transaction Menu
  B. Balance
  D. Deposit
  W. Withdraw
  X. Exit
Choice ? D

Deposit amount ? 50

Transaction Type
  B. Balance
  D. Deposit
  W. Withdraw
  X. Exit
Choice ? B

Balance = $150.00

Transaction Type
  B. Balance
  D. Deposit
  W. Withdraw
  X. Exit
Choice ? X

Defining Diagram

Inputs Processing Output
transType
amount
Display transaction menu
Input transType
Input amount
Perform transaction
balance

Outline the Solution

Pseudo Code

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Data Dictionary

Name Data Type Description
amount Double The amount of the deposit or withdrawal
balance Double The current account balance in $
transType String The type of transaction. "B"=Balance, "D"=Deposit, "W"=Withdrawal, "X"=eXit

Example 2: Membership Fees

Problem Description

The following is a modification of a problem done in earlier lectures to calculate the membership fees for a club member.

The enhancements are:

The logic has similarities to the banking program above. A point of difference is that the menu option is validated, so the nested IF statement does not need to allow for invalid values.

Defining Diagram

Inputs Processing Output
membershipType Input membershipType
Check membershipType is correct
Determine the membershipFee
Determine the membershipName
Total the membershipFees
Display membershipName, membershipFee
Display totalFees
membershipName
membershipFee
totalFees

Outline the Solution

Pseudo Code

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Discussion

 
 
 
 

Data Dictionary

Name Data Type Description
membershipFee Double The membership fee for a club member.
membershipName String The full name of the membership type: Full, Junior or Life
membershipType String The type of membership in the club. Values: F=Full, J=Junior, L=Life and X=Exit.
totalFees Double The total membership fees in $.

Desk Check

Access Basic Code

' Name: calcMembershipFees
' Purpose: Calculate the fees for club members
' Author: Tim Whitfort

Option Compare Database
Option Explicit
 
Sub Main()
 
   Dim membershipFee As Double  ' The membership fee for a club member.
   Dim membershipName As String ' The full name of the membership type: Full, Junior or Life
   Dim membershipType As String ' The type of membership in the club. Values: F=Full, J=Junior, L=Life and 
    X=Exit.
   Dim totalFees As Double ' The total membership fees in $.
 
   ' Initially the total fees are zero
   totalFees = 0
 
   ' Input and validate membershipType
   membershipType = InputBox("Membership Type (F=Full, J=Junior, L=Life, X=eXit) ?")
   While membershipType <> "F" And membershipType <> "J" And _
         membershipType <> "L" And membershipType <> "X"
      MsgBox ("Error: membership type must be F, J, X or X")
      membershipType = InputBox("Membership Type (F=Full, J=Junior, L=Life, X=eXit) ?")
   Wend
 
   ' While the user hasn't finished
   While membershipType <> "X"
 
      ' Determine the membershipFee and membershipName
      If membershipType = "F" Then
         membershipFee = 160
         membershipName = "Full"
      Else
         If membershipType = "J" Then
            membershipFee = 80
            membershipName = "Junior"
         Else
            membershipFee = 10
            membershipName = "Life"
         End If
      End If
 
      ' Sum the membership fees
      totalFees = totalFees + membershipFee
 
      ' Display the membership fee
      Debug.Print membershipName; " membership fee = $"; Format(membershipFee, "0.00")
 
      ' Input and validate membershipType
      membershipType = InputBox("Membership Type (F=Full, J=Junior, L=Life) ?")
      While membershipType <> "F" And membershipType <> "J" And _
            membershipType <> "L" And membershipType <> "X"
         MsgBox ("Error: membership type must be F, J, X or X")
         membershipType = InputBox("Membership Type (F=Full, J=Junior, L=Life, X=Exit) ?")
      Wend
 
   Wend
 
   Debug.Print "Total Fees = $"; Format(totalFees, "0.00")
 
End Sub

4. Review of Looping

Types of Loops

Some Common Uses of Repetition

Approach to Solving Problems Involving Repetition

When solving problem that may involve repetition, determine:

Common Logic Errors


Key Points

Further Reading


Written by Tim Whitfort.