The Complete Guide to COBOL Programming on z/OS
Learn COBOL on z/OS from the four divisions to files, tables, subprograms, compiling with JCL and reading abends, with complete programs and their output.

COBOL is the language that moves most of the world's money, and a large share of it runs on z/OS, IBM's mainframe operating system. A bank's nightly interest run, an insurer's claims batch, a payroll cycle and a government benefits system are very often COBOL programs on a mainframe, started by a job, reading and writing files and databases, and ending in a return code that a scheduler reads. This guide teaches the language as it is used there. It uses Enterprise COBOL for z/OS 6.4 on z/OS 3.1, and it assumes you can program a little in any language and have never seen a mainframe. By the end you will know how a COBOL program is laid out, how it stores and calculates numbers, how it reads and writes files, how programs call each other, how a job compiles and runs one and how to read the result when it goes wrong. Each topic has a deeper post on this site, listed in the roadmap near the end, and this guide is the map that connects them.
What COBOL on z/OS is for
COBOL, the Common Business-Oriented Language, dates from 1959 and was designed for one kind of work: reading large numbers of records, doing exact decimal arithmetic on them and writing reports and new records. Its strengths follow from that purpose. Decimal arithmetic is exact, with no binary rounding surprises on money. Record layouts are described in the program as fixed-size fields, so a record in a file is the same bytes as a structure in memory. The language is verbose and reads like English, which was meant to let auditors and business analysts follow the logic.
On z/OS, a COBOL program runs in one of several environments:
Batch, a job started by the scheduler, which reads input files or tables and writes output files. Most of this guide is about batch, because it is the simplest and teaches the language fully.
CICS, a transaction server, where the program serves one online request at a time for a terminal user or a web service call.
IMS, a hierarchical database and transaction system, where programs read and write the database through calls.
Db2, where a COBOL program embeds SQL statements and a precompiler turns them into calls.
The language is the same in all four, and the differences are in how data comes in and goes out. A program that does its calculation in a subprogram can be used in batch and online with no change, which is one reason shops put business rules in called programs.
Every Enterprise COBOL program also runs on top of Language Environment, or LE, the runtime that manages storage, files, condition handling and the interface to the operating system for all the languages on z/OS. When you see a message beginning IGZ, it comes from the COBOL part of LE.
The shape of a program
A COBOL program has four divisions, always in the same order:
IDENTIFICATION DIVISION.
PROGRAM-ID. HELLO.
ENVIRONMENT DIVISION.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 WS-MESSAGE PIC X(30) VALUE 'HELLO FROM COBOL ON Z/OS'.
PROCEDURE DIVISION.
DISPLAY WS-MESSAGE
GOBACK.HELLO FROM COBOL ON Z/OSThe identification division names the program. The environment division says how the program connects to its surroundings, mainly the files it uses. The data division declares every variable and record. The procedure division holds the statements that run. A program with no files can leave out the environment division, and the shortest useful program has an identification division and a procedure division.
COBOL source on z/OS is fixed format, and the columns carry meaning:
| Columns | Use |
|---|---|
| 1 to 6 | Sequence numbers, ignored by the compiler |
| 7 | Indicator: * makes the line a comment, - continues a literal |
| 8 to 11 | Area A: division, section and paragraph names, and 01 and 77 level numbers |
| 12 to 72 | Area B: statements and the rest of data descriptions |
| 73 to 80 | Ignored |
That is why a line of code starts with seven spaces, and why a statement that starts in column 8 is read as a paragraph name. Most first-week compile errors come from the column rules, so keep them in mind.
A paragraph is a name in Area A, ended by a full stop, followed by statements. A section groups paragraphs. The statements run from the top of the procedure division in order, and PERFORM and GO TO change the flow. A sentence ends with a full stop. A statement is a verb with its operands, and many verbs have a scope terminator such as END-IF, which closes them explicitly. Use the terminators, and keep full stops for the end of each paragraph, since a stray full stop in the middle ends every open statement and is the cause of many puzzling bugs.
Data: levels, pictures and usage
Everything a program works with is declared in the data division. A declaration has a level number, a name and usually a picture and a usage.
01 CUSTOMER-RECORD.
05 CUST-ID PIC 9(6).
05 CUST-NAME.
10 CUST-FIRST PIC X(8).
10 CUST-LAST PIC X(10).
05 CUST-BALANCE PIC S9(5)V99 COMP-3.The level number says where an item sits in the hierarchy. 01 begins a record, higher numbers up to 49 nest items within it, 77 is a standalone item and 88 names a value of the field above it. An item with items below it is a group, treated as plain text when it is moved or displayed, and an item without is an elementary item, which must have a picture. The numbers 05, 10 and 15 are a habit that leaves room to insert levels later.
The picture clause, PIC, gives the size and kind. The symbols to learn first are:
| Symbol | Meaning |
|---|---|
X | Any character |
9 | A decimal digit |
S | The number is signed. It takes no space, since the sign is stored in the last digit |
V | An implied decimal point, which also takes no space |
Z | A digit, with a leading zero shown as a space. Used in edited fields for output |
, . $ - CR | Insertion and sign symbols for printed numbers |
A count in brackets repeats a symbol, so PIC 9(6) is six digits. A number can have at most 18 digits by default.
The usage clause says how the digits are stored in memory:
DISPLAY, the default, stores one character per digit. It is readable in a dump and slow for arithmetic.COMP, alsoBINARY, stores a binary integer in two, four or eight bytes, and is the choice for counters and subscripts.COMP-3, packed decimal, stores two digits per byte with the sign in the last half-byte, and is the standard for money, since it keeps exact decimal digits in a compact form.COMP-5is native binary, with no truncation to the digits in the picture.
A field's usage must match the file or the caller that supplies its bytes. A packed field read as text, or the other way round, gives garbage, and a packed field that holds invalid digits ends the program with a data exception, the S0C7 abend, the most common COBOL runtime failure.
Working storage and its relatives
The data division has sections that decide where a variable lives. WORKING-STORAGE holds the program's variables, allocated once and kept between calls. LOCAL-STORAGE is allocated and initialised on each call. LINKAGE describes data that belongs to a calling program and arrives as parameters. FILE SECTION describes the records of files.
The VALUE clause sets a starting value. A field with no VALUE has no defined content, so set it before you read it. A VALUE in WORKING-STORAGE is applied once, when the program is first loaded, which matters for subprograms that are called many times, as a flag set in the first call is still set in the second.
Condition names
An 88-level entry gives a readable name to a value of the field above it:
01 WS-STATUS PIC X.
88 ACCOUNT-ACTIVE VALUE 'A'.
88 ACCOUNT-CLOSED VALUE 'C' 'X'.Then IF ACCOUNT-CLOSED replaces IF WS-STATUS = 'C' OR 'X', and SET ACCOUNT-ACTIVE TO TRUE stores A. The literal appears once, in the declaration, and the logic reads like the business rule.
Sharing layouts with COPY
A record layout that several programs use belongs in one library member, a copybook, brought in at compile time with COPY CUSTREC. The compiler finds the member through the SYSLIB DD statement of the compile step. A change to a copybook takes effect only when the programs that copy it are recompiled, so a layout change is also a list of programs to rebuild. COPY ... REPLACING ==:TAG:== BY ==OLD== changes text as it is copied, which lets one layout serve two uses with different names.
Procedure: moving, calculating, deciding, repeating
MOVE
MOVE source TO target copies a value and converts it to the target's picture. Text is padded with spaces on the right or cut on the right. A number is lined up on the decimal point, padded with zeros and cut on the high-order side, silently, so a MOVE of 12345 to a PIC 99 field leaves 45. A move to an edited picture formats the number for printing. A MOVE never rounds.
Arithmetic
The verbs ADD, SUBTRACT, MULTIPLY and DIVIDE have forms with TO, FROM, BY, INTO and GIVING, and read as short English instructions. ADD WS-B TO WS-A puts the sum in WS-A, and ADD WS-B WS-C GIVING WS-TOTAL puts it in a separate field. DIVIDE ... GIVING q REMAINDER r keeps the remainder. For anything with more than one operation, COMPUTE takes an expression:
COMPUTE WS-PAY ROUNDED = WS-HOURS * WS-RATE
ON SIZE ERROR
DISPLAY 'PAY TOO LARGE FOR FIELD'
END-COMPUTEWithout ROUNDED, extra decimals are cut off. With it, the result is rounded to the number of decimals in the target, away from zero at exactly half by default. ON SIZE ERROR runs when the result does not fit or a divisor is zero, and leaves the target unchanged. Use it wherever money or division is involved, because without it a result that is too large loses its high-order digits and the program carries on with a wrong value.
Decisions
IF WS-SCORE >= 50
DISPLAY 'PASS'
ELSE
DISPLAY 'FAIL'
END-IFAn IF tests relational conditions, class conditions such as IS NUMERIC, sign conditions and 88-level names, joined with AND, OR and NOT. Always close it with END-IF. For many cases, EVALUATE is the language's switch:
EVALUATE TRUE
WHEN WS-SCORE >= 90 MOVE 'A' TO WS-GRADE
WHEN WS-SCORE >= 80 MOVE 'B' TO WS-GRADE
WHEN OTHER MOVE 'C' TO WS-GRADE
END-EVALUATEThe first matching WHEN runs, there is no fall through and WHEN OTHER is the default, which you should always write. Text comparisons use the machine's collating sequence, EBCDIC on z/OS, where letters sort before digits, the reverse of ASCII. Test IS NUMERIC on any field that came from outside before you do arithmetic with it.
Loops
COBOL has one looping verb, PERFORM. It runs a block inline, closed by END-PERFORM, or a named paragraph:
PERFORM VARYING WS-I FROM 1 BY 1 UNTIL WS-I > 5
ADD WS-I TO WS-SUM
END-PERFORM
PERFORM 3 TIMES
PERFORM SHOW-LINE
END-PERFORM
PERFORM UNTIL WS-EOF = 'Y'
PERFORM PROCESS-RECORD
PERFORM READ-NEXT
END-PERFORMUNTIL stops when its condition becomes true, tested before each pass unless you write WITH TEST AFTER. A VARYING counter ends one step past the last value used. The third loop is the shape of most batch programs: a priming read before the loop, the processing in the body and the next read at the bottom, which handles an empty file and processes the last record once.
Tables
OCCURS makes a table, with elements numbered from 1:
01 WS-SALES-TABLE.
05 WS-MONTH-SALES PIC 9(5)V99 OCCURS 12 TIMES
INDEXED BY MONTH-IX.You reach an element with a subscript, an ordinary numeric field, as in WS-MONTH-SALES (WS-I), or with an index, a compiler-managed offset that you change with SET. Neither is range-checked unless you compile with SSRANGE, so a subscript of 0 or 13 on a table of 12 silently touches whatever is next in storage, which is a common cause of corrupted variables. Turn SSRANGE on while you test. SEARCH scans a table from the current index, and SEARCH ALL does a binary search on a table declared with ASCENDING KEY and kept in order. Always code AT END.
Text handling
STRING joins items, UNSTRING splits one field at delimiters and INSPECT counts or replaces characters. STRING does not clear its target, so move spaces to it first. Reference modification, WS-NAME (3 : 4), takes four characters starting at position 3. Intrinsic functions cover much more: FUNCTION UPPER-CASE, TRIM, NUMVAL to turn text into a number, INTEGER-OF-DATE and DATE-OF-INTEGER for date arithmetic, and MOD, MAX and MIN. Never add days to a date stored as YYYYMMDD. Convert it to a day number, add and convert back.
Files: the heart of batch COBOL
A batch program reads files and writes files, and the way COBOL connects the two worlds is worth understanding in full, because it explains the JCL as much as the program.
From program name to data set
Inside the program, a file has a name and a layout. Outside it, a data set has a name on disk. They meet at a DD statement in the JCL of the step. The SELECT entry names the DD:
FILE-CONTROL.
SELECT ORDER-FILE ASSIGN TO ORDERS
ORGANIZATION IS SEQUENTIAL
FILE STATUS IS WS-ORD-STATUS.and the job supplies it:
//ORDERS DD DISP=SHR,DSN=PROD.SALES.ORDERSThe name after ASSIGN TO is the DD name, one to eight characters. Older programs write UT-S-ORDERS, and the compiler drops the prefix. The data set name lives only in the JCL, so one load module can run against a test file today and a production file tomorrow. A missing DD gives a file status of 35 at open.
The file's layout comes from the FD:
FD ORDER-FILE
RECORDING MODE IS F
BLOCK CONTAINS 0 RECORDS.
01 ORDER-RECORD.
05 ORD-ID PIC 9(6).
05 ORD-CUST PIC X(10).
05 ORD-QTY PIC 9(3).
05 ORD-PRICE PIC 9(5)V99.
05 FILLER PIC X(54).RECORDING MODE IS F means fixed-length records and BLOCK CONTAINS 0 RECORDS takes the block size from the JCL or the data set label, which is the usual practice. The record length must equal the LRECL of the data set, 80 here, or the open fails with status 39.
Reading and writing
The statements are OPEN, READ, WRITE and CLOSE. READ file AT END handles the end. WRITE record FROM area moves a working-storage line to the record and writes it. OPEN INPUT reads, OPEN OUTPUT creates or replaces and OPEN EXTEND appends. A report written with WRITE ... AFTER ADVANCING gets a carriage-control character, so the data set needs RECFM=FBA and an LRECL one byte longer than the line.
File status
Declare a FILE STATUS field for every file and test it after every operation. 00 is success, 10 is end of file, 22 and 23 are duplicate and missing keys on indexed files, 35 is a missing file, 39 is a mismatch between the program and the data set, and the codes beginning with 9 come from VSAM. With a status field declared, the runtime does not stop the program when an operation fails, so an unchecked failure leaves a program that runs to completion with a return code of 0 and no output. Put the check in one paragraph and perform it after each statement, set RETURN-CODE to a value your scheduler understands and end with GOBACK.
VSAM files
The other file type you will meet constantly is VSAM, IBM's indexed file system, in which a key-sequenced data set holds records in key order behind an index. COBOL reads it through ORGANIZATION IS INDEXED with a RECORD KEY:
SELECT CUST-FILE ASSIGN TO CUSTVSAM
ORGANIZATION IS INDEXED
ACCESS MODE IS DYNAMIC
RECORD KEY IS CUST-ID
FILE STATUS IS WS-STATUS.The key's length and position must match the definition of the cluster, which an IDCAMS job created. READ by key finds a record, REWRITE replaces the one just read and must not change the key, WRITE adds, DELETE removes, and START with READ NEXT browses from a key onward. The INVALID KEY phrase handles a missing or duplicate key. Programs need no VSAM-specific code beyond that, and the catalog supplies record length and block information, so the DD statement is a name and a disposition. How to create, load and tune these files is the subject of the VSAM posts in this series.
Programs that call programs
A real application is a set of programs. The CALL statement runs another, and the USING phrase passes data:
CALL 'LINECALC' USING BY CONTENT WS-QTY
BY CONTENT WS-PRICE
BY REFERENCE WS-TOTALThe called program names the parameters in its LINKAGE SECTION and in the header PROCEDURE DIVISION USING. Arguments match by position, never by name. By reference, the default, passes the address of the caller's field, so the subprogram can change it, and this is how results come back. By content passes a copy, which protects the caller's variable. By value passes the value itself, for calls to C and other languages. The compiler does not check that the caller's arguments and the callee's linkage items agree in number or size, so a mismatch gives wrong data or an S0C4 abend with no compile-time warning. Share the parameter layout through a copybook.
A subprogram ends with GOBACK, which returns to the caller. STOP RUN ends the entire run unit and is almost always wrong in a subprogram. EXIT PROGRAM returns from a subprogram and does nothing in a main program, so use GOBACK everywhere.
A CALL with a literal is static by default: the called program is copied into the caller's load module at link-edit, which makes the call fast and means a change to the subprogram needs a relink of every caller. A CALL with a data name, or any call under the DYNAM compiler option, is dynamic: the subprogram stays in its own load module, is loaded at the first call from the library search order and can be replaced alone. A dynamic call to a module that is missing ends with an S806 abend unless you code ON EXCEPTION. CANCEL frees a dynamic subprogram and resets its working storage.
Building a program on z/OS
Compiling a program takes three steps. The compiler turns the source into an object module, the binder (the linkage editor) combines object modules into an executable load module in a library, and the system loads and runs it. IBM supplies cataloged JCL procedures that bundle these, and IGYWCLG compiles, link-edits and runs:
//ORDRJOB JOB (ACCT),'ORDER REPORT',CLASS=A,MSGCLASS=X,
// NOTIFY=&SYSUID
//CLG EXEC IGYWCLG,LNGPRFX='IGY.V6R4M0',LIBPRFX='CEE',
// PARM.COBOL='LIST,MAP,XREF,SSRANGE'
//COBOL.SYSIN DD DISP=SHR,DSN=USER01.COBOL.SOURCE(ORDERRPT)
//COBOL.SYSLIB DD DISP=SHR,DSN=USER01.COPYLIB
//LKED.SYSLMOD DD DISP=SHR,DSN=USER01.COBOL.LOAD(ORDERRPT)
//GO.ORDERS DD DISP=SHR,DSN=USER01.SALES.ORDERS
//GO.SYSOUT DD SYSOUT=*The IGYWCL procedure stops after the link, which is what a build job uses, and IGYWCG compiles and runs through the loader. A step-qualified DD such as COBOL.SYSIN overrides the procedure's DD of that name.
Once the load module exists, a plain job runs it, with STEPLIB pointing at the library and the data DDs for the program:
//RUNORDR EXEC PGM=ORDERRPT
//STEPLIB DD DISP=SHR,DSN=USER01.COBOL.LOAD
//ORDERS DD DISP=SHR,DSN=USER01.SALES.ORDERS
//SYSOUT DD SYSOUT=*Compiler options
Options are passed in PARM.COBOL or in a CBL statement at the top of the source. The ones to know early:
| Option | Effect |
|---|---|
LIST, MAP, XREF | Print the generated code, a map of data and a cross reference of names |
SSRANGE | Check subscripts, indexes and reference modification at run time |
DYNAM | Make every CALL with a literal dynamic |
TRUNC(STD, OPT, BIN) | Decide how binary fields are truncated to their picture |
ARITH(COMPAT, EXTEND) | Allow 18 or 31 digits in numeric fields and intermediate results |
OPT(0, 1, 2) | The optimisation level |
Test with SSRANGE and no optimisation, then decide with the performance team which options production uses, since the same source can behave differently under different settings.
Reading the result
The job log shows a condition code for each step: 0 is success, 4 is a warning, 8 an error, 12 a severe error and 16 a critical one. The compile listing shows your source with line numbers and every diagnostic with a message number such as IGYPS2121-S, where the last letter is the severity. Fix the first message and recompile, because the first often causes the next dozen. The GO step's SYSOUT holds what your DISPLAY statements wrote.
When a program fails
A COBOL program can fail in the compiler, in the binder, at run time with an abend or with a wrong answer and a clean return code. Each has its own habits.
Compile errors are almost always column mistakes, a missing full stop after a data description, a name that is not declared or a misspelling. Read the first message.
Link errors report unresolved external references: a static CALL to a program the binder could not find in the libraries on SYSLIB. Add the library or the INCLUDE.
Abends are the system's way of stopping a program that did something it could not allow. The four you will meet most:
| Abend | Meaning | Usual COBOL cause |
|---|---|---|
S0C7 | Data exception | A numeric field, often packed or zoned, holds invalid data such as spaces |
S0C4 | Protection or addressing exception | A subscript out of range, a linkage item that was not passed or a file buffer used after close |
S806 | Program not found | A dynamic CALL or EXEC PGM= names a module that is not in any library searched |
S322 or S522 | Time limit or wait limit | A loop that never ends, or a job waiting for a resource |
The Language Environment message that goes with an abend gives the program name and the offset of the failing instruction, and the compile listing with LIST lets you map the offset to a source line. A debugging tool such as IBM z/OS Debugger shows the program line by line, but a good habit is to test with DISPLAY statements and small inputs first.
For S0C7, find the field. Test every input field with IS NUMERIC before using it, and check that the record layout in the program matches the file, since a layout that is shifted by one byte is the most common reason that a good file looks bad.
Wrong answers with a clean return code come from truncation and from unchecked file statuses. Add ON SIZE ERROR to arithmetic, test the status of every file operation and compare the counts of records read and written with what the input should produce.
A complete program: an order report
This program ties the pieces together. It reads a file of orders, calls a subprogram to calculate each line total, prints a report line with edited fields and prints a count and a grand total at the end.
The subprogram:
IDENTIFICATION DIVISION.
PROGRAM-ID. LINECALC.
DATA DIVISION.
LINKAGE SECTION.
01 LK-QTY PIC 9(3).
01 LK-PRICE PIC 9(5)V99.
01 LK-TOTAL PIC 9(7)V99.
PROCEDURE DIVISION USING LK-QTY LK-PRICE LK-TOTAL.
COMPUTE LK-TOTAL ROUNDED = LK-QTY * LK-PRICE
ON SIZE ERROR
MOVE ZERO TO LK-TOTAL
END-COMPUTE
GOBACK.The main program:
IDENTIFICATION DIVISION.
PROGRAM-ID. ORDERRPT.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT ORDER-FILE ASSIGN TO ORDERS
ORGANIZATION IS SEQUENTIAL
FILE STATUS IS WS-ORD-STATUS.
DATA DIVISION.
FILE SECTION.
FD ORDER-FILE
RECORDING MODE IS F
BLOCK CONTAINS 0 RECORDS.
01 ORDER-RECORD.
05 ORD-ID PIC 9(6).
05 ORD-CUST PIC X(10).
05 ORD-QTY PIC 9(3).
05 ORD-PRICE PIC 9(5)V99.
05 FILLER PIC X(54).
WORKING-STORAGE SECTION.
01 WS-ORD-STATUS PIC XX.
01 WS-EOF PIC X VALUE 'N'.
88 END-OF-ORDERS VALUE 'Y'.
01 WS-COUNT PIC 9(3) VALUE 0.
01 WS-LINE-TOTAL PIC 9(7)V99.
01 WS-GRAND-TOTAL PIC 9(9)V99 VALUE 0.
01 DETAIL-LINE.
05 DL-ID PIC 9(6).
05 FILLER PIC X VALUE SPACE.
05 DL-CUST PIC X(10).
05 FILLER PIC X VALUE SPACE.
05 DL-QTY PIC ZZ9.
05 FILLER PIC XX VALUE SPACES.
05 DL-PRICE PIC ZZ,ZZ9.99.
05 FILLER PIC XX VALUE SPACES.
05 DL-TOTAL PIC Z,ZZZ,ZZ9.99.
01 WS-TOTAL-OUT PIC Z,ZZZ,ZZ9.99.
PROCEDURE DIVISION.
0000-MAIN.
OPEN INPUT ORDER-FILE
IF WS-ORD-STATUS NOT = '00'
DISPLAY 'OPEN FAILED, STATUS=' WS-ORD-STATUS
MOVE 16 TO RETURN-CODE
GOBACK
END-IF
PERFORM 1000-READ-ORDER
PERFORM UNTIL END-OF-ORDERS
PERFORM 2000-PRINT-ORDER
PERFORM 1000-READ-ORDER
END-PERFORM
CLOSE ORDER-FILE
MOVE WS-GRAND-TOTAL TO WS-TOTAL-OUT
DISPLAY 'ORDERS READ: ' WS-COUNT
DISPLAY 'GRAND TOTAL: ' WS-TOTAL-OUT
GOBACK.
1000-READ-ORDER.
READ ORDER-FILE
AT END SET END-OF-ORDERS TO TRUE
END-READ.
2000-PRINT-ORDER.
CALL 'LINECALC' USING BY CONTENT ORD-QTY
BY CONTENT ORD-PRICE
BY REFERENCE WS-LINE-TOTAL
ADD WS-LINE-TOTAL TO WS-GRAND-TOTAL
ADD 1 TO WS-COUNT
MOVE ORD-ID TO DL-ID
MOVE ORD-CUST TO DL-CUST
MOVE ORD-QTY TO DL-QTY
MOVE ORD-PRICE TO DL-PRICE
MOVE WS-LINE-TOTAL TO DL-TOTAL
DISPLAY DETAIL-LINE.Suppose the ORDERS data set holds three 80-byte records, shown here without their padding, with the price in hundredths in seven digits:
100001ACME 0100012550
100002GLOBEX 0050004000
100003ACME 0030010000The job prints:
100001 ACME 10 125.50 1,255.00
100002 GLOBEX 5 40.00 200.00
100003 ACME 3 100.00 300.00
ORDERS READ: 003
GRAND TOTAL: 1,755.00Check it by hand: 10 at 125.50 is 1,255.00, 5 at 40.00 is 200.00, 3 at 100.00 is 300.00, and the sum is 1,755.00.
Look at what each part of the guide does here. The FD mirrors the file's 80-byte layout. The ASSIGN TO ORDERS ties the file to the ORDERS DD. The priming read and the UNTIL END-OF-ORDERS loop handle an empty file and process the last record once. The 88-level name keeps the literal 'Y' in one place. The subprogram receives two inputs by content and returns the total by reference, and it uses ON SIZE ERROR. The edited fields format the numbers, and RETURN-CODE reports a failed open.
A production version would also test the status after every read, check ORD-QTY and ORD-PRICE with IS NUMERIC before the call, write the report to a file with carriage control and count rejected records. Those are the habits the earlier sections describe, and adding them is the first exercise to try.
Habits of maintainable COBOL
Programs on z/OS live for decades, so the cheapest improvement you can make is to write for the next reader.
Use scope terminators for every statement that has one, and keep one full stop at the end of each paragraph.
Name paragraphs by what they do and number them, such as
2000-PRINT-ORDER, so a reader can find them in a long listing and see the structure.Keep each paragraph short enough to read at once, and let the main paragraph read like an outline.
Declare condition names for every code, and never write a code literal in the procedure division.
Put shared layouts in copybooks, and record in each copybook which files and programs use it.
Avoid
GO TOandALTER, and usePERFORMinstead. A program with only structured flow is far easier to change.Test boundary values: zero, one, the largest and a negative where the field allows it.
Initialise every field before you read it, and do not rely on a
VALUEclause for a subprogram variable that must be reset on each call.Write the business rule in a comment above the statements that implement it, particularly rounding and truncation rules.
Newer features of the language let you work with modern data as well. Enterprise COBOL can parse and generate JSON and XML with JSON PARSE and JSON GENERATE, call Java and C programs through the interoperability rules, and run in a program that serves a web service through CICS. Those build on the same foundations: fixed fields, exact decimals, files and calls.
Reading a compile listing
The compiler listing is the most useful document a COBOL programmer has, and it is worth reading properly once. With the options LIST, MAP and XREF, it has several parts in a fixed order.
The first part is the option summary: the options in force, including those the installation set as defaults and those you passed. When a program behaves differently in two places, compare this part first. The second is the source listing, with a line number for every line, a marker beside lines brought in by COPY, and the diagnostic messages placed after the lines they refer to. Each message has an identifier that starts with IGY, a number and a severity letter: I informational, W warning, E error, S severe and U unrecoverable. A program with only I and W messages compiles to a module that runs. One with E messages may produce a module that misbehaves, and one with S messages usually produces nothing useful.
The third part is the data map, which lists every data item with its level, its offset from the start of its record, its length and its usage. This is where you check a record layout against a file: add up the lengths and compare the total with the LRECL, and compare each offset with the layout in the file documentation. The cross reference lists every name with the line numbers that define and use it, which finds a variable that is set in one paragraph and never read, or the reverse. The generated code, from the LIST option, is for the cases where you need to turn an abend offset into a source line: the listing shows the machine instructions for each statement with their offsets.
The listing ends with a summary line, which states the number of statements flagged and the return code of the compile. Read the end first to see whether the compile worked, then go to the first diagnostic.
Db2, CICS and the precompilers
Most COBOL programs on z/OS touch a database or run online, and the language handles both with embedded statements that a translator turns into calls before the compiler sees them. In a Db2 program you write SQL between EXEC SQL and END-EXEC, in the procedure division and in the working storage:
EXEC SQL
SELECT NAME, BALANCE
INTO :CUST-NAME, :CUST-BALANCE
FROM CUSTOMER
WHERE CUST_ID = :CUST-ID
END-EXECThe colon marks a host variable, a COBOL field that holds the value. After each statement, the program checks SQLCODE, a field in the communication area SQLCA: zero means success, 100 means no row was found and a negative number is an error. A Db2 program is processed by a precompiler or by the compiler's own SQL coprocessor, then compiled and linked with a Db2 interface module, and it is bound into a package that records the access paths. The extra build steps are why Db2 shops have their own compile procedures, and your site will give you the one to use.
In CICS, a program receives the request and ends with a return to CICS, using EXEC CICS commands in the same style:
EXEC CICS READ FILE('CUSTFIL')
INTO(CUST-REC)
RIDFLD(CUST-ID)
RESP(WS-RESP)
END-EXECA CICS program does not use OPEN, READ and CLOSE for its files, because CICS owns them. It checks the response code in RESP after each command and ends with EXEC CICS RETURN or GOBACK. It must never use STOP RUN, and it must not keep state in working storage between requests, since each task has its own copy. The business logic that the earlier sections describe, calculations, validation and table lookups, moves unchanged into a subprogram that both the batch program and the CICS program call, and that is the arrangement most shops aim for.
Checking a program before it ships
A COBOL program that has compiled has not been tested. A short routine catches most problems before a program reaches production.
Start with the data. Prepare a small test input that holds an ordinary record, an empty file, a single record, a record at each boundary of a decision, the largest and smallest values each numeric field can take and a record with bad data in each numeric field. Work out the expected output by hand for each case before you run, and keep the expected results with the input in the test library. A program that has been run only on good data has not been run.
Next, read the output against the input, not just for the totals. Compare record counts in and out, with the number of rejected records, so that the totals reconcile: records read equals records written plus records rejected. A program that reads a thousand records and writes nine hundred and ninety-nine with a clean return code has dropped one, and a count printed at the end is how you find it.
Then compile with SSRANGE and with a check on every file status, and run again, so that table subscripts and file errors show up as messages instead of silent corruption. Run once more with the production compiler options, since the optimiser and the TRUNC option can change results in programs that depend on truncation.
Finally, review the job's condition codes and messages. A step that ends with code 4 has a warning that someone decided was acceptable. Find out what it is, and write it down if it is part of the normal run, so that the next code 4 that is not normal stands out.
The part JCL plays
Every COBOL batch program lives inside a job, and the JCL deserves the same care as the program. A job has JOB, EXEC and DD statements. The JOB statement names the job and says how to run it. Each EXEC runs a program or a procedure as a step, and a step ends with a condition code. Each DD supplies a file to the step, by data set name or by data in the job stream or by sending output to the print queue with SYSOUT=*.
Conditions link the steps. In a job with a compile, a link and a run, you want the run to happen only if the earlier steps worked, and COND on the step or an IF block does that. The disposition on each output file says what happens to it at the end of the step: DISP=(NEW,CATLG,DELETE) creates the data set, catalogs it if the step ends well and deletes it if the step abends, which keeps a half-written file from lying around. A rerun of a job that created a file will fail unless the file was deleted first, and designing jobs so that they can be rerun safely is a skill of its own.
The JCL and the program meet in three places: the DD names, the record attributes and the return code. Check all three whenever a job fails to start, produces nothing or ends with an unexpected code, before you look anywhere else.
Where to go next
The topics of this guide are the first rungs of a longer ladder. The roadmap lists each with the kind of question it answers, and the posts on this site go deeper into each.
| Topic | The question it answers |
|---|---|
| The four divisions | How is a COBOL program laid out, and which columns matter |
| Compiling and running | How do I turn source into a running job with JCL |
| PIC clauses and level numbers | How are fields declared and edited |
Arithmetic and COMPUTE | How do I calculate exactly, round and catch overflow |
IF, EVALUATE and PERFORM | How do I decide and repeat |
Tables, SEARCH and SEARCH ALL | How do I hold and look up lists |
| Sequential files, file status and DD mapping | How do I read and write files and find out why they fail |
COPY members | How do I share record layouts |
COMP, COMP-3 and COMP-5 | How are numbers stored, and why do records look wrong |
CALL, static and dynamic | How do programs call each other |
| VSAM from COBOL | How do I read and update an indexed file |
Strings, functions and REDEFINES | How do I handle text, dates and alternate views of data |
A sensible order for a newcomer is the one in the table: first write and run the small programs, then files, then subprograms, and only then the storage details and VSAM. Write a small program for each topic, run it, and read the compiler listing and the output in detail. Understanding what the listing tells you is a skill that pays for itself in every later task.
Reference material for everything here is in the Enterprise COBOL for z/OS documentation, in the Language Reference and the Programming Guide, and the job control details are in the z/OS documentation under MVS JCL Reference.


