Title here
Summary here
COBOL provides several ways to implement loops. Here are some basic types of loops in COBOL.
IDENTIFICATION DIVISION.
PROGRAM-ID. FOR-LOOPS.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 I PIC 9(2) VALUE 1.
01 J PIC 9(2) VALUE 0.
01 N PIC 9(2) VALUE 0.
PROCEDURE DIVISION.
MAIN-PROCEDURE.
*> The most basic type, with a single condition.
PERFORM UNTIL I > 3
DISPLAY I
ADD 1 TO I
END-PERFORM
*> A classic initial/condition/after loop.
PERFORM VARYING J FROM 0 BY 1 UNTIL J >= 3
DISPLAY J
END-PERFORM
*> Another way of accomplishing the basic "do this N times" iteration.
PERFORM 3 TIMES
DISPLAY "range" FUNCTION WHEN-COMPILED(7:2)
END-PERFORM
*> PERFORM without a condition will loop indefinitely until EXIT PERFORM.
PERFORM FOREVER
DISPLAY "loop"
EXIT PERFORM
END-PERFORM
*> You can also use CONTINUE to skip to the next iteration of the loop.
PERFORM VARYING N FROM 0 BY 1 UNTIL N >= 6
IF FUNCTION MOD(N, 2) = 0
CONTINUE
ELSE
DISPLAY N
END-IF
END-PERFORM
STOP RUN.
When you run this COBOL program, it will produce the following output:
1
2
3
0
1
2
range 01
range 01
range 01
loop
1
3
5
In COBOL, we use different constructs to achieve looping:
PERFORM UNTIL
is used for condition-based loops.PERFORM VARYING
is used for counter-based loops, similar to the classic for loop in other languages.PERFORM n TIMES
is used to execute a block of code a specific number of times.PERFORM FOREVER
creates an infinite loop that can be exited using EXIT PERFORM
.CONTINUE
can be used to skip to the next iteration of a loop.COBOL doesn’t have a direct equivalent to Go’s range
keyword for iterating over sequences, so we’ve simulated it using PERFORM n TIMES
. The FUNCTION WHEN-COMPILED
is used here just to generate some varying output for each iteration.
COBOL’s looping constructs are powerful and flexible, allowing for various types of iteration and control flow within loops.