Vigay.com11
Feb
Search Vigay.com
 
 
Beginners Introduction to BASIC Programming - Lesson 4
Previous | Next

Looping and doing things more than once
Sometimes you may have the need to do some things more than once. For example, entering peoples names or doing repeated mathematical calculations, such as converting centigrade to fahrenheit.

There are a few ways of getting the computer to do repetitive tasks. The first, and probably the easiest, is to use a FOR .... NEXT loop. This type of loop is very useful if you know that you need to do something a fixed, preset, number of times.

The following simple example will print the numbers 1 to 10 on the screen.

10 FOR N=1 TO 10
20   PRINT N
30 NEXT N

Can you understand what the computer is doing?

Line 10 is telling the computer to count from 1 to 10. It uses the variable N to use as its counter. This can be any valid variable name you like.
Line 20 will display the current value of the loop variable N and,
Line 30 tells the computer to go back to the previous FOR command until N equals the value given.

The syntax of the FOR NEXT loop is as follows;

FOR n=x TO y STEP z
NEXT n

n can be any variable name, which is used by the computer to use for its counting. It should not be used between the FOR line and the NEXT line, or the computer may get confused and forget where it has got up to.

x can either be a numeric value (as in the previous example) or a numeric variable name. It is used as the starting value for n. If a numeric variable name is given, n will start at the current contents value of the variable at the time the program reaches the FOR line.

y can have the same values as x (ie. a number or a numeric variable name) and is used as the finish value for n. ie. what you want the computer to count up to.

The STEP z part of the line is optional and thus, may be omitted if you like. This allows you to tell the computer to jump in steps of z. If, in the previous example, you changed line 10 to;

10 FOR N=1 TO 10 STEP 2

then only the values 2,4,6,8 and 10 would be printed out because the computer is now jumping in steps of 2. If you omitted this, the computer will use a default step of 1.

z can be negative if you like, to count downwards. For example;

10 FOR N=10 TO 1 STEP -1

will start at 10 and count down to 1 in steps of -1.

The syntax of NEXT is fairly simple - you just match it with the loop variable you used after the FOR. In this case, n.

When the computer encounters a NEXT statement, it will increment the value in its loop counter (n) and, if the new value is less than or equal to the maximum loop value (y), it will jump back to the line where the FOR statement is. Therefore, any lines between the FOR line and the NEXT line will be repeated a number of times, depending on what values x, y and optionally, z you use.

You should be careful not to duplicate variables and use n inside the loop as the computer will get confused. For example, can you see what would happen if you inserted the line

25 N=5

into the example above?

This would reset the loop counter each time the computer reached line 25, thus N would never equal 10 (as stated in line 10). Therefore the computer would loop forever because N would never reach the required value stated in the FOR statement.

Can you see any disadvantages of using FOR .... NEXT loops?
Well, one disadvantage is that you have to know how many times you want to loop at the time you write the program. Of course, this may not be feasible, as you may want the user to be able to loop indefinitely - say until they enter a known termination value, such as -1, if all values entered are normally positive. Or, xxx if typing in peoples names.

Another disadvantage of FOR .... NEXT loops is that they are ALWAYS executed at least once. Can you see why this is?

It's because the computer doesn't know it's doing a loop until it reaches the NEXT statement. Therefore it will have to go past (and thus execute) the lines inbetween, even if the line was;

10 FOR N=2 TO 1

which is obviously wrong, as the start number already exceeds the finish number. The computer will only notice this when it comes to the NEXT statement. It will then see that the finish value has been exceeded, and stop.

Luckily to BASIC programmers, there are two alternative ways using BBC BASIC to overcome both of these disadvantages.

The first is by using what's known as a REPEAT .... UNTIL loop. This works in a similar way to the FOR .... NEXT loop, but the condition is at the end of the loop. An example will help clarify this;

10 N=1
20 REPEAT
30   PRINT N
40   N=N+1
50 UNTIL N>10

This may look slightly longer and more complicated, but it is also a bit more flexible. For a start, we can put whatever condition we like as part of the UNTIL statement. The syntax is actually slightly simpler than a FOR .... NEXT loop as well:-

REPEAT
  ....program lines
UNTIL <condition>

where condition can be anything you like. The computer will repeat everything between the two lines until the <condition> is TRUE. For example, <condition> could be;

UNTIL N/2=M+6
or
UNTIL name$="PAUL"

depending upon what program statements you insert between the two lines. Obviously, you have to be careful the condition is likely to become TRUE at some point, or else the computer will loop forever. For example,

UNTIL 1=2

It should be obvious that this condition can never occur and thus, the computer will never get to the end of the loop. If you have too complicated a condition after the UNTIL statement, you will need to check their validity carefully.

There may of course, be times when you may want the computer to loop indefinitely. Many people may be familiar with going up to a computer and typing;

10 PRINT "HELLO"
20 GOTO 10

which will repeatedly print HELLO down the screen until someone comes along and presses the ESCAPE key (which will halt the running of a program - handy if you do want to stop the computer if it accidentally gets into a never ending loop).

Technically, you shouldn't use the GOTO statement, as it does not fit into structured programming - More of this term later. Basically, the GOTO statement relies on the fact that you have given it an absolute line number to jump to. This is not ideal. For example, if you decide to change your program at a later date, all your GOTO's would need to be changed.

Instead you could replace the example above with;

10 REPEAT
20 PRINT "HELLO"
30 UNTIL FALSE

This would perform exactly the same task as the program above, but is a better way of writing it. This way, the program will still loop forever - FALSE is a keyword known to the computer which is exactly that - a short, or quick way or writing 1=2 or some 'false' statement. As the UNTIL statement loops until the condition is TRUE, this will never succeed.

Try experimenting with loops yourself. How about writing a program to ask the user to type in a list of numbers and then print the total of the list? The program should be terminated by entering -9999.
Have a think about this before you start writing a program. What sort of things do you need the computer to do?

You need a loop, a prompt to enter a number, a variable to calculate and store the total and a condition to end the program when -9999 is entered.

See if you can write a program to solve this problem, then compare it with the example below.

10 total=0
20 REPEAT
30   PRINT"Enter a number. Type -9999 to end."
40   INPUT number
50   total=total+number
60 UNTIL number=-9999
70 total=total-9999
80 PRINT "The total is ";total

How did your program compare? Did you spot a potential problem?
By waiting until the number entered equals -9999, you are still adding that number to the total (line 50) before the program does the loop checking. This means that, if you don't want to include the termination value as part of the calculations, you will need to subtract it after the loop.

A slightly tidier way of writing this, taking into account that -999 will terminate the list, is to delete line 70 and change line 10 to

10 total=-9999

Can you see how this will cancel the effect of entering -9999 to end the loop?

As mentioned earlier, there is an additional way of looping available to RISC OS users. It's similar to a REPEAT .... UNTIL loop, but instead of testing the condition at the end of the loop, checks a condition at the beginning. This has the added benefit of not executing the loop at all if the condition is initially false.

This alternative loop is called a WHILE .... ENDWHILE loop. It works very much like a back to front REPEAT .... UNTIL loop in that the ENDWHILE replaces the REPEAT but goes at the end and the WHILE replaces the UNTIL and goes at the beginning. Confused? Lets look at the syntax and an example;

WHILE <condition>
  ....program lines
ENDWHILE

The <condition> works in exactly the same way as the UNTIL statement, in that it checks to see if the condition is TRUE. If it is, the computer will execute the program lines following, get to the ENDWHILE and then jump back to the WHILE. it will do this indefinitely until the condition is no longer true.

By using a WHILE .... ENDWHILE loop we can make the previous example a bit simpler still. See if you can see how?

Have a think about it before examining the following example.

10 total=0:number=0
20 WHILE number<>-9999
30   total=total+number
40   PRINT "Enter a number. Enter -9999 to end."
50   INPUT number
60 ENDWHILE
70 PRINT "The total is "total

Can you see what changes have been made? For a start, we initialise both variables to zero before starting the loop. I have also moved line 30 so that the total is added up before we actually enter a value (line 50). The first time the program is run, 'number' will be zero, so nothing will be added. As the condition is at the beginning of the loop, as soon as we enter -9999, the loop will stop and -9999 will not be added to our list, so we no longer have to subtract it or take into account this situation.

By now you may have spotted a way of re-writing our original REPEAT .... UNTIL example to work the same way as this. A few modifications could produce;

10 total=0:number=0
20 REPEAT
30   total=total+number
40   PRINT "Enter a number. Type -9999 to end."
50   INPUT number
60 UNTIL number=-9999
70 PRINT "The total is ";total

As you can see, this example has overcome the original problem. You'll find that when you start to write more and more programs and become familiar with the various quirks and tricks of BASIC, you'll see alternative ways of writing programs a lot easier.

The thing to remember is that there is no right and wrong way to solve a problem. One person may use a WHILE .... ENDWHILE loop, whilst another may use a REPEAT .... UNTIL loop. As long as both solve the problem, neither can say the other person is wrong.

Of course, there are 'better' ways of doing things. You should always try to make your programs understandable and it's best to try to solve problems using the minimum amount of program lines. This way, you won't get too lost if you leave the program for a few weeks and then come back to it and try amending it. If the program is a mass of jumbled code, it will be harder for you to work out what it was doing in the first place.

One way of making programs more readable is to indent looped lines. If you look back at the examples above, you'll see that I have indented the program lines between the loops. This way you can see in an instant where your loops are in a program, especially when you start having loops within loops....

Continue to lesson 5.

Previous | Next


Email Email this page to a friend

Last edit: 11th Dec 2009 at 12:49pm
(792 days ago)

Bookmark with:What are these?
delicious Deliciousdigg Diggreddit redditfacebook Facebookstumbleupon StumbleUpon

RSS Feed

^
 
Valid HTML 4.01!
Valid CSS!
Best viewed with a cup of tea Crafted by RISC OS