Thursday, 28 January 2010

For Next loops

Sometimes in a program you will need to repeat an action a certain number of times. If this was a PRINT statement, as in the 'Hello World' Program  we could simply  write PRINT "Hello World" Ten Times but this would be very inefficient.  The basic language provides the for next loop for this purpose. The simplest for next loop carries out an operation based on a fixed number that is set at the beginning of the loop.

The following code will repeat a rather simple printing operation ten times


________________________________________________

 REM Print Ten Times Using a FOR NEXT loop

FOR a = 1 TO 10

PRINT "Hello World"

NEXT a

_________________________________________________

Type the above code into the QBasic editor then Save and Run.
The 'a' in the FOR 'a' and the last statement NEXT 'a' is a variable which is used to hold an incrementing number. In this particular case it holds a number between 1 and 10.  FOR a = 1 TO 10 sets the parameters of the Variable 'a'  and the NEXT a statement increments the 'a' by 1 each time the NEXT statement is executed. Until the variable 'a' is equal to 10 all the statements between the FOR and NEXT will be repeated.

In the next program we will use the for next loop again to do our times tables.

This lesson has introduced the FOR NEXT loop and the the variable.  

No comments:

Post a Comment