Module 3 · Les 2 van 26/10 in de cursus~15 min
Modulelessen (2/2)
Lussen en iteraties
Lussen en iteratieve constructies in COBOL worden niet gedefinieerd door trefwoorden als for of while, maar gebruiken in plaats daarvan syntactische variaties van dezelfde PERFORM-instructie.
Vaste numerieke lussen (PERFORM TIMES)
Als we de uitvoering van een alinea een vast aantal keren moeten herhalen, kunnen we de modifier TIMES toevoegen aan de opdracht PERFORM.
COBOL
PERFORM PROCESS-LINE 10 TIMES.In dit geval zal de compiler de paragraaf PROCESS-LINE precies 10 keer uitvoeren en vervolgens de lineaire uitvoering van de code hervatten.
Voorwaardelijke lussen (PERFORM TOT)
Om te herhalen totdat een bepaalde voorwaarde waar wordt (equivalent aan een omgekeerde while lus), gebruiken we de instructie PERFORM ... UNTIL.
COBOL
PERFORM INCR-COUNTER UNTIL WS-COUNTER > 5.COBOL
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."
/>