Module 3 · Lesson 2 of 26/10 in the course~15 min
Module lessons (2/2)
Loops and Iterations
Loops and iterative constructs in COBOL are not defined by keywords like for or while, but instead use syntactic variations of the same PERFORM statement.
Fixed Numeric Loops (PERFORM TIMES)
If we need to repeat the execution of a paragraph a fixed number of times, we can add the TIMES modifier to the PERFORM command.
Code
PERFORM PROCESS-LINE 10 TIMES.
In this case, the compiler will execute the PROCESS-LINE paragraph exactly 10 times, then resume the linear execution of the code.
Conditional Loops (PERFORM UNTIL)
To iterate until a certain condition becomes true (equivalent to a reversed while loop), we use the PERFORM ... UNTIL statement.
Code
PERFORM INCR-COUNTER UNTIL WS-COUNTER > 5.
Code
PROCEDURE DIVISION.
MAIN-PROCEDURE.
PERFORM PROCESS-ITEM UNTIL WS-COUNTER > 3.
STOP RUN.
PROCESS-ITEM.
DISPLAY "Counter: " WS-COUNTER.
ADD 1 TO WS-COUNTER.
---
## Try it yourself
<CobolExercise
id="cobol.m3.l2.e1"
prompt="Write a statement inside MAIN-PROCEDURE to execute the PROCESS-ITEM paragraph exactly 10 times."
starter={` PROCEDURE DIVISION.\n MAIN-PROCEDURE.\n * WRITE CODE HERE\n STOP RUN.\n`}
solution={` PROCEDURE DIVISION.\n MAIN-PROCEDURE.\n PERFORM PROCESS-ITEM 10 TIMES.\n STOP RUN.\n`}
rules={{
requiredKeywords: ['PERFORM PROCESS-ITEM', '10', 'TIMES.', 'STOP RUN.'],
}}
hint="Use the syntax: PERFORM PROCESS-ITEM 10 TIMES."
/>
<CobolExercise
id="cobol.m3.l2.e2"
prompt="Repeatedly execute the PROCESS-STEP paragraph until the WS-COUNTER variable becomes greater than 5."
starter={` PROCEDURE DIVISION.\n MAIN-PROCEDURE.\n * WRITE CODE HERE\n STOP RUN.\n`}
solution={` PROCEDURE DIVISION.\n MAIN-PROCEDURE.\n PERFORM PROCESS-STEP UNTIL WS-COUNTER > 5.\n STOP RUN.\n`}
rules={{
requiredKeywords: ['PERFORM PROCESS-STEP', 'UNTIL', 'WS-COUNTER', '>', '5', 'STOP RUN.'],
}}
hint="Use the syntax: PERFORM PROCESS-STEP UNTIL WS-COUNTER > 5."
/>