Skip to content
Volume C · The TensorCore.si Library

COBOL

The business language that runs the world's money.

COBOL (COmmon Business-Oriented Language) was designed in 1959 for business data processing. It still runs core systems at banks, insurers and governments, handling a huge share of daily financial transactions on mainframes. AI tools are now being used to understand and modernise these systems.

Prologue

Why learn COBOL?

COBOL developers are scarce and in demand, and AI-assisted modernisation of COBOL is a fast-growing field.

  • Critical systems: banks and governments rely on COBOL every day.
  • Exact decimals: fixed-point maths avoids rounding errors with money.
  • Modernisation: translating and documenting COBOL with LLMs is a hot area.
Prologue

Set up and run your first program

Install GnuCOBOL to compile COBOL on Linux, macOS or Windows (WSL).

terminal
sudo apt install gnucobol
cobc -x -free hello.cob -o hello
./hello
hello.cob
IDENTIFICATION DIVISION.
PROGRAM-ID. HELLO.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 WS-NAME PIC X(10) VALUE "Ada".
PROCEDURE DIVISION.
    DISPLAY "Hello, AI! Welcome to COBOL, " FUNCTION TRIM(WS-NAME) "."
    STOP RUN.
Tip-free allows free-format source. Classic COBOL uses fixed columns (code starts at column 8).
Chapter 1

Divisions and program structure

Every program has up to four divisions: IDENTIFICATION (name), ENVIRONMENT (files and system), DATA (variables) and PROCEDURE (logic). Statements end with a period.

structure.cob
IDENTIFICATION DIVISION.
PROGRAM-ID. STRUCTURE.
ENVIRONMENT DIVISION.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 WS-LAYERS PIC 9(3) VALUE 32.
PROCEDURE DIVISION.
    DISPLAY "Model has " WS-LAYERS " layers"
    STOP RUN.
Chapter 2

PIC clauses and records

PIC (picture) describes each field: 9 is a digit, X a character, V an implied decimal point and S a sign. Level numbers build nested records.

data.cob
WORKING-STORAGE SECTION.
01 WS-GPU.
   05 WS-GPU-NAME   PIC X(12)  VALUE "H100".
   05 WS-GPU-VRAM   PIC 9(3)   VALUE 80.
   05 WS-GPU-PRICE  PIC 9(6)V99 VALUE 25000.00.
01 WS-PRICE-OUT     PIC $$$,$$9.99.
PROCEDURE DIVISION.
    MOVE WS-GPU-PRICE TO WS-PRICE-OUT
    DISPLAY WS-GPU-NAME " " WS-GPU-VRAM "GB " WS-PRICE-OUT
    STOP RUN.
Chapter 3

Arithmetic

COBOL uses English verbs (ADD, SUBTRACT, MULTIPLY, DIVIDE) or COMPUTE for formulas. Decimal fields keep money exact; ROUNDED controls rounding.

arithmetic.cob
WORKING-STORAGE SECTION.
01 WS-HOURS   PIC 9(4)     VALUE 720.
01 WS-RATE    PIC 9(2)V99  VALUE 2.49.
01 WS-COST    PIC 9(6)V99.
01 WS-TAX     PIC 9(5)V99.
PROCEDURE DIVISION.
    MULTIPLY WS-HOURS BY WS-RATE GIVING WS-COST
    COMPUTE WS-TAX ROUNDED = WS-COST * 0.22
    ADD WS-TAX TO WS-COST
    DISPLAY "Monthly GPU cost: " WS-COST
    STOP RUN.
Chapter 4

IF, EVALUATE and PERFORM

IF and EVALUATE (like switch) make decisions. PERFORM runs paragraphs or loops with VARYING and UNTIL.

control.cob
WORKING-STORAGE SECTION.
01 WS-I    PIC 9(2).
01 WS-BITS PIC 9(2) VALUE 8.
PROCEDURE DIVISION.
    PERFORM VARYING WS-I FROM 1 BY 1 UNTIL WS-I > 3
        DISPLAY "Epoch " WS-I
    END-PERFORM
    EVALUATE WS-BITS
        WHEN 32 DISPLAY "FP32"
        WHEN 16 DISPLAY "FP16"
        WHEN 8  DISPLAY "FP8"
        WHEN OTHER DISPLAY "other"
    END-EVALUATE
    PERFORM SHOW-DONE
    STOP RUN.
SHOW-DONE.
    DISPLAY "Training complete".
Chapter 5

Reading files

Batch processing of record files is COBOL's core job. Files are declared in the ENVIRONMENT and DATA divisions and read record by record.

files.cob
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
    SELECT TXN-FILE ASSIGN TO "txns.dat" ORGANIZATION IS LINE SEQUENTIAL.
DATA DIVISION.
FILE SECTION.
FD TXN-FILE.
01 TXN-REC.
   05 TXN-ID     PIC X(6).
   05 TXN-AMOUNT PIC 9(5)V99.
WORKING-STORAGE SECTION.
01 WS-EOF   PIC X VALUE "N".
01 WS-TOTAL PIC 9(9)V99 VALUE 0.
PROCEDURE DIVISION.
    OPEN INPUT TXN-FILE
    PERFORM UNTIL WS-EOF = "Y"
        READ TXN-FILE AT END MOVE "Y" TO WS-EOF
            NOT AT END ADD TXN-AMOUNT TO WS-TOTAL
        END-READ
    END-PERFORM
    CLOSE TXN-FILE
    DISPLAY "Total: " WS-TOTAL
    STOP RUN.
Part II · AI with COBOL

AI and COBOL

The big AI story for COBOL is modernisation. Banks and governments use LLMs to explain old programs, generate documentation and tests, and translate COBOL into Java or other languages. Tools such as IBM watsonx Code Assistant for Z target this work, and general coding assistants can read COBOL well. Mainframes also run AI inference on-chip (IBM Telum) to score transactions for fraud in real time.

The essential libraries

IBM watsonx Code Assistant for ZAI-assisted COBOL understanding and translation.
GnuCOBOLFree compiler for learning and testing.
ZoweOpen-source tools to work with mainframes.
LLM coding assistantsExplain, document and test COBOL code.

Explain COBOL with a local LLM

A Python helper that sends a COBOL program to a local model and asks for a plain-English explanation, a common modernisation step.

explain.py
from openai import OpenAI
from pathlib import Path

client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")
source = Path("files.cob").read_text()

prompt = ("Explain what this COBOL program does in plain English, list its inputs and outputs, "
          "and suggest equivalent Python.\n\n" + source)
reply = client.chat.completions.create(model="llama3.1",
    messages=[{"role": "user", "content": prompt}])
print(reply.choices[0].message.content)
Part III · Build an AI agent

A COBOL modernisation agent

This agent can compile and run COBOL as a tool, so the model can test its own understanding: it reads a program, runs it with GnuCOBOL and reports what happened.

Your goal→Model plans→Tool call→Your code runs the tool→Result back to model→Final answer
agent.py
import json, subprocess
from openai import OpenAI

client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")

def run_cobol(path):
    build = subprocess.run(["cobc", "-x", "-free", path, "-o", "prog"], capture_output=True, text=True)
    if build.returncode: return "Compile error:\n" + build.stderr
    return subprocess.run(["./prog"], capture_output=True, text=True, timeout=10).stdout

tools = [{"type": "function", "function": {"name": "run_cobol", "description": "Compile and run a COBOL file",
    "parameters": {"type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]}}}]
messages = [{"role": "user", "content": "Run arithmetic.cob and explain the result."}]
for _ in range(5):
    msg = client.chat.completions.create(model="llama3.1", messages=messages, tools=tools).choices[0].message
    messages.append(msg)
    if not msg.tool_calls:
        print(msg.content); break
    for c in msg.tool_calls:
        out = run_cobol(**json.loads(c.function.arguments))
        messages.append({"role": "tool", "tool_call_id": c.id, "content": out})

Only let an agent run code inside a sandbox or container you control.

Run it locallyInstall Ollama, run ollama pull llama3.1, and keep it running. The code talks to its OpenAI-compatible API at http://localhost:11434/v1, so the same program also works with vLLM, llama.cpp server or a cloud API by changing the URL, model name and adding an API key.
Part IV · Your path

COBOL learning roadmap

Tick items off as you go. Your progress is saved in this browser.

Beginner

Intermediate

Advanced

Part IV · Your path

Projects to build

PayrollCalculate pay and tax from an employee file.
Bank ledgerProcess deposits and withdrawals with exact decimals.
Modernisation demoUse an LLM to document and translate a COBOL program.
Reference

COBOL cheat sheet

TaskSyntax
Field01 WS-X PIC 9(4) VALUE 0.
Text field01 WS-N PIC X(20).
AssignMOVE 5 TO WS-X
FormulaCOMPUTE WS-X = A * B + 1
LoopPERFORM VARYING I FROM 1 BY 1 UNTIL I > 9
PrintDISPLAY "Total " WS-X
Reference

Common mistakes

  • A missing period can change which statements belong to an IF.
  • Fixed-format code must respect columns (code in 8–72).
  • Numbers that do not fit a PIC are silently truncated unless you check ON SIZE ERROR.
Reference

Where to go next

On TensorCore.si: Java volume, SQL volume.

Keyboard: [ previous language · ] next language · / search the library