FOR Loops.

        FOR loops are one of the most useful constructs not only in QBasic, but also in many other languages as well. The main purpose of a FOR loop is to do a section of code for a certian number of times. Often when you to a loop you will want it done for a specific number of times and this type of loop is designed specifically for that.
        The general form of the loop is demonstrated in the example below:

        FOR X% = 1 TO 5
          PRINT X%
        NEXT X%

Output:
        1
        2
        3
        4
        5

        Okay now to explain what exactly, all that means. First, the first line of the code is read: X% equals 1, loop until X% equals 5. The second line just prints the value of X%, and the last line of code would read add 1 to X% and go back to the beginning of the loop. In the first line of code X% can be any number type of variable, which excludes strings and User-defined types and arrays(which will be discussed in part2 of this tutoral.)
        Often you will want to start X% at some number and decrease until you reach a smaller number. You may find a need to increase X% by some value greater than one, or less than one. This can be done with the STEP clause. The example below demonstrates how to use a STEP clause.

        FOR X% = 5 TO 1 STEP -1
          PRINT X%
        NEXT X%

Output:
        5
        4
        3
        2
        1

        In this example we start the 'loop variable' X% at 5 and decrease it by 1 until it reaches 1. If we wanted to go from 0 to 10 in increments of 2, we would just put a 2 in place of the -1 after the STEP clause. Here is an example:
        FOR X% = 0 TO 10 STEP 2
          PRINT X%
        NEXT X%

Output:
        0
        2
        4
        6
        8
        10

        As you can see we can put any value we want in after the step and the variable will increase, or decrease if there is a negative sign, until the value of the variable is equal to the number after the TO. Another thing to note is that you can have the value after the TO be a variable.

    Back         Tutorial Part 1         Next