Menu
CoddyTech

PERFORM VARYING

Part of the Decisions and Loops section of Coddy's COBOL Programming journey. Lesson 14 of 20.

PERFORM ... VARYING runs a paragraph with a counter. It sets the counter FROM a start, tests UNTIL, and adds BY after each pass:

PERFORM PRINT-DAY
    VARYING D FROM 1 BY 1 UNTIL D > 7

The steps are: set D to 1, test, run, add 1, test again. The loop ends when the test is true, so D is 8 afterwards.

BY can be any step, a negative one too. This counts 10, 8, 6, 4, 2:

PERFORM PRINT-ROW
    VARYING I FROM 10 BY -2 UNTIL I < 1

The counter must hold the value that ends the loop. With I PIC 9 and UNTIL I > 9, adding 1 to 9 gives 0 (the 1 is truncated), so I is never above 9 and the loop never ends.

challenge icon

Challenge

Easy

The program reads N. Print its times table from N x 1 to N x 5: PRINT-ROW prints row I, like 3 x 1 = 03.

Example input, one line per ACCEPT: 3.

Try it yourself

       IDENTIFICATION DIVISION.
       PROGRAM-ID. TIMESTAB.
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 N PIC 9.
       01 I PIC 9.
       01 PRODUCT PIC 99.
       PROCEDURE DIVISION.
       MAIN-PARA.
           ACCEPT N.
           *> Perform PRINT-ROW for I from 1 to 5
           STOP RUN.
       PRINT-ROW.
           COMPUTE PRODUCT = N * I.
           DISPLAY N " x " I " = " PRODUCT.

All lessons in Decisions and Loops