Lecture 12 - While Loops


Home


Objectives

Contents


1. Introduction

The loops used so far are useful if (a) the loop is always done the same number of times or (b) the number of times to do the loop is known before the loop commences (e.g. the user inputs the number of times to repeat the loop). A FOR loop is a simple counting loop, once commenced it will continue until the required number of repetitions are completed.

A more flexible loop must allow the loop to stop under some condition (or conditions) specified by the programmer. For example: if a user is inputting a series of prices, then a special value such as -1 could be input to indicate that the user has finished inputting prices.

A WHILE loop allows a condition to be specified to control the loop.

2. The WHILE Statement

The program to display "Hello World" 3 times from the previous lecture can be written using a While loop as follows:

Example

Defining Diagram

Inputs Processing Output
  Display "Hello World"  

Outline Solution

Loop 3 times.

Pseudo Code

threeHelloWorlds3()
    count = 1
    WHILE count <= 3 DO
        Display "Hello World"
        count = count + 1
    ENDWHILE
STOP

Data Dictionary

Name Data Type Description
count Integer A counter for counting the number of times through the loop

Note:

Note: for a problem like this with a known number of repetitions, a FOR loop would be a better alternative.

The logic of the above WHILE loop (and associated code e.g. initializing and incrementing the count) can be represented diagrammatically as follows. The logic only flows in the direction of the arrows.

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Desk Check

1  threeHelloWorlds3()
2      count = 1
3      WHILE count <= 3 DO
4          Display "Hello World"
5          count = count + 1
6      ENDWHILE
7  STOP
Line Number count Conditions Input/Output
1, 2 1    
3   1 <= 3? is T  
4     Hello World
5 1 + 1 = 2    
6, 3   2 <= 3? is T  
4     Hello World
5 2 + 1 = 3    
6, 3   3 <= 3? is T  
4     Hello World
5 3 + 1 = 4    
6, 3   4 <= 3? is F  
7      

Basic Code

' Name: helloWorlds
' Purpose: Display "Hello World" 3 times
' Author: Tim Whitfort

Option Compare Database
Option Explicit

Sub Main()
    Dim count As Long ' Loop counter
    count = 1
    While count <= 3
        Debug.Print "Hello World"
        count = count + 1
    Wend
End Sub

Syntax

Pseudo Code Syntax - WHILE Loop

WHILE condition DO
    statement
    statement
    ...
ENDWHILE

Basic Syntax - While Loop

While condition
    statement
    statement
    ...
Wend

3. Looping Until the User is Finished

When a user is inputting a number of values, and it not always feasible to input the number of times that a loop is to be repeated. One way to know if the user is finished is to ask them each time through the loop.

Problem Description

Write a program to display the area of square. The program is to allow the user to input the length of a square until they indicate they are finished.

Example Runs

Run
Continue (Y=Yes, N=No) ? Y

Length (mm) ? 10
Area = 100

Continue (Y=Yes, N=No) ? Y

Length (mm) ? 2
Area = 4

Continue (Y=Yes, N=No) ? N

Defining Diagram

Inputs Processing Output
continue,  length Input continue
Input length
Calculate the area
Display the area
area

Outline the Solution

Examine the run to see what is repeated:

Continue (Y=Yes, N=No) ? Y

Length (mm) ? 10
Area = 100
Continue (Y=Yes, N=No) ? Y

Length (mm) ? 2
Area = 4
Continue (Y=Yes, N=No) ? N

Once only

Repeated

Condition

Pseudo Code

calcSquareArea1()
    Input continue
    WHILE continue = "Y" DO
        Input length
        area = length * length
        Display area
        Input continue
    ENDWHILE
STOP

Data Dictionary

Name Data Type Description
area Double The area of a square in mm squared
continue String Does the user want to continue processing ("Y"=Yes or "N"=No)
length Double The length of a square in mm

Desk Check

1 calcSquareArea1()
2     Input continue
3     WHILE continue = "Y" DO
4         Input length
5         area = length * length
6         Display area
7         Input continue
8     ENDWHILE
9 STOP

Inputs: continue = "Y", length = 10; Correct Results: area = 100
Inputs: continue = "Y", length = 2; Correct Results: area = 4
Inputs: continue = "N"

Line Number area continue length Conditions Input/Output
1, 2   "Y"     continue ? Y
3       "Y" = "Y" ? is T  
4     10   length ? 10
5 10 * 10 = 100        
6         area = 100
7   "Y"     continue ? Y
8, 3       "Y" = "Y" ? is T  
4     2   length ? 2
5 2 * 2 = 4        
6         area = 4
7   "N"     continue ? N
8, 3       "N" = "Y" ? is F  
9          

Basic Code

' Name: calcSquareArea1
' Purpose: Calculate the area of squares
' Author: Tim Whitfort
Option Compare Database
Option Explicit
Sub Main()
    Dim area As Double     ' The area of a square in mm squared
    Dim continue As String ' Does the user want to continue processing ("Y"=Yes or "N"=No)
    Dim length As Double   ' The length of a square in mm

    continue = InputBox("Continue (Y=Yes, N=No) ?")
    While continue = "Y"
        length = InputBox("Length (mm) ?")
        area = length * length
        Debug.Print "Area = "; area
        continue = InputBox("Continue (Y=Yes, N=No) ?")
    Wend

End Sub

4. Sentinel Controlled Loops

An alternative to explicitly asking the user whether they have finished is to have the user input a special value called a sentinel value. The sentinel value must be a value that can't be confused with the "normal" values input. This approach is usually quicker for users when entering a series of data.

Example 1: if the user was inputting marks between 0 and 100, then the sentinel value must be outside of this range (e.g. -1) so that it can't be confused with a mark.

Example  2: if the user is inputting customer names then a sentinel value of a blank string (nothing) could be used.

When processing a loop that uses a sentinel value it is important that the sentinel value is not included in the normal processing of the loop, for example the sentinel value of -1 should not be processed as a mark.

Example

Problem Description

Write a program to display the area of square. The program is to allow the user to input the length of a square until a length of 0 or less is input.

This is the same as the earlier example except for using a sentinel value rather than an explicit questions asking the user if they wish to continue.

Example Runs

Run
Length (0 to exit) (mm) ? 10
Area = 100

Length (0 to exit) (mm) ? 2
Area = 4

Length (0 to exit) (mm) ? 0

Defining Diagram

 
 
 
 
 

Outline the Solution

 

 

Pseudo Code

calcSquareArea2()
 
 
 
 
 
 
 
STOP

Data Dictionary

Name Data Type Description
area Double The area of a square in mm squared
length Double The length of a square in mm

Desk Check

Inputs: length = 10; Correct Results: area = 100
Inputs: length = 2; Correct Results: area = 4
Inputs: length = 0

 
 
 
 
 
 
 
 
 
 
 
 
 

Basic Code

' Name: calcSquareArea2
' Purpose: Calculate the area of squares
' Author: Tim Whitfort
Option Compare Database
Option Explicit
Sub Main()
    Dim area As Double   ' The area of a square in mm squared
    Dim length As Double ' The length of a square in mm
 
 
 
 
 
 
 
End Sub

5. Infinite Loops

Infinite loops are loops that continue looping for ever. This is caused by having a condition in a WHILE loop that never becomes FALSE.

Example: infinite loop (the condition is always True)

count = 1
WHILE count > 0 DO
    count = count + 1
ENDWHILE

In Access Basic an hourglass displayed for overly long may be an indication of an infinite loop.

Press Ctrl+Break to stop an infinite loop.

6. Discuss Assignment 2

See assessment > assignment 2


Key Points

Further Reading


Written by Tim Whitfort.