Learn COBOL by Examples
COBOL 2002COBOL (Common Business-Oriented Language) is a compiled English-like computer programming language designed for business use. It is imperative, procedural and, since 2002, object-oriented. COBOL is primarily used in business, finance, and administrative systems for companies and governments.
This page provides comprehensive code samples to help learners understand COBOL from basics to advanced concepts. Each example includes complete, runnable code with line numbers, detailed explanations, and line-by-line breakdowns.
Hello World
Writing your first COBOL program to display text output on the console, understanding the mandatory IDENTIFICATION DIVISION with PROGRAM-ID paragraph, implementing executable logic in the PROCEDURE DIVISION with the DISPLAY statement for output, and terminating program execution properly with STOP RUN to return control to the operating system.
Program Structure
Understanding the hierarchical structure of a COBOL program with its four mandatory divisions in fixed order, learning the purpose of IDENTIFICATION for program metadata, ENVIRONMENT for hardware configuration, DATA for variable definitions, and PROCEDURE for executable logic, and implementing proper division organization following COBOL standards.
Divisions
Exploring the detailed purpose and organization of each COBOL division including sections within divisions, understanding CONFIGURATION SECTION and INPUT-OUTPUT SECTION in the ENVIRONMENT DIVISION, working with WORKING-STORAGE SECTION and FILE SECTION in the DATA DIVISION, and learning how data must be defined before procedural code execution.
Sections
Organizing procedural code using sections within the PROCEDURE DIVISION as logical groupings of paragraphs, implementing the PERFORM statement to transfer control between sections and return after completion, structuring programs into modular units like initialization, processing, and cleanup, and preventing fall-through execution with proper control flow management using STOP RUN.
Paragraphs
Understanding paragraphs as the smallest named units of code in the PROCEDURE DIVISION consisting of user-defined names and executable sentences, implementing structured programming with PERFORM statements to execute paragraphs and return control, avoiding unstructured GO TO statements that create spaghetti code, and managing sequential paragraph execution with proper termination to prevent fall-through behavior.
Data Types
Understanding COBOL data type definition using Picture (PIC) clauses instead of traditional type keywords, implementing numeric fields with 9 for digits, alphabetic fields with A for letters, and alphanumeric fields with X for any character, defining fixed-width variables with precise memory control, and using parenthetical notation for field length specification.
PIC Clauses
Exploring advanced Picture clause features for signed numbers using S prefix, implementing implied decimal points with V for fixed-point arithmetic without storage overhead, creating display-formatted output with editing characters like dollar signs and commas, and understanding the difference between computational and display picture formats for numeric data processing.
Level Numbers
Understanding COBOL level numbers for defining data hierarchy from 01 for record-level structures to 49 for nested field definitions, implementing group items without PIC clauses that contain elementary items with PIC clauses, using level 77 for independent standalone variables outside any record structure, and working with level 88 condition names for boolean logic and readable conditional statements.
Variables
Declaring, initializing, and modifying variables in the WORKING-STORAGE SECTION with level numbers, PIC clauses for data type and size, and VALUE clauses for initialization, understanding COBOL naming conventions with hyphens and descriptive identifiers, manipulating data using MOVE for assignment and arithmetic verbs like ADD, and working with automatic type conversion and padding for fixed-width fields.
Literals
Understanding numeric literals as constant number values and non-numeric string literals enclosed in quotes written directly in code, working with figurative constants like ZERO, SPACES, HIGH-VALUE, and LOW-VALUE as special reserved words representing specific values, improving code readability by using meaningful constant names instead of hardcoded values, and leveraging figurative constants that automatically expand to fill target field sizes.
Arithmetic
Performing arithmetic operations using English-like verbs ADD, SUBTRACT, MULTIPLY, and DIVIDE with the GIVING clause for result storage, implementing complex calculations with the COMPUTE statement using standard mathematical operators, handling rounding explicitly with ROUNDED clause, detecting numeric overflows with ON SIZE ERROR exception handling, and preserving data integrity in financial calculations.
Conditions
Controlling program flow with conditional logic using IF-ELSE-END-IF structure for decision-making, implementing level 88 condition names as boolean flags associated with variables for readable code, understanding comparison operators and verbose syntax alternatives, preventing scope termination errors with proper END-IF usage instead of periods, and creating self-documenting code with meaningful condition names.
EVALUATE
Implementing multi-way branching with the EVALUATE statement asmore powerful alternative to nested IF-ELSE chains, matching single or multiple variables against patterns with WHEN clauses, using EVALUATE TRUE pattern for boolean condition evaluation, handling range checking and complex combinations, and implementing default catch-all logic with WHEN OTHER clause.
PERFORM Loops
Understanding iteration with the versatile PERFORM statement handling all loop types in COBOL, implementing simple fixed repetition with PERFORM TIMES, creating counter-based loops with PERFORM VARYING for initialization increment and termination, using PERFORM UNTIL for conditional iteration like while loops, and utilizing inline perform blocks with END-PERFORM for localized logic.
Tables
Defining fixed-size arrays called tables using the OCCURS clause with 1-based indexing, implementing variable-length tables with OCCURS DEPENDING ON clause, accessing table elements with parentheses notation, and creating multi-dimensional tables for matrices and complex data structures.
Table Search
Searching tables with SEARCH for linear sequential search and SEARCH ALL for binary search, using INDEXED BY clause for table index variables, initializing indexes with SET statement before searching, and implementing efficient lookups with sorted tables.
Sequential Files
Processing sequential files with OPEN INPUT/OUTPUT modes, reading records with READ AT END for end-of-file detection, mapping files in ENVIRONMENT DIVISION with SELECT ASSIGN, defining record layouts in FILE SECTION with FD, and using LINE SEQUENTIAL organization for text files.
Indexed Files
Working with indexed files for random access by primary key, implementing ORGANIZATION IS INDEXED with RECORD KEY, using ACCESS MODE RANDOM or DYNAMIC, handling INVALID KEY errors, and understanding VSAM KSDS datasets on mainframes.
Relative Files
Understanding relative file organization for record access by position number, using RELATIVE KEY with Working-Storage variables, implementing array-like disk storage, and managing sparse data efficiently.
File Status
Implementing robust error handling with FILE STATUS codes for I/O operations, checking two-digit status values after file commands, understanding common codes like 00 for success and 10 for EOF, and gracefully handling errors.
Copybooks
Reusing code across programs with COPY statement, including external copybook files during compilation, maintaining consistent data structures, and managing shared record layouts centrally.
Subprograms
Structuring applications with external subprograms using CALL statement, passing data by reference with USING clause, implementing modular development with separate compilation, and managing program control flow with EXIT PROGRAM.
Parameters
Receiving parameters in subprograms using LINKAGE SECTION for shared memory, matching PROCEDURE DIVISION USING signature with caller, preventing memory corruption with correct type matching, and using EXIT PROGRAM to return control.
Intrinsic Functions
Using built-in intrinsic functions from COBOL-85 and later standards, implementing string manipulation with UPPER-CASE and LOWER-CASE, performing mathematical calculations with SQRT MAX MIN, and simplifying code without custom subroutines.
Dates and Times
Retrieving current system date and time with CURRENT-DATE intrinsic function, formatting dates using structured group items with YYYY MM DD fields, displaying time components for hours minutes seconds, and handling timezone offsets.
String Handling
Manipulating strings with STRING for concatenation, UNSTRING for splitting text by delimiters, INSPECT for counting and replacing characters, handling fixed-width fields with DELIMITED BY clauses, and formatting data for reports.
Editing Masks
Formatting numeric output with PIC editing characters for presentation, using Z for zero suppression to replace leading zeros with spaces, implementing check protection with asterisk fill, displaying signs with plus and minus, and separating data storage from display formatting.
Environment Variables
Reading operating system environment variables with ACCEPT FROM ENVIRONMENT, configuring programs dynamically based on runtime context, handling missing variables with space checks, and integrating with modern deployment scenarios for configuration.
SQL (Embedded)
Embedding SQL statements in COBOL with EXEC SQL blocks, accessing relational databases like DB2, using host variables with colon prefix for data binding, checking SQLCODE for error handling, and integrating database queries into business logic.
VSAM Basics
Accessing VSAM (Virtual Storage Access Method) files on IBM mainframes, using ORGANIZATION IS INDEXED with dynamic access mode, implementing robust FILE STATUS error handling for production code, and working with Key Sequenced Data Sets for high-performance storage.
Sort
Sorting files with built-in SORT verb for batch processing, defining Sort Description (SD) for temporary workspace, specifying ascending or descending sort keys, using USING and GIVING clauses for automatic file handling, and implementing INPUT/OUTPUT procedures for filtered sorting.
Merge
Merging pre-sorted files efficiently with MERGE statement, combining multiple input streams into single sorted output, using zipper algorithm for optimal performance, and processing batch transactions from distributed sources.
Report Writer
Automating report generation with Report Writer module, defining page layouts in REPORT SECTION with RD (Report Definition), handling automatic page breaks and line counting, using INITIATE GENERATE and TERMINATE for declarative reporting, and implementing control footings for subtotals.
Screen Section
Pointer Data
Managing dynamic memory with POINTER data type for heap allocation, using ALLOCATE statement to request memory, implementing BASED clause for template variables without fixed storage, mapping memory addresses with SET ADDRESS OF, and preventing leaks with explicit FREE statement.
Object-Oriented
Implementing object-oriented programming in COBOL 2002+ standard, defining classes with CLASS-ID and INHERITS for inheritance, encapsulating instance data in OBJECT paragraph, creating public methods with METHOD-ID and RETURNING values, and integrating with Java and .NET runtime environments.
XML Generation
Converting COBOL data structures to XML with XML GENERATE statement, serializing group items automatically for web services, mapping field names to XML element tags, controlling output format with COUNT clause and WITH ENCODING, and handling buffer overflow with ON EXCEPTION error management.
XML Parsing
Parsing XML documents with event-based XML PARSE statement, implementing SAX-style processing with PROCESSING PROCEDURE callbacks, handling XML-EVENT and XML-TEXT registers, processing large files efficiently without loading entire DOM trees, and managing state manually for nested elements.
JSON Generation
Generating JSON from COBOL data using JSON GENERATE statement, serializing group items into JSON objects automatically, ensuring proper type conversion for numbers and strings, supporting REST API integration and microservices, and using NAME OF phrase for custom field mapping.
JSON Parsing
Parsing JSON text into COBOL variables with JSON PARSE INTO statement, mapping JSON keys to COBOL field names by matching identifiers, leveraging automatic type conversion from JSON types to COBOL data types, consuming modern web API responses easily, and using NAME OF phrase for field name translation.

