Range Over Built in COBOL Here we use PERFORM
to sum the numbers in an array-like structure.
IDENTIFICATION DIVISION .
PROGRAM-ID . RangeExample .
DATA DIVISION .
WORKING-STORAGE SECTION .
01 nums PIC 9(4) OCCURS 3 VALUE 2 , 3 , 4 .
01 sum PIC 9(4) VALUE 0 .
01 i PIC 9(4) .
PROCEDURE DIVISION .
PERFORM VARYING i FROM 1 BY 1 UNTIL i > 3
ADD nums ( i ) TO sum
END-PERFORM
DISPLAY "sum: " sum .
*> To get the index:
PERFORM VARYING i FROM 1 BY 1 UNTIL i > 3
IF nums ( i ) = 3
DISPLAY "index: " ( i - 1 )
END-IF
END-PERFORM .
*> Using PERFORM to iterate over key/value pairs:
01 kvs .
05 kvs1 .
10 key1 PIC X VALUE 'a' .
10 value1 PIC X(10) VALUE 'apple' .
05 kvs2 .
10 key2 PIC X VALUE 'b' .
10 value2 PIC X(10) VALUE 'banana' .
PERFORM VARYING i FROM 1 BY 1 UNTIL i > 2
IF i = 1
DISPLAY "a -> apple"
ELSE
DISPLAY "b -> banana"
END-IF
END-PERFORM .
*> Using PERFORM to iterate over keys:
PERFORM VARYING i FROM 1 BY 1 UNTIL i > 2
IF i = 1
DISPLAY "key: a"
ELSE
DISPLAY "key: b"
END-IF
END-PERFORM .
*> Using PERFORM to iterate over each character in a string:
01 my-string PIC X(4) VALUE 'go' .
01 j PIC 9(4) .
PERFORM VARYING j FROM 1 BY 1 UNTIL j > LENGTH OF my-string
DISPLAY j - 1 " " FUNCTION ORD ( my-string ( j : 1 ))
END-PERFORM .
STOP RUN .
To run this program, save the code into a file named RangeExample.cbl
and compile it using a COBOL compiler like GnuCOBOL.
Example usage:
$ cobc -x -o RangeExample RangeExample.cbl
$ ./RangeExample
sum: 9
index: 1
a -> apple
b -> banana
key: a
key: b
0 103
1 111
This example demonstrates how to iterate over different built-in data structures in COBOL. Now that you understand how to use PERFORM
for various data structures, you can explore more COBOL features.