Saturday, July 27

FOR and NEXT statements

The FOR and NEXT statement is used to execute a series of instructions a specified number of times in a loop.
Syntax
LN FOR variable = X To Y [STEP  Z]
.
.
.
NEXT [variable][,variable...]
Where,
LN      : Line Number
variable  : variable used as a counter
X, Y and Z  :numeric expressions
STEP  Z  :  specifies the counter increment for each loop.

Points to remember

  • The first numeric expression(x) is the initial value of the counter.
  • The second numeric expression is the final value of the counter.
  • Program lines following the FOR statement are executed until the NEXT statement is encountered. Then the counter is incremented by the amount specified by STEP.
  • When STEP is not mentioned, the increment is considered as 1.
  • It is checked if the value of the counters is greater than the final value(Y). If it is not greater, GW - BASIC branches back to the statement, immediately after the FOR statement, and the process is repeated. If it is greater, execution continues with the statement following the NEXT statement. Hence, FOR and NEXT statement forms a loop (i.e. FOR-NEXT loop)
  • If STEP value is negative, the final value of the counter will be less than the initial value.

Examples

1. 10 For A = 0 To 20   
.
.
.
80 NEXT A
2. For A = 0 To 20 STEP 2
.
.
.
80 NEXT A
3. 10 For A = 20 To 0 STEP-2
.
.
.
30 NEXT A

Use of FOR and NEXT statement in the program.
1. To sum the numbers from 1 to 5000 in step of 7

1. CS 7.3 Display on the screen for FOR and NEXT statement

Ok
LIST
5      REM Learning the use of FOR...NEXT statement
10    S = 0
20    FOR I = 1 TO 5000 STEP  7
30    S =S+I
40    NEXT I
50    PRINT "SUM =" ; S
60    END
Ok  
RUN
SUM = 1787500
Ok


2.To generate the natural number up to 10 (i.e. 1 to 10)

CS 7.4 Display on the screen for FOR and NEXT statement

Ok
LIST
10    REM To generate numbers from 1 to 10
20    FOR I = 1 TO 10
30    PRINT I
40    NEXT I
50    END
Ok
RUN
1
2
3
4
5
6
7
8
9
10
Ok      






No comments:

Post a Comment