Menu
CoddyTech

Looping Over a Table

Part of the Tables and Text section of Coddy's COBOL Programming journey. Lesson 3 of 19.

PERFORM VARYING walks a table: its counter is the subscript, from 1 to the table's size.

PERFORM VARYING I FROM 1 BY 1 UNTIL I > 5
    ADD SCORE(I) TO TOTAL
END-PERFORM.

The loop ends once I passes the last element. UNTIL I = 5 stops before adding SCORE(5), and UNTIL I > 6 reaches a sixth element that does not exist, which stops the program.

The same loop fills a table from input, one ACCEPT per element:

PERFORM VARYING I FROM 1 BY 1 UNTIL I > 5
    ACCEPT SCORE(I)
END-PERFORM.

Give the counter room for one more than the size. A 9-element table needs I to reach 10, but a PIC 9 counter wraps from 9 to 0 and the loop goes on: here the next pass uses element 0, which stops the program. PIC 99 works.

challenge icon

Challenge

Easy

The program reads 4 sales into the table SALE. Add them all to TOTAL with a loop, so it prints Total: 0100 for 10, 20, 30 and 40.

Example input, one line per ACCEPT: 10, 20, 30, 40.

Try it yourself

       IDENTIFICATION DIVISION.
       PROGRAM-ID. SALES.
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 SALES.
           05 SALE PIC 9(3) OCCURS 4 TIMES.
       01 I PIC 9.
       01 TOTAL PIC 9(4) VALUE ZERO.
       PROCEDURE DIVISION.
           PERFORM VARYING I FROM 1 BY 1 UNTIL I > 4
               ACCEPT SALE(I)
           END-PERFORM.
           *> Add every SALE to TOTAL here
           DISPLAY "Total: " TOTAL.
           STOP RUN.

All lessons in Tables and Text