Lecture 11 - Introduction to Repetition


Home


Objectives

Contents


1. Introduction

The programs developed so far have used sequence and/or selection. The logical flow of the program is from top to bottom. If selection is used then some of the steps may be omitted under some circumstances.

Many problems require that steps be repeated. This is commonly known as looping (or repetition or iteration). It is called looping because logically it forms a loop as instructions are executed one after the other in the forward direction then control jumps back to the start of the loop and this is repeated again, and again.

To perform repetition successfully we need to know what instructions are to be repeated (e.g. lines 5 through 10) and we need to know when to stop looping.

2. A Simple Example Problem

Problem: Display "Hello World" 3 times

in English we may write something like

Display a line, followed by "Hello World" 3 times, followed by a line

or

Display a line
Do the following step 3 times:
    Display "Hello World"
Display a line

or

1  Display "-----------"
2  Display "Hello World"
3  If step 2 has been done 3 times, go to step 5
4  Go back to Step 2
5  Display "-----------"
6  ...

Pseudo Code Solution 1: Using Sequence

threeHelloWorlds1()
    Display "-----------"
    Display "Hello World"
    Display "Hello World"
    Display "Hello World"
    Display "-----------"
STOP

This is a simple solution, but what if we wanted to do it 10 times or 1000 times?

Pseudo Code Solution 2: Using a FOR loop

Pseudo Code

threeHelloWorlds2()
    Display "----------"
    FOR count = 1 TO 3 DO
        Display "Hello World"   
    ENDFOR
    Display "----------"
STOP

Discussion

FOR marks the start of the FOR loop. ENDFOR marks the end of the loop. Everything in between FOR and ENDFOR  is repeated the specified number of times (3 in the above example). 

Data Dictionary

Name Data Type Description
count Integer A counter variable used to keep track of how many times the loop has been repeated.

The logic of the above FOR loop can be represented diagrammatically as follows. The logic only flows in the direction of the arrows.

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Desk Check

1  threeHelloWorlds2()
2      Display "-----------"   
3      FOR count = 1 TO 3 DO
4          Display "Hello World"   
5      ENDFOR
6      Display "-----------"   
7  STOP
Line Number count Conditions Input/Output
1, 2     -----------
3 1 1 <= 3? is T  
4     Hello World
5 1 + 1 = 2    
3   2 <= 3? is T  
4     Hello World
5 2 + 1 = 3    
3   3 <= 3? is T  
4     Hello World
5 3 + 1 = 4    
3   4 <= 3? is F  
6     -----------
7      

3. The FOR Statement

The syntax of a FOR loop is as follows

Pseudo Code Syntax - FOR Loop

FOR counter-variable = 1 TO number-of-repetitions DO
    statement
    statement
    ...
ENDFOR

Basic Syntax - For Loop

For counter-variable = 1 To number-of-repetitions
    statement
    statement
    ...
Next

4. Fixed Number of Repetitions

The simplest type of loop is to repeat something a fixed (constant) number of times every time the program is run.

Example 1 : Display a users name 4 times.

Example Run

Run
Name ? Helen

Helen
Helen
Helen
Helen
----------

Defining Diagram

Inputs Processing Outputs
name Input name
Display name
Display line
name

Outline the Solution

The name is to be displayed 4 times

Pseudo Code

displayName()
    Input name
    FOR i = 1 TO 4 DO
        Display name
    ENDFOR
    Display "----------"
STOP

Data Dictionary

Name Data Type Description
i Integer A loop counter, used to count the number of times the loop is repeated.
name String The name of a person

Discussion

In this example, the loop counter (i) is used to control the loop, but is not otherwise used in processing.

Desk Check

1 displayName()
2     Input name
3     FOR i = 1 TO 4 DO
4         Display name
5     ENDFOR
6     Display "----------"
7 STOP

Inputs: name = Helen. Correct Result: Helen displayed 4 times

Line Number i name Conditions Input/Output
1, 2   "Helen"   Name ? Helen
3 1   1 <= 4? is T  
4       Helen
5 1 + 1 = 2      
3     2 <= 4? is T  
4       Helen
5 2 + 1 = 3      
3     3 <= 4? is T  
4       Helen
5 3 + 1 = 4      
3     4 <= 4? is T  
4       Helen
5 4 + 1 = 5      
3     5 <= 4? is F  
6       ----------
7        

Basic Code

' Name: displayName
' Purpose: Display a persons name 4 times
' Author: Tim Whitfort
Option Compare Database
Option Explicit

Sub Main()

    ' Declare variables
    Dim i As Long  ' Counter used to control the loop
    Dim name As String  ' The name of the person

    ' Input the user name
    name = InputBox("Name ?")

    ' Display the name 4 times
    For i = 1 To 4
        Debug.Print name
    Next
    Debug.Print "----------"
End Sub

Example 2: Display the numbers from 1 to 10 and their square

Example Run

Run
x  x Squared
1    1
2    4
3    9
4    16
5    25
6    36
7    49
8    64
9    81
10   100

Defining Diagram

Inputs Processing Outputs
  Calculate xSquared
Display x, xSquared
x, xSquared

Outline the Solution

The loop is to be repeated 10 times

Discussion

In the above problem the repetition isn't as obvious as in previous problems. The heading "x   x Squared" occurs once only, before the table of values is printed. It is important that this is not inside a loop and it is done before the table of values is displayed. Then the table of values is displayed - this involves repetition.

Examine a line of the table:

On a single line e.g. x = 2, xSquared = 4, the value of xSquared can be calculated from x (xSquared = x * x). This applies to any line. In general form xSquared = x * x whatever the value of x

Next look at the relationship between lines of values: x increases by 1 from line to line

The difference between the lines is that x is increased by 1. In a general form x = x + 1.

Focusing on what is done once and what is repeated, the processing looks like:

x = 1                           | Once only before the loop

xSquared = x * x = 1 * 1 = 1    |
Display x, xSquared             | Repeated section
x = x + 1 = 1 + 1 = 2           |

xSquared = x * x = 2 * 2 = 4
Display x, xSquared
x = x + 1 = 2 + 1 = 3

xSquared = x * x = 3 * 3 = 9
Display x, xSquared
x = x + 1 = 3 + 1 = 4.
...
x = x + 1 = 9 + 1 = 10. 

xSquared = x * x = 10 * 10 = 100
Display x, xSquared
x = x + 1 = 10 + 1 = 11         | Exit condition reached
Stop 

The repeated part is:

xSquared = x * x
Display x, xSquared
x = x + 1

Pseudo Code

 
 
 
 
 
 
 

Data Dictionary

Name Data Type Description
x Integer A loop counter, used to count the number of times the loop is repeated, and as the value of x to be displayed and used to calculate x squared
xSquared Integer The current value of x Squared

Discussion

In this example, the loop counter (x) is used to control the loop, and is also used in processing - it is displayed and used to calculate xSquared.

Desk Check

Correct Result: Table of results for x from 1 to 10 and xSquared: 1, 4, 9, ... 81, 100

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Basic Code

' Name: calcSquares
' Purpose: Display a table of values showing x and it squares
' Author: Tim Whitfort
Option Compare Database
Option Explicit

Sub Main()
 
 
 
 
 
 
 
 
 
 
 
 
 
End Sub

Features of Problems Containing Loops

A problem involving looping usually has the following features:

  1. Something may be done once only before the loop (e.g. the headings)
  2. The loop repeats the body of the loop while some condition is true
  3. The body of the loop contains one or more statements, these should move towards a point where the loop is exited (e.g. incrementing a counter)
  4. Something may be done once only after the loop

For the above problem:

1. Something may be done once only before the loop (e.g. the headings)

The headings "x   x Squared" are done once only, before the loop. As this is always to occur once, it is not appropriate to put them in a loop. It is placed before the loop as the headings must be displayed on top of the table.

2. The loop repeats the body of the loop while some condition is true

The loop stops after x = 10 and xSquared = 100 are displayed

3. The body of the loop contains one or more statements, these should move processing towards a point where the loop is exited (e.g. incrementing a counter)

The value of xSquared is calculated, the value of x is incremented by 1 (add 1 to x).

4. Something may be done once only after the loop

Nothing needs to be done after the loop in this problem.

5. Number of Repetitions Determined at Run-Time Before the Loop is Entered

The following examples can be used where the number of times to loop varies from run to run, but is determined before the loop is entered at run-time. For most problems of this type encountered in this subject, the number of repetitions will be input by the user, however for some problems if may be determined in other ways.

Example 1: Display the number of "*" specified by the user

Example Runs

Run
Number of stars ? 3
***
Run
Number of stars ? 8
********

Defining Diagram

Inputs Processing Outputs
numberOfStars Input numberOfStars
Display "*"
"*"

Outline the Solution

The loop is to be repeated numberOfStars times.

Pseudo Code

displayStars()
    Input numberOfStars
    FOR count = 1 TO numberOfStars DO
        Display "*"
    ENDFOR
STOP

Data Dictionary

Name Data Type Description
count Integer A loop counter, used to count the number of times the loop is repeated
numberOfStars Integer The number of stars to be displayed. Used to specify the number of times the loop is repeated

Discussion

In this example, the loop counter (count) is used to count the number of times through the loop. numberOfStars is used to specify how many repetitions are to occur.

Desk Check

1 displayStars()
2     Input numberOfStars
3     FOR count = 1 TO numberOfStars DO
4         Display "*"
5     ENDFOR
6 STOP

Inputs: numberOfStars = 3. Correct Result: "***"

Line Number count numberOfStars Conditions Input/Output
1, 2   3   numberOfStars ? 3
3 1   1 <= 3 ? is T  
4       *
5 1 + 1 = 2      
3     2 <= 3 ? is T  
4       *
5 2 + 1 = 3      
3     3 <= 3 ? is T  
4       *
5 3 + 1 = 4      
3     4 <= 3 ? is F  
6        

Basic Code

' Name: displayStars
' Purpose: Display a number of stars
' Author: Tim Whitfort
Option Compare Database
Option Explicit

Sub Main()

    ' Declare variables
    Dim count As Long  ' Counter used to control the loop
    Dim numberOfStars As Long ' The number of stars to display

    ' Input numberOfStars to display
    numberOfStars = InputBox("Number Of stars to display ?")

    ' Display the stars the number of times specified
    For count = 1 To numberOfStars
        ' The ; indicates don't start a new line, so *** is printed
        Debug.Print "*"; 
    Next
    Debug.Print ""

End Sub

Example 2: Count a number of items

Count the number of items weighing over 20 kg. The number of items to be input is specified by the user at run-time.   

Example Runs

Run
Number of items ? 4
Weight (kg) ? 12
Weight (kg) ? 21
Weight (kg) ? 35
Weight (kg) ? 8

Number of items over 20kg = 2

Pseudo Code

 
 
 
 
 
 
 
 
 
 
 

Discussion

In this problem there are two counters: itemNumber and heavyCount. itemNumber is used as a loop control variable, it counts how many item weights are input, and is used by the FOR loop condition to determine if the user specified number of enough items have been input. Whereas heavyCount is used to count the number of items that are over 20kg.

6. Types of Loops

There are three main types of loops:

7. Suggestions for Detecting Repetition

If the problem indicates (or suggests) that something may be done multiple times then it probably requires a loop. Some indicators of repetition are:


Key Points

Further Reading


Written by Tim Whitfort.