Programming for Computing 07 - 08

Chapter: Loops: While and For

Module Admin   Contents, Index   Schedule  
1: Intro to VB    2: First Program and Projects    3: Variables, assignment, Strings    4: Type Conversion, InputBox, Constants    5:Built-in Functions    6: If - decisions    7: Loops - while, for    Example - find smallest    8: Scopes: local, global    9: Writing Procedures.Parameters, Functions   
10: Objects    11: Design    12: Testing    13: Graphics    14: Controls and events    15: Listboxes    16: Arrays    17: Files    18: The Command Line   

Appendices(links etc)   Additional Lectures    Tutorials (not in printed notes)     Selected solutions (not in printed notes)     Assignments    Additions and Errata   

new

The  schedule page has info on what we will do each week.

Why do we do this...

The repetition concept exists in most programs - you can't really write much without it.

 


Section 7.0

Introduction

Frequently, we need to obey the same VB statements over and over again, and one way to accomplish this is by setting up a loop (the other way is by recursion ). There are a number of loop statements in VB, but we will concentrate on 'while' and 'For'.

The 'while' loop can handle 'undetermined' loops, where it is not possible to know how many repetitions we need. For example, how many times will a user get a password wrong, before getting it right? We cannot say.

The 'for' loop is used when it is known in advance that the loop will repeat a particular number of times. e.g adding up the marks for a class. We probably know how many students there are.  


Section 7.1

The While Statement

Problem: check a password. Display an error message if needed.. (The password is "basic")
Private Sub Button1_Click(etc...)
dim attempt as string

attempt = inputBox("Enter your password")
While attempt <> "basic"
    MessageBox.Show("Wrong! - try again.")
    attempt = inputBox("Enter your password")
End While

MessageBox.Show("Welcome to the program!")
End Sub
Here is the equivalent as a ring-road, with a roundabout at its entry. A condition is tested at the roundabout. If it is true, the car enters the ring-road, then eventually comes round again to the roundabout. It might go round many times. Eventually, the condition would become false, and the car exits from the loop.

As an example, if the condition was 'no fuel warning light', the car would loop as long as the light was off.

[loopwhile1.jpg]
Flowchart of a While

Here is a mixture of ring-road' and VB:

 

attempt = inputBox("Enter your password")

|--->--While attempt <> "basic" ------>-----------------------
|            |                                               |
|            |  True - so go through the 'body' of the loop  |   False
|            |                                               |  go to after the End While
|        MessageBox.Show("Wrong! - try again.")              |
|        attempt = inputBox("Enter your password")           V
--<--End While                                               |
                                                             |
            ---------------------<----------------------------
            |
MessageBox.Show("Welcome to the program!")
End Sub
  • The condition is tested at the top of the loop, after the word 'While'.
  • As long as it is true, the statements in the middle of the loop (the indented ones) are obeyed once.
  • When End While (meaning end-of-while) is reached, the program goes back up to the While and tests the condition again. (The result from the test might be different, as we asked the user to have another go).
  • When the condition is found to be false, the program goes to the line just underneath the End While, and the next statement in the program is obeyed. Remember - 'While' means 'as long as'.
  • The middle of the loop is called the body.
  • You must indent the body - it becomes unclear if you do not. (VB does this for you)
  • Another way to look at this is that we are trapped inside the loop until the user gets the password right. The ONLY way to get past the While loop down to the 'welcome' message is by getting the password right.
  • Note that the inputBox has been used twice - is this a waste? No.
    We MUST have an inputBox used in the middle of the loop, otherwise the value of attempt could never change.
    We MUST ensure that the very first time the program gets to:
    While attempt <>"basic"
    
    it has a sensible value for attempt - so we read one in first!

    What if we reversed the 2 instructions in the body of the loop:

    ' WRONG
    attempt = inputBox("Enter your password")
    While attempt <> "basic"
        attempt = inputBox("Enter your password")      ' NB
        MessageBox.Show("Wrong! - try again.")
    End While
    
    Look at the NB line above - imagine the user enters the correct password here. The very next thing to happen is that an error message is displayed. However, in the correct version, the execution sequence is as follows. (Note that the following lines are not a program. They show the order of execution, as if we were writing down the lines as we step though the program with the F8 key):
    attempt = inputBox("Enter your password")
    End While      (sends it back up to While)
    While attempt <> "basic"
    attempt = inputBox("Enter your password")  ' NB
    
    thus, between the input and the error message, we have a test.

 


Section 7.2

Combining control structures.

Often, we need to nest - e.g. put a statement completely within another one. Here we do the marks classification from the IF notes, but make it repeat, asking for another mark. To end the loop, the user enters -1.
Private Sub Button1_Click(etc...)
dim mark as integer
mark = CInt(inputBox("Enter next mark (-1 to stop)"))
While mark <> -1
    If mark >= 40 then
        MessageBox.Show("pass")
    Else
        MessageBox.Show("fail")
    EndIf
    mark = CInt(inputBox("Enter next mark (-1 to stop)"))
End While
MessageBox.Show("done")
End Sub
Note that the inputs come in the same place as the password example: one above the While, and one just above the End While.

The nesting is:

While------------
|    If------   |
|    |       |  |
|    |       |  |
|    Endif---   |
End While--------
Imagine that the IF 'box' is totally inside the WHILE box.

The following is incorrect nesting:

While
    if
End While
    endif
 


Section 7.3

A counting loop

counter = 1
While ( counter<=10)
    MessageBox.Show("value is" & counter)
    counter = counter+1
End While
This displays the numbers from 1 to 10 inclusive. It does not display 11 .

You can use While to count with, but the For loop is more convenient in this pre-determined case. See below.  


Section 7.4

Stuck in a loop?

If you code a loop wrongly, the program may be stuck in the loop forever. E.g:
counter = 1
While ( counter>=0)
    MessageBox.Show("value is" & counter)
    counter = counter+1
End While
Here, the counter is always above 0, so it loops forever. Do NOT use ctrl/alt/del. You might lose your code. Intead, select the main VB window, choose the Debug menu, then Stop Debugging.

 


Section 7.5

Problems - While

1. Modify the password program so it counts how many incorrect goes were made. (Use another variable, e.g wrongCount)

2. Write a program which inputs a valid number of hours (must be 0 to 23) and a valid number of minutes (0 to 59). Any errors should cause a 'try again' message. Display the total number of minutes (e.g 2 hours 3 mins gives 123). This needs two loops, not nested.

3. write a counting loop from 1 to 10, which displays the squares: 1 4 9 25 36 ...100

4. spot the logic/run-time error in:

n=0
While n>=0
    n=n+1
End While

5. Spot the error in:

n=0
While n>=0
    m=n
    m=m+1
End While

6. On the last page of this chapter - Q1.(a).

 


Section 7.6

The For Statement

In programming, 'counting' loops are common, as in:
counter = 1
While ( counter<=10)
    MessageBox.Show("value is" & counter)
    counter = counter+1
End While
which displays out the integers from 1 to 10 inclusive. We see that initialising, testing, and adding to the counting variable occur in separate statements. The VB 'For' simplifies this.

The general form of the VB For is:

For variable = start to finish Step increment
    statements
Next
in which:
  • 'Step increment' is optional - not used much. Use this when the increment is not 1. - see below.
  • Start, finish, increment can be expressions (numbers, variables, calculations)
The above 'While' could be expressed with 'For' as:
	For counter = 1 to 10
          MessageBox.Show("value is" & counter)
	Next
Important: we don't need to put: counter = counter + 1
This is automatically done for us by the 'Next' instruction.

We can also 'step', as in:

	For counter = 1 to 10 Step 2
          MessageBox.Show("value is" & counter)
	Next
which displays 1,3,5,7,9
and can go backwards, as in
	For counter = 10 to 1 Step -1
          MessageBox.Show("value is" & counter)
	Next
which displays 10 9 8 7 6 5 4 3 2 1

Here is the marks classification, which asks how many students we have, before using a For:

Private Sub Button1_Click(etc...)
dim mark as integer
dim studentCount as integer
dim n as integer
studentCount = CInt(inputBox("How many students? "))

For n = 1 to studentCount
    mark = CInt(inputBox("Enter mark number " &  studentCount))
    if mark >= 40 then
        MessageBox.Show("pass")
    else
        MessageBox.Show("fail")
    endIf
Next

MessageBox.Show("done")
End Sub
Note the prompt for the mark, which does this:
Enter mark number 1
Enter mark number 2
   etc
 


Section 7.7

Nesting loops

Sometimes, we need to put a loop inside another loop. Here is an example which displays hours and minutes, e.g

H   M
0   0
0   1
0   2
...etc up to
0   59
1   0
1   1
...etc up to
1   59

...and up to
3   59

The code is:

For hours = 0 to 3                                                                 '1
    For mins = 0 to 59                                                             '2
        pictureBox1.TextBox1.AppendText(CStr(hours) & "  " & CStr(mins) & VbCrLf)  '3
    Next                                                                           '4
Next                                                                               '5
The sequence is:
  • line 1 runs, sets hours to 0
  • line 2 runs, sets mins to 0 (hours is still 0)
  • The inner loop (lines 2 3 4) runs, displaying hours and mins. (mins changes, hours is still 0)
  • When the inner loop gets to 59, line 4 runs, sending the program back to line 1. This sets hours to 1. The process continues, displaying 4 x 60 lines in total
 


Section 7.8

The End instruction

Trivially, this statement ends the run of a program - you will often see it attached to a 'quit' button.

Key Points

The test for continuing a While loop takes place at the top. While can deal with most programming problems - choose it if in doubt. For will be useful when we encounter arrays.

Problems

1. Write a program to process a series of 10 exam marks.

a). it should add up and display the sum of the marks. Code it, test it.

b). in addition, it should count how many marks were entered. Code it, test it.

c). in addition, it should display the average mark. Code it, test it.

d). in addition it should count how many fails (less than 40). Code it, test it.

Module Admin   Contents, Index