This code causes S0C4. Find the bug:
01 WS-TABLE.
05 WS-ITEM PIC X(10) OCCURS 10 TIMES.
01 WS-IDX PIC 99 VALUE 0.
PERFORM VARYING WS-IDX FROM 0 BY 1 UNTIL WS-IDX > 10
DISPLAY WS-ITEM(WS-IDX)
END-PERFORM.
Fix the Subscript Error
Problem Description
Expected Output
Should display all 10 items
Hints
COBOL subscripts start at 1, not 0.
Solution
IDENTIFICATION DIVISION.
PROGRAM-ID. FIXS0C4.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 WS-TABLE.
05 WS-ITEM PIC X(10) OCCURS 10 TIMES.
01 WS-IDX PIC 99.
PROCEDURE DIVISION.
* BUG: Subscript started at 0 and went to 11 (> 10)
* FIX: Start from 1, stop at 10 (not > 10)
PERFORM VARYING WS-IDX FROM 1 BY 1 UNTIL WS-IDX > 10
DISPLAY "ITEM " WS-IDX ": " WS-ITEM(WS-IDX)
END-PERFORM.
STOP RUN.
Explanation:
COBOL arrays are 1-indexed. Subscript 0 or beyond OCCURS causes S0C4.