FOR - NEXT LOOP


FOR-NEXT Loop
Purpose: 
  • To execute a series of instructions the given number of times. 
  • In FOR - NEXT loop, you must establish a counter variable and specify the range of values (Start value to Final Value).
 Syntax:
FOR Counter = Start Value TO Final Value [Step]
                   Block of statements
NEXT [Counter]

Example: Print 1,2,3,… 10

Start Value
Final Value
Step
1
10
+1
Counter
Print
Relation
I = 1
1
Same
2
2
Print I
3…
3….
…..
                   CLS
FOR I = 1 TO 10 STEP 1
                             PRINT I ;
                   NEXT I
For Next Loop Guidelines
1.    Always write FOR statement at the top and NEXT at the bottom of the structure.
2.    The counter variable or control variable is a numeric variable that controls the number of repetitions.
3.    The optional STEP clause specifies the step value by which the counter variable will be increased or decreased after each repetition.
4.    Repetition in FOR-NEXT does not take place in either of the following situations:
§  If the starting value is less than the final value, the step is negative.
§  If the starting value is greater than the end value and the step is positive.
5.    Loop does not work if the initial value is bigger than the final value and the step is missing.
Practice Programs:
a.    10     9       8       7       6       up to 10th terms
b.    1       4       9       16     25     up to 10th terms
c.     5       7       10     14     19     up to 10th terms
d.    99     97     95     93     91     up to 10th terms

a)    10          9       8       7       6       up to 10th terms
Start Value
Final Value
Step
1
10
+1
Counter
Print
Relation
1
A = 10
PRINT A
2
9
A =A -1
3
8

….
7


CLS
A=10
FOR I = 1 TO 10 STEP 1
     PRINT A;
A=A-1
NEXT I
END




b)   1            4       9       16     25     up to 10th terms

Start Value
Final Value
Step
1
10
+1
Counter
Print
Relation
I = 1
1
I^2
2
4

3
9

4
16

….
25


CLS
FOR I = 1 TO 10 STEP 1
     PRINT I^2;
NEXT I
END




c)    5            7       10     14     19     up to 10th terms
Start Value
Final Value
Step
1
10
+1
Counter
Print (A=4)
Relation
I = 1
5
A=A+I
2
7
A=A+I
3
10
A=A+I
4
14
A=A+I
….
19


CLS
A=4
FOR I = 1 TO 10 STEP 1
     A=A+I
     PRINT A;
NEXT I
              END




d)   99          97     95     93     91     up to 10th terms

Start Value
Final Value
Step
1
10
+1
Counter
Print(A=99)
Relation
1
99
PRINT A;
2
97
A=A-2
3
95

4
93

…..
91



CLS
A=99
FOR I = 1 TO 10 STEP 1
          PRINT A;
          A=A-2
NEXT I
END