BudiBadu Logo
Samplebadu

COBOL by Example: PERFORM Loops

COBOL 2002

Understanding iteration with the versatile PERFORM statement handling all loop types in COBOL, implementing simple fixed repetition with PERFORM TIMES, creating counter-based loops with PERFORM VARYING for initialization increment and termination, using PERFORM UNTIL for conditional iteration like while loops, and utilizing inline perform blocks with END-PERFORM for localized logic.

Code

       IDENTIFICATION DIVISION.
       PROGRAM-ID. LOOPS.
       
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  I           PIC 99.
       
       PROCEDURE DIVISION.
           *> Simple loop
           PERFORM 3 TIMES
               DISPLAY "Hello"
           END-PERFORM.
           
           *> Loop with counter
           PERFORM VARYING I FROM 1 BY 1 UNTIL I > 5
               DISPLAY "Count: " I
           END-PERFORM.
           STOP RUN.

Explanation

Loops in COBOL are handled by the PERFORM statement. Unlike other languages with distinct for, while, and do-while loops, COBOL uses variations of PERFORM to handle all iteration needs. It is one of the most versatile verbs in the language.

The VARYING phrase is particularly powerful. It allows you to initialize a counter (FROM), specify the increment (BY), and define the termination condition (UNTIL) all in one readable sentence. You can even nest loops by adding AFTER clauses to the VARYING statement.

Modern COBOL encourages the use of inline PERFORM blocks (terminated by END-PERFORM) rather than performing a separate paragraph. This keeps the logic localized and easier to read, similar to code blocks in C-style languages.

  • Simple Repetition: PERFORM 3 TIMES executes a block a fixed number of times.
  • Conditional Loop: PERFORM UNTIL condition acts like a while loop, checking the condition before each iteration.
  • Inline Loop: PERFORM VARYING... is the equivalent of a for-loop, managing a counter variable automatically.

Code Breakdown

10
PERFORM 3 TIMES. The simplest loop form. It executes the body exactly 3 times.
11
DISPLAY "Hello". This statement is repeated 3 times.
12
END-PERFORM. Marks the end of the inline loop block.
15
PERFORM VARYING I FROM 1 BY 1 UNTIL I > 5. This initializes I to 1, increments it by 1 after each iteration, and stops when I > 5.
16
DISPLAY "Count: " I. Prints the current value of the counter variable I.