Nested loop in QBASIC
A nested loop is a loop that is contained within another loop. The inner loop will execute fully for each iteration of the outer loop.
Syntax:
FOR variable1 = start1 TO end1 [STEP step1]
FOR
variable2 = start2 TO end2 [STEP step2]
statements
[EXIT FOR]
[statements]
NEXT
[variable2]
[EXIT FOR]
[statements]
NEXT [variable1]
Example:
FOR i = 1 TO 3
FOR
j = 1 TO 4
PRINT i, j
NEXT j
NEXT i
Output:
The outer loop is controlled by the variable i,
and the inner loop is controlled by the variable j. The inner loop will execute
fully for each iteration of the outer loop. In this case, the inner loop will
execute 4 times for each iteration of the outer loop, so it will execute a
total of 3 * 4 = 12 times.
You can solve above program by using sub
procedure in QBasic
DECLARE SUB nested()
CLSthe
CALL nested
END
SUB nested
FOR i = 1 TO 3
FOR
j = 1 TO 4
PRINT i, j
NEXT j
NEXT i
END SUB
You can also use a STEP statement to specify
the amount by which the loop variable should be incremented or decremented on
each iteration.
Example:
FOR i = 1 TO 10 STEP 2
FOR
j = 1 TO 5 STEP 3
PRINT i, j
NEXT j
NEXT i
Output:
The outer loop variable i will be incremented
by 2 on each iteration, and the inner loop variable j will be incremented by 3
on each iteration.
By using WHILE…WEND
Syntax:
WHILE <counter 1> <condition>
WHILE <counter 2> <condition>
[statement]
………………….
WEND
[statement]
………..........
WEND
Example:
CLS i = 5 WHILE i >= 1 j = 5 WHILE j >= i PRINT j; j = j - 1 WEND PRINT i = i - 1 WEND END |
Output
5 54 543 5432 54321
|
By using DO WHILE ……LOOP
Syntax:
DO WHILE <counter 1> <condition>
DO WHILE <counter 2> <condition>
[statement]
………………….
LOOP
[statement]
………..........
LOOP
Example
CLS i = 1 DO WHILE i <= 5 j = 5 DO WHILE j >= i PRINT j; j = j - 1 LOOP PRINT i = i + 1 LOOP END |
Output
54321 5432 543 54 5
|
By using DO…..LOOP WHILE
Syntax:
DO
[statement]
…………….
…………….
DO
[statement]
……………..
……………….
LOOP WHILE <counter 2>
<condition>
[statement]
……………
……………..
LOOP WHILE <counter 1>
<condition>
Example
CLS i = 1 DO j = i DO PRINT j; j = j - 1 LOOP WHILE j >= 1 PRINT i = i + 1 LOOP WHILE i <= 5 END |
Output
1 21 321 4321 54321
|
You may also Read:
No comments:
Post a Comment