1.            Loops

The For Loop The While Loop Summary
Practice Exercise Assignment

Learning Outcomes

On completion of this section you will be familiar with the structures and uses of:

·         for loops

·         while loops

·         do loops

Download pdf version

Introduction

The sequence of our programming has up to now gone from top to bottom. In Listing 21 the sequence of execution went from line 7 to line 14 without any interruption. (The lines containing variable declarations are not executed.) In Listing 41 the sequence of execution would go 7, 8, 9, 11, 15, 16, 17, 18, if the value of curGross was 500 or less. If the value was greater than 500 then the sequence would be 7, 8, 9, 13, 15, 16, 17, 18.

Some lines could be skipped but the sequence was always top to bottom with no going back.

In loops we interrupt this top to bottom sequence, because the nature of a loop is that a group of lines may be repeatedly executed before the line following them gets executed. Thus a sequence of execution of a group of lines containing a loop could be:

1, 2, 3, 4, 5, 3, 4, 5, 3, 4, 5, 3, 4, 5, 3, 4, 5, 6, 7, 8

Here we notice that the lines 3, 4, 5 are executed 5 times before line 6 is executed. This means that those lines are part of a loop. In programming there are three types of loops:

·         For loops

·         While loops

·         Do loops

In each type of loop a group of lines is repeated. The difference between the loops is how they control the repetition of the lines.

The for loop

Go to top

Listing 61 below contains a For loop that prints the square of all numbers between 1 and 5.

 

Listing 61

1

Sub ForDemo()

2

    Dim intCounter As Integer

3

    Dim intSquare As Integer

4

    For intCounter = 1 To 5

5

        intSquare = intCounter ^ 2

6

    Debug.Print intCounter, intSquare

7

    Next

8

End Sub

In lines 2 and 3 we declare the two variables that we shall be using. The first one, intCounter, is used to control the loop as we shall see shortly, while the other will hold the value of the square of counter, before being printed.

Line 4 is where the loop is defined. It begins with the keyword For which indicates what type of loop we are going to use. After this we have the variable that is to be the loop counter i.e. intCounter. After the loop counter we have a “=” and this is followed by the initial value of intCounter which is 1 in this case. The initial value is followed by the keyword To. This keyword is in turn followed by the final value of intCounter – which in our case is 5. This means that intCounter starts with an initial value of 1 and is then successively revalued to 2, 3, 4 and 5.

Let us now look at a line by line execution. When line 4 is first encountered the variable intCounter is initialised to 1. Since this is less than or equal to 5 the body of the loop is entered. At line 5 the variable intSqure is updated. This is done by squaring the counter and storing the result in intSquare. (In Visual Basic the power operator is ^. Thus intCounter ^ 2 is equivalent to intCounter2 in ordinary mathematics.) Since intCounter has a value of 1 its square will also be 1 and so intSquare also is 1.

Control now passes to line 6 where the values of intCounter and intSquare are printed. In this case the output will be:

1          1

Control now passes to line 7 which contains the keyword Next. This indicates that it is the end of the body of the loop. However as this is a loop it does not necessarily mean that the code following Next will be executed. What happens instead is that control is passed back to line 4, where the value of intCounter is incremented to 2. This value is still not greater than 5 and thus control once more goes into the body of the loop to line 5.

This time, intSquare will be valued to 4 (the square of 2) and line 6 will print out

2          4

Control again passes to line 7, where Next passes control back to line 4.

Everything proceeds as described up to now until intCounter has a value of 5. When this occurs intSquare is valued to 25 and line 6 prints out

5          25

Once more control passes to line 7. This time the loop counter – intCounter - has reached its maximum value. Because of this control is not passed back to line 4 any more, instead control passes to line 8 where the programme ends.

In the counter is incremented by 1 each time around the loop. We can, on the other hand increment the counter by any value we want. In Listing 62we have an example where the counter is incremented in steps of 2

 

Listing 62

1

Sub ForStep()

2

    Dim intCounter As Integer

3

    Dim intSquare As Integer

4

    For intCounter = 1 To 10 Step 2

5

        intSquare = intCounter ^ 2

6

        Debug.Print intCounter, intSquare

7

    Next

8

End Sub

The code here is identical to that in Listing 61except for line 4. In the present example this reads as

            For intCounter = 1 To 10 Step 2

This means that the variable intCounter starts off as 1, goes through the body of the loop as explained before, calculating the value of intSquare in line 5 and printing it in line 6. When line 7 passes control back to line 4, Step 2 ensures that intCounter is incremented by 2 instead of by 1. Thus its new value will be 3. This means that at each turn of the loop the successive values of intCounter and intSquare will be

1          1

3          9

5          25

7          49

9          81

The For loop can also count backwards as shown in Listing 63

Listing 63

1

Sub ForBack()

2

    Dim intCounter As Integer

3

    Dim intSquare As Integer

4

    For intCounter = 5 To 1 Step -1

5

        intSquare = intCounter ^ 2

6

        Debug.Print intCounter, intSquare

7

    Next

8

End Sub

Once again this programme changes from its two predecessors only at line 4. This time it is

For intCounter = 5 To 1 Step -1

In this case intCounter starts at 5 and each time around the loop its value will decrease by 1 each time until it reaches 1. Its output will be:

5          25

4          16

3          9

2          4

1          1

Before leaving the For loop we shall look at its most frequent uses – totalling numbers. Listing 64 shows a programme for totaling the numbers between 1 and 5.

Listing 64

1

Sub AddUp()

2

    Dim intCounter As Integer

3

    Dim intTotal As Integer

4

    intTotal = 0

5

    For intCounter = 1 To 5

6

        intTotal = intTotal + intCounter

7

    Next

8

    Debug.Print intTotal

9

End Sub

In this listing the main difference is at line 6 where the total is calculated. Notice that at line 4 the number that holds the total is initialised to zero. After that we enter the body of the loop. The first time around the loop intCounter will have a value of 1. Thus at line 6 intTotal = intTotal + intCounter means add the value of intTotal to the value of intCounter and store the result in intTotal. The first time around the loop intCounter will have a value of 1 and intTotal will have a value of 0, thus line 4 will be equivalent to intTotal = 0 + 1. Once the line is executed intTotal will end up with a value of 1.

The second time around the loop intCounter will have a value of 2 and intTotal will have a value of 1, thus line 4 will be equivalent to intTotal = 1 + 2. Once the line is executed intTotal will end up with a value of 3.

The third time around the loop intCounter will have a value of 3 and intTotal will have a value of 3, thus line 4 will be equivalent to intTotal = 3 + 3. Once the line is executed intTotal will end up with a value of 6.

The fourth time around the loop intCounter will have a value of 4 and intTotal will have a value of 6, thus line 4 will be equivalent to intTotal = 6 + 4. Once this line is executed intTotal will end up with a value of 10.

The final time around the loop intCounter will have a value of 5 and intTotal will have a value of 10, thus line 4 will be equivalent to intTotal = 10 + 5. Once this line is executed intTotal will end up with a value of 15.

The while loop

Go to top

Listing 64 shows a For loop that adds up the numbers between 1 and 5. This is fine but what if we wanted to add up the numbers between 5 and 35? We could, of course, alter line 5 to

            For intCounter = 5 To 35.

This would work but altering programme code frequently is not recommended – especially if it is being used by a non IT person. Suppose we were adding up random numbers such as 125, 15, 89, 217, 5. In this case the For loop would be of no use at all. In this instance we need the While loop.

A While loop is structurally and logically different from a For loop. The main differences between them are as follows:

·         The For loop is controlled by the values on both sides of the keyword To. These values determine how many times the loop will run. The while loop is controlled by a priming read before the loop itself and then by a test that occurs at the start of the loop. There is a second read inside the body of the loop that further controls it.

·         The For loop runs a definite number of times. The While loop runs an indefinite number of times and in fact, depending on the circumstances may not run at all.

Listing 65 below shows the structure of a while loop.

Listing 65

1

Sub WhileExample()

2

    Dim intValue As Integer

3

    Dim intTotal As Integer

4

    intTotal = 0

5

    intValue = InputBox("Enter value to be totalled")

6

    While intValue >= 0

7

        intTotal = intTotal + intValue

8

        intValue = InputBox("Enter value to be totalled")

9

    Wend

10

    Debug.Print "The total of the values you have entered is ", intTotal

11

End Sub

This loop is used to total up a random set of numbers that is entered by the user. It could be used for totalling student marks or totalling a customer’s purchases at a supermarket checkout since in both of those cases the values would always be positive.

In lines 2 and 3 we declare our variables. intValue will be used to accept the value entered by the user while intTotal will be used to total up all of the values.

When using a variable for totalling up a number of values, the first action should always be to initialise that variable to zero. In our case this is done at line 4.

Line 5 contains the priming read of the loop. The user is simply requested to enter a value and once the value is entered it is stored in the variable intValue.

Line 6 is the start of the loop structure. It begins with the keyword While. This is followed by the condition. In our case the condition is intValue >= 0. Thus if the user entered 6 then the condition would be true. If the condition is true then the main body of the loop is entered. The body of the loop consists of lines 7 and 8. In line 7 the value entered by the use is added to intTotal in exactly the same way as it was done in line 6 of Listing 64.

Line 8 contains the other loop control – the main read of the loop. Notice that this line is identical to line 5 – it accepts the user’s input and stores it in the variable intValue. Once this is done control passes to line 9 which contains the keyword Wend. This is an abbreviation of “while end” and is the end of the loop structure. Wend passes control back to the line containing While i.e. line 6, where the value of intValue is tested once more. If the condition is true then the body of the loop is entered once more and processing proceeds as before. This continues indefinitely until the user enters a negative number at line 8. When this occurs Wend passes control back to line 6 again where intValue is tested once more. This time the condition will be false since intValue will contain a negative number. Because of this the body of the loop will be skipped and control will pass to the line after the Wend statement, i.e. to line 10. Here the value of intTotal is printed and the programme finishes.

As a final example of the While loop we shall look at how to use it to validate data, in other words how to use it to ensure that only correct data is allowed to be processed by the programme. As an example, in our payroll programme if we want to ensure that the hours worked are between 5 and 60 then we must ensure that any number that is greater than 5 or less than 60 is rejected and that the user is asked to re-enter that number again. This process should continue until a number in the correct range, i.e. between 5 and 60 is received.

In Listing 66 below is shown part of the Pay programme where a While loop structure that extends from line 2 to line 6 is used to control the values that can be entered into the variable sngHours.

Listing 66

1

sngHours = InputBox("Enter Hours worked")

2

While sngHours < 5 Or sngHours > 60

3

    MsgBox "Hours must be in the range 5 - 60"

4

    sngHours = InputBox("Enter hours")

5

Wend

6

curRate = InputBox("Enter Rate")

At line 1 we have the priming read for the loop. This line is identical to line 5 in Listing 65. In the current case, instead of going straight ahead and getting the value for the rate we set about ensuring that the value entered is between 5 and 60 inclusive. Thus at line 2 we have a While structure with a somewhat more complex condition than we have had before. This is because we have to check the number is greater than or equal to the minimum value and less than or equal to the maximum value. Thus the condition has got two parts separated by the operator Or. This means that if any one of the two subconditions is true the entire condition is true. As an example if sngHours has a value of 3 then the subcondition sngHours <5 will be true while the sub condition sngHours > 60 will be false. Since one of them is true then entire condition will be true.

Similarly if sngHours has a value of 80 then sngHours < 5 will be false while sngHours > 60 will be true. Once again one of the sub conditions is true and therefore the entire condition is true.

If the entire condition is true then the body of the loop is entered where at line 3 a message is displayed indicating the fact that a number in the wrong range was entered and at line 4 the user is once more asked to enter the value for hours. The Wend at line 5 throws the programme back to line 2 again where the new value for hour is tested.

On the other hand, if at line 1 the user had entered 40 for hours then the sub condtion sngHours < 5 would be false and sngHours > 60 would also be false. Because of this the entire condition would be false. In this case the body of the loop would be skipped and control would jump from line 2 to line 6 where the user would be prompted to enter the value for the rate.

The do..loop until

Go to top

The final loop construct, the do..loop until , appears in Listing 37 below.

Listing 67

1

Sub DoLoopExample()

2

    Dim intValue As Integer

3

    Dim intTotal As Integer

4

    intTotal = 0

5

    Do

6

        intValue = InputBox("Enter a number")

7

        If intValue >= 0 Then

8

            intTotal = intTotal + intValue

9

        End If

10

    Loop Until intValue < 0

11

    Debug.Print intTotal

12

End Sub

The loop structure here is between lines 5 and 10. Notice that there is no priming read outside of the loop structure itself. The only read in the loop occurs at line 6. An IF construct test if this value is a positive number. If it is then at line 8 the value entered is added to the variable intTotal. At line 10 the variable intValue is tested for being negative. If it is then the loop terminates, otherwise control is passed back to line 5 again.

Summary

Go to top

All loops are used to repeat a group of command lines a number of times. Each loop must have a keyword to indicate what type of loop it is, a counter that keeps track of how often to go around the loop, a part that initialises the counter, a part that alters the counter and condition that tests the value of the counter to see if it has reached its minimum or maximum.

In the For loop, the values before and after the keyword To controls how many times the loop repeats. The value of the loop counter starts at the first number and is incremented on each repetition until the counter is equal to the second number.

In the While loop the counter is initialised outside the body of the loop in a separate command line. The condition of the loop follows the keyword While. If the condition is true then the body of the loop is entered where the loop processing occurs. Beore the end of the loop the loop counter is revalued again and the keyword Wend passes control back to the While line once more. This process continues until the condition of the loop becomes false.

Practice

Go to top

Copy the code of Listing 52 into your programme area and modify it by adding the While loop in Listing 66 in order to validate the value of the hours. Now run this program and try entering values for hours that are less then 5 or greater than 60 and ensure that each one of them is rejected and that the programme comes back again to ask for another value for hours..

Once you are satisfied that values less than 5 or greater than 60 are rejected then test a range of values that are between 5 and 60 and ensure that all of those are accepted.

Finally add another While loop to validate the value of the rate. The rate must be between 10 and 20. Again test the programme a number of times to ensure that numbers less than 10 or greater than 20 are rejected and that numbers that fall between 10 and 20 are accepted.

Finally prepare test data for various ranges of values for hours and rate.  For each have some below the allowed range, within the allowed range and above the allowed range. Determine which set of values will produce output and which will not.  Now run the programme and test it with those values.  Check that the expected results and the actual results are the same.

Exercise 6

Go to top

Part 1

1.      give a general definition of a programming loop.

2.      describe the structure of a for loop.

3.      what are the essential components of a while loop and where are they placed in relation to the structure of the loop?

4.      what are the main logical differences between a while loop and a for loop?

5.      what are the essential components of a do..while loop and where are they placed in relation to the structure of the loop?

6.      what are the similarities between the while and the do..while loops?

7.      what are the differences between the while and the do..while loops?

Part 2

Write a programme, using a For loop, that adds up all of the numbers between 1 and 100. The programme will only print out the final sum, and not the intermediate calculations.

Part 3

Repeat part 2, except this time use a while loop.

In Listing 65 the Input and Process sections are mixed up.  Determine which lines form the Input and which ones form the Process.

Assignment Part 5

Go to top

Section 1

The programme you created in Assignment Part 4 has a fault in that it can only process the sale of one single item. If the customer purchases two different items then the programme has to be run twice. Your task is to modify the programme so that it can handle the sale of any number of different items. A While loop will be used to control the data entry. The sequence will be as follows:

·         The user is prompted to enter the price of a single item

·         A While loop tests this for being greater than zero.

·         If this is true then the body of the loop is entered and the user is prompted for the amount sold. The processing will now continue as before until the data for that sale is printed.

·         The user is prompted once more for the price of a single item.

·         This command is followed by a Wend which throws control back to the While line where the value is once more tested for being greater than zero

Section 2

Modify further the programme of Section 1. As well as being able to handle multiple purchases by the same customer it should also be able to total all of the purchases by that customer as well as totaling the total GST for the same customer.

For suggestions on how to do this totaling check Listing 65

Section 3

Modify further the programme of Section 1 so that the unit price is validated as being a value between 3 and 25.  Use Listing 66 as an example of how to do this

Section 4

Once you feel that the programme is performing correctly prepare test data.  In this case you need two sets of test data. One set tests whether the While loop will either loop or terminate depending on the value entered for the price of a single item.  The other set is more complex.  This tests data that will cause the While loop to continue looping.  It must test that individual transactions produce the correct results and that a number of transactions will produce the correct total.