Course COBOL
COBOL Cheatsheet
A quick, printable reference for modern and mainframe COBOL: four divisions, fixed-format columns, PIC & COMP-3 layouts, COMPUTE arithmetic, IF/EVALUATE, PERFORM loops, OCCURS tables, batch file I/O, strings, and subprograms. Print to PDF with Ctrl/Cmd + P.
Save or print this cheatsheet as PDF
Print-ready layout: open in one click and save as PDF from your browser, no account or email required.
0. Core COBOL Invariants & Pitfalls to Avoid
Five rules that prevent column-alignment compile errors and silent decimal truncation.
- A trailing period (.) terminates EVERY nested IF or EVALUATE scope — always prefer explicit END-IF / END-EVALUATE inside blocks.
- In fixed format keep strict columns: Col 7 for * (comment), Area A (Col 8–11) for divisions/paragraphs/level 01, Area B (Col 12–72) for statements.
- Use V (PIC 9(4)V99) for implied decimals in arithmetic storage; reserve edited dots (PIC Z,ZZ9.99) strictly for printed output.
- Overflow silently truncates leading digits unless ON SIZE ERROR handles exceeding field capacity.
- End main control flow with STOP RUN. (or GOBACK.): without it, execution falls straight into subsequent paragraphs!
1. Structure & Divisions
Minimal Program
IDENTIFICATION DIVISION. PROGRAM-ID. MINIMAL-PROGRAM. PROCEDURE DIVISION. DISPLAY "Hello from COBOL". STOP RUN.IDENTIFICATION DIVISION, PROGRAM-ID, and PROCEDURE DIVISION are mandatory.
Pitfall: Division headers require trailing periods, whereas mid-block statements inside IF/END-IF should omit periods.
Fixed Format Rules (Col 1–80)
Column 1-6 : Sequence number (optional) Column 7 : Comment (*), continuation (-) Column 8-11 : Area A (Divisions, Sections, Paragraphs, level 01) Column 12-72 : Area B (Statements, data clauses, levels > 01)An asterisk * in column 7 comments the entire line; text past column 72 is ignored.
Pitfall: Starting executable verbs like DISPLAY in column 8 (Area A) or wrapping past column 72 breaks compilation.
2. Variables, PIC & Levels (DATA DIVISION)
Variable Declarations & Sign S
DATA DIVISION. WORKING-STORAGE SECTION. 01 WS-USER-NAME PIC X(20) VALUE "Alice". 01 WS-USER-AGE PIC 9(3) VALUE 25. 01 WS-BALANCE PIC S9(5)V99 VALUE -150.50.PIC X stores alphanumeric text, PIC 9 stores digits, V defines the implied decimal position, and S preserves sign.
Pitfall: Omitting S in front of PIC S9(5)V99 drops the negative sign and silently stores the absolute value!
Opposite Padding & Editing Masks
01 WS-CODE PIC X(6) VALUE "AB". 01 WS-ID PIC 9(5) VALUE 42. 01 WS-AMOUNT PIC Z,ZZ9.99 VALUE ZERO.PIC X left-aligns and right-pads with spaces ("AB "); PIC 9 right-aligns and left-pads with zeros ("00042").
Pitfall: Numeric-edited fields like PIC Z,ZZ9.99 are display-only — never use them inside COMPUTE or ADD!
3. COBOL Arithmetic & COMPUTE
Formal Mathematical Statements
ADD 5 TO WS-COUNTER. ADD WS-VAL-A TO WS-VAL-B GIVING WS-SUM. SUBTRACT 10 FROM WS-TOTAL. MULTIPLY WS-QTY BY WS-PRICE GIVING WS-SUBTOTAL. DIVIDE WS-TOTAL BY 2 GIVING WS-QUOTIENT REMAINDER WS-REM.GIVING stores the result separately without overwriting source operands.
Pitfall: In SUBTRACT A FROM B (without GIVING), B is overwritten — verify operand direction carefully.
COMPUTE ROUNDED & ON SIZE ERROR
COMPUTE WS-FINAL-AMOUNT ROUNDED = (WS-SUBTOTAL * 1.22) - WS-DISCOUNT ON SIZE ERROR DISPLAY "OVERFLOW" END-COMPUTE.Evaluates algebraic expressions (+, -, *, /, **) with optional ROUNDED and overflow trap ON SIZE ERROR.
Pitfall: Without ROUNDED fractional digits are chopped; without ON SIZE ERROR integer overflow truncates high-order digits.
4. Flow Control (IF / EVALUATE)
IF-ELSE Conditionals with END-IF
IF WS-USER-AGE >= 18 DISPLAY "Access granted" ELSE DISPLAY "Access denied" END-IF.Always close conditional blocks cleanly with explicit END-IF.
Pitfall: Putting a stray period after DISPLAY "Access granted" ends the entire IF statement before ELSE!
EVALUATE (Switch-Case & TRUE)
EVALUATE TRUE WHEN WS-AGE < 18 DISPLAY "Minor" WHEN WS-AGE <= 64 DISPLAY "Adult" WHEN OTHER DISPLAY "Senior" END-EVALUATE.Supports ranges via THRU, multi-condition EVALUATE TRUE, and WHEN OTHER fallback.
Pitfall: COBOL does not fall through between WHEN branches — only the first matching branch executes.
5. Paragraphs, PERFORM & Loops
Modular Paragraphs & PERFORM
PROCEDURE DIVISION. MAIN-LOGIC. PERFORM DO-INITIALIZE. DISPLAY "Running...". STOP RUN. DO-INITIALIZE. DISPLAY "Initializing".PERFORM invokes a named paragraph and automatically returns control to the next statement.
Pitfall: Omitting STOP RUN. lets execution fall straight down into DO-INITIALIZE a second time!
TIMES, UNTIL & VARYING Loops
PERFORM 3 TIMES DISPLAY "PING" END-PERFORM. PERFORM VARYING WS-IDX FROM 1 BY 1 UNTIL WS-IDX > 5 DISPLAY "IDX=" WS-IDX END-PERFORM.PERFORM UNTIL / VARYING repeats until its predicate turns TRUE (pre-tested by default).
Pitfall: Inverted compared to C/Java while: UNTIL WS-IDX > 5 means "stop once WS-IDX > 5"!
6. Group Records, REDEFINES & Level 88
Group Items & Contiguous Storage
01 WS-CUSTOMER-REC. 05 WS-CUST-ID PIC 9(6) VALUE 104200. 05 WS-CUST-NAME PIC X(20) VALUE "MARIA ROSSI". 05 WS-ADDR. 10 WS-CITY PIC X(15) VALUE "MILANO". MOVE SPACES TO WS-CUSTOMER-REC.Level numbers (01, 05, 10) aggregate contiguous sub-fields in RAM; DISPLAY prints the entire record string.
Pitfall: Moving into a group item is always alphanumeric — `MOVE SPACES TO WS-GROUP` fills numeric subfields with spaces!
REDEFINES & Condition Names (Level 88)
01 WS-DATE-RAW PIC X(8) VALUE "20261115". 01 WS-DATE-PARTS REDEFINES WS-DATE-RAW. 05 WS-YEAR PIC 9(4). 05 WS-MONTH PIC 9(2). 05 WS-DAY PIC 9(2). 01 WS-STATUS PIC X(1) VALUE "A". 88 STATUS-ACTIVE VALUE "A". 88 STATUS-CLOSED VALUE "C" "X".REDEFINES overlays two layouts on the exact same bytes; level-88 condition names make branches readable (`IF STATUS-ACTIVE`).
Pitfall: The REDEFINES item must immediately follow its target at the same level number and omit VALUE.
7. OCCURS Tables, Indexing & SEARCH
1-Based OCCURS Table
01 WS-PRICE-TABLE. 05 WS-ITEM-PRICE PIC 9(4)V99 OCCURS 12 TIMES. 01 WS-IDX PIC 9(2) VALUE 1. PROCEDURE DIVISION. MOVE 19.90 TO WS-ITEM-PRICE(1). DISPLAY WS-ITEM-PRICE(WS-IDX).OCCURS arrays are ALWAYS 1-based (never 0!). Out-of-bounds indexing silently corrupts adjacent WORKING-STORAGE.
Pitfall: Subscripting `WS-ITEM-PRICE(0)` is a classic bug for developers arriving from C or Java.
INDEXED BY & SEARCH / SEARCH ALL
01 WS-CODE-TABLE. 05 WS-ENTRY OCCURS 50 TIMES ASCENDING KEY IS WS-KEY INDEXED BY TAB-IDX. 10 WS-KEY PIC X(4). 10 WS-DESC PIC X(20). SET TAB-IDX TO 1. SEARCH WS-ENTRY AT END DISPLAY "NOT FOUND" WHEN WS-KEY(TAB-IDX) = "EUR " DISPLAY WS-DESC(TAB-IDX) END-SEARCH.SEARCH runs sequential scan starting at `SET idx TO 1`; `SEARCH ALL` performs binary search $O(\log N)$ on sorted keys.
Pitfall: Forgetting `SET TAB-IDX TO 1` before sequential `SEARCH` resumes from whatever stale index was left over!
8. Batch Sequential File I/O (SELECT / FD / READ / WRITE)
ENVIRONMENT & DATA FILE SECTION
ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT TX-FILE ASSIGN TO "TRANS.DAT" ORGANIZATION IS LINE SEQUENTIAL FILE STATUS IS WS-FS. DATA DIVISION. FILE SECTION. FD TX-FILE. 01 FD-TX-REC PIC X(80).SELECT binds the logical FD name to an external dataset plus an optional two-byte `FILE STATUS` (`"00"` OK, `"10"` EOF).
Pitfall: Reading or writing a file before opening it in matching mode (`INPUT` vs `OUTPUT` / `EXTEND`) causes runtime failure.
Canonical Batch EOF Loop (Priming Read)
OPEN INPUT TX-FILE. READ TX-FILE AT END SET EOF-REACHED TO TRUE END-READ. PERFORM UNTIL EOF-REACHED PERFORM PROCESS-RECORD READ TX-FILE AT END SET EOF-REACHED TO TRUE END-READ END-PERFORM. CLOSE TX-FILE.Using a priming READ before the loop ensures the final record is never processed twice after hitting AT END.
Pitfall: Reading only at the bottom of the loop without a priming read processes garbage or duplicates the last record on EOF!
9. Strings (STRING/UNSTRING/INSPECT) & Subprograms
STRING, UNSTRING & INSPECT
STRING WS-FIRST DELIMITED BY SPACE " " DELIMITED BY SIZE WS-LAST DELIMITED BY SIZE INTO WS-FULL-NAME END-STRING. INSPECT WS-PHONE TALLYING WS-DASHES FOR ALL "-". INSPECT WS-PHONE REPLACING ALL "-" BY "/".DELIMITED BY SPACE strips trailing blanks on PIC X fields; DELIMITED BY SIZE copies the full field width or literal.
Pitfall: Always initialize tally counters (`MOVE ZERO TO WS-DASHES`) before `INSPECT ... TALLYING` because COBOL adds onto existing values!
Modular Subprogram (CALL / LINKAGE / GOBACK)
* Caller CALL "TAXCALC" USING BY CONTENT WS-AMOUNT BY REFERENCE WS-TAX. * Callee (Program ID: TAXCALC) LINKAGE SECTION. 01 LK-AMOUNT PIC 9(5)V99. 01 LK-TAX PIC 9(5)V99. PROCEDURE DIVISION USING LK-AMOUNT LK-TAX. COMPUTE LK-TAX = LK-AMOUNT * 0.22. GOBACK.Arguments map into `LINKAGE SECTION` in exact `USING` order; use `GOBACK` inside reusable subprograms.
Pitfall: Putting `STOP RUN` instead of `GOBACK` / `EXIT PROGRAM` inside a callee terminates the entire batch job instead of returning!
10. SORT, Copybooks, COMP-3 & Legacy Maintenance
COPY (Copybook) & Batch SORT
01 WS-CUSTOMER-REC. COPY CUSTCOPY REPLACING ==:PRE:== BY ==WS-==. SORT SORT-WORK-FILE ON ASCENDING KEY SW-CUST-ID USING INPUT-FILE GIVING SORTED-FILE.`COPY` pulls shared record layouts into many programs; `SORT ... USING/GIVING` sorts entire files natively.
Pitfall: Changing a field PIC inside a copybook without recompiling every consumer program silently breaks binary record offsets.
Packed-Decimal COMP-3 (Exact Accounting)
01 WS-LEDGER-TOTAL PIC S9(9)V99 COMP-3 VALUE 0. 01 WS-PACKED-CNT PIC S9(5) COMP-3 VALUE -12509.COMP-3 packs two BCD digits per byte plus the trailing sign nibble (`ceil((N+1)/2)` bytes): zero binary floating-point rounding error.
Pitfall: Never DISPLAY COMP-3 bytes raw or transfer them in text mode — MOVE them to human-readable PIC 9/Z display fields first!