>>SOURCE FORMAT IS FREE *> cobol-perform-varying.cob - every common loop shape: *> PERFORM n TIMES, UNTIL with TEST BEFORE and TEST AFTER, inline *> VARYING over a table, nested VARYING ... AFTER, and EXIT PERFORM *> Dialect: GnuCOBOL 3.x, free format *> Status : desk-checked against the GnuCOBOL 3.2 Programmer's Guide; *> compiled and run with GnuCOBOL 3.2 on 2026-10-29 *> Inputs : none *> Outputs: nine lines on standard output *> Build : cobc -x cobol-perform-varying.cob *> Run : ./cobol-perform-varying *> (Windows: cobol-perform-varying.exe) IDENTIFICATION DIVISION. PROGRAM-ID. PERFORM-DEMO. ENVIRONMENT DIVISION. DATA DIVISION. WORKING-STORAGE SECTION. 01 WS-Counter PIC 9(2) VALUE 0. 01 WS-Idx PIC 9(2). 01 WS-Row PIC 9. 01 WS-Col PIC 9. 01 WS-Total PIC 9(4) VALUE 0. 01 WS-Squares. 05 WS-Square PIC 9(3) OCCURS 5 TIMES. 01 WS-Grid-Data PIC X(12) VALUE "ABCDEFGHIJKL". 01 WS-Grid REDEFINES WS-Grid-Data. 05 WS-Grid-Row OCCURS 3 TIMES. 10 WS-Cell PIC X OCCURS 4 TIMES. PROCEDURE DIVISION. MAIN-PARAGRAPH. *> 1. Out-of-line PERFORM, a fixed number of times. PERFORM SHOW-TICK 3 TIMES *> 2. UNTIL with the default TEST BEFORE: condition already true, *> so the body never runs. MOVE 10 TO WS-Counter PERFORM WITH TEST BEFORE UNTIL WS-Counter >= 10 DISPLAY "test-before body ran" END-PERFORM *> 3. UNTIL with TEST AFTER: the body always runs at least once. PERFORM WITH TEST AFTER UNTIL WS-Counter >= 10 DISPLAY "test-after body ran once" END-PERFORM *> 4. Inline VARYING over a five-element table. PERFORM VARYING WS-Idx FROM 1 BY 1 UNTIL WS-Idx > 5 COMPUTE WS-Square(WS-Idx) = WS-Idx * WS-Idx ADD WS-Square(WS-Idx) TO WS-Total END-PERFORM DISPLAY "Sum of squares 1..5 : " WS-Total DISPLAY "Index after the loop: " WS-Idx *> 5. Nested VARYING ... AFTER over a 3-row by 4-column grid. PERFORM VARYING WS-Row FROM 1 BY 1 UNTIL WS-Row > 3 AFTER WS-Col FROM 1 BY 1 UNTIL WS-Col > 4 DISPLAY WS-Cell(WS-Row, WS-Col) WITH NO ADVANCING END-PERFORM DISPLAY SPACE *> 6. EXIT PERFORM leaves an inline loop early. PERFORM VARYING WS-Idx FROM 1 BY 1 UNTIL WS-Idx > 5 IF WS-Square(WS-Idx) > 10 DISPLAY "First square over 10: " WS-Square(WS-Idx) EXIT PERFORM END-IF END-PERFORM STOP RUN. SHOW-TICK. ADD 1 TO WS-Counter DISPLAY "tick " WS-Counter.