Salt la conținutul principal
Modulul 3 · Lecția 2 din 26/10 în curs~15 min
Lecții din modul (2/2)

Bucle și iterații

Buclele și constructele iterative din COBOL nu sunt definite de cuvinte cheie precum for sau while, ci folosesc variații sintactice ale aceleiași instrucțiuni PERFORM.

Bucle numerice fixe (PERFORM TIMES)

Dacă trebuie să repetăm ​​execuția unui paragraf de un număr fix de ori, putem adăuga modificatorul TIMES la comanda PERFORM.

COBOL
PERFORM PROCESS-LINE 10 TIMES.

În acest caz, compilatorul va executa paragraful PROCESS-LINE de exact 10 ori, apoi va relua execuția liniară a codului.

Bucle condiționate (PERFORM UNTIL)

Pentru a repeta până când o anumită condiție devine adevărată (echivalent cu o buclă while inversată), folosim instrucțiunea 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."
/>