The FOR ... NEXT Loop
Normally programs flow along line by line (linear execution) in the order in which the line appears in your source code.
The FOR - NEXT statements enable you to repeat a block of code a set number of times (if you know exactly how many times you need to go through the loop).
Here is what an FOR-NEXT loop structure looks like in QBasic...
If you are uncertain about how many times you want to go through the loop, then you should use a WHILE loop or a DO loop.
Sample:
DIM x AS INTEGER DIM y AS INTEGER DIM z AS INTEGERREM example #1FOR x = 1 to 10 y = x * 2 COLOR x PRINT y NEXT xREM example #2 z = 12 For x = z to z+10 y = x * 2 PRINT y Next xPRINT "Good Bye"
A more Complex version of the FOR-NEXT Loop:
"More Advanced" For Loop |
WHERE:
After all statements in the loop have executed, step is added to counter. At this point, either the statements in the loop execute again (based on the same test that caused the loop to execute initially), or the loop is exited and execution continues with the statement following the Next statement. |
Sample:
DIM a AS INTEGER DIM b AS INTEGER DIM c AS INTEGER DIM x AS INTEGER DIM y AS INTEGER DIM z AS INTEGERREM example #1 For x = 10 to 100 Step 10 y = x * 2 PRINT y Next xREM example #2 For x = 1000 to 100 Step -100 y = x * 2 PRINT y Next xREM example #3 a = 3 b = 11 c = 2 For x = a to b Step c y = x * 2 PRINT y Next xPRINT "Good Bye"
* If a NEXT statement is encountered before its corresponding FOR statement, an error occurs.
How to avoid problems and errors using the FOR - NEXT loop:
Syntax Errors:
Logic Errors:
|