next up previous
Next: 13. WHILE/WEND Loops Up: VisualBasic Previous: 11.CheckBoxes


12. FOR/NEXT Loops

Often the main benefit of computers is that they perform the same (often tedious task) repeatedly - without even complaining. Rather than writing out the same list of instructions many times, you can get the program to repeatedly loop through the one set of instructions many times.

As an example, consider the procedure you need to go through to check the pressure in your car's tyres (written in an imaginary computer language):


MOVE TO TYRE 1
MEASURE PRESSURE IN TYRE 1
MOVE TO TYRE 2
MEASURE PRESSURE IN TYRE 2
MOVE TO TYRE 3
MEASURE PRESSURE IN TYRE 3
MOVE TO TYRE 4
MEASURE PRESSURE IN TYRE 4

Instead of writing out what to do for each of the four tyres, you can simply write:

LOOP OVER THE VALUES n = 1,2,3,4
MOVE TO TYRE n
MEASURE PRESSURE IN TYRE n
GO TO START OF LOOP

In Basic, the commands to start the above loop is For n = 1 To 4 and the command at the end is Next n. As an example, the following program writes out all the numbers from 1 to 10: (Note that you can click here to download a copy of this program.)

For i = 1 TO 10
Print i
Next i

The variable i is called the loop variable. Note that the loop variable i is incremented by one each time through the loop. You can increment the loop variable by any amount you choose. For example, the following program prints all odd numbers between 1 and 10. This is done using the Step parameter in the For line: (Note that you can click here to download a copy of this program.)

For i = 1 TO 10 Step 2
Print i
Next i

The above examples print out numbers down a column. i.e. each number is on a separate line. To print out numbers across a line (i.e. along a row) you need to modify the Print command to

Print i,

i.e. the comma is telling the programme to expect more output on that line. The comma inserts a TAB character (which gives a fairly big space). If you don't want such a big space between the numbers, you could use

Print i;"  ";

The semi-colon adds no extra space at all, so the ;" "; will add just a few spaces between the numbers. Click here to get a programme which illustrates these Print commands.

You can get a program to repeat a similar task many times using the For loop.

CHECKPOINT: Write a program which prints out the numbers 10,9,8, ...1.


next up previous
Next: 13. WHILE/WEND Loops Up: VisualBasic Previous: 11.CheckBoxes
Chris Allton 2006-10-27