Learn COBOL

Part 0—COBOL Examples

Example 1: Hello World

This is a simple program that displays "Hello, World!" on the screen.

IDENTIFICATION DIVISION.
PROGRAM-ID. HelloWorld.

PROCEDURE DIVISION.
    DISPLAY 'Hello, World!'.
    STOP RUN.

Example 2: Accepting User Input

<

COBOL allows interaction with the user through the ACCEPT statement, which captures input from the user at runtime. Data can be accepted from the console or other sources, such as files or system variables. When running COBOL programs in online compilers, user input is often provided via STDIN (Standard Input), meaning you can preload inputs instead of typing them interactively.

In environments where interactive input isn't supported (like some online COBOL compilers), the input is taken from STDIN before running the program. You can provide multiple inputs at once, separated by new lines, simulating what would normally be entered interactively.

For example, if you want to accept multiple inputs, such as a user's name and age, you can write a program like this:

IDENTIFICATION DIVISION.
    PROGRAM-ID. UserInputProgram.
    
    DATA DIVISION.
    WORKING-STORAGE SECTION.
    01 CustomerName PIC X(20).
    01 CustomerAge PIC 9(2).
    
    PROCEDURE DIVISION.
        DISPLAY 'Enter your name: '.
        ACCEPT CustomerName.
        
        DISPLAY 'Enter your age: '.
        ACCEPT CustomerAge.
    
        DISPLAY 'Hello, ' CustomerName ', you are ' CustomerAge ' years old.'.
    
        STOP RUN.

Using STDIN: In online COBOL compilers, such as JDoodle, you can enter inputs like this in the "Input" section (STDIN):


  John Doe
  30
  

The program will then take "John Doe" as the value for CustomerName and "30" as the value for CustomerAge, and output:


  Enter your name: 
  Enter your age: 
  Hello, John Doe, you are 30 years old.
  

This method of using STDIN is crucial for compilers that don't support live user interaction.

Example 3: Simple Arithmetic

This program performs a simple addition operation and displays the result.

IDENTIFICATION DIVISION.
PROGRAM-ID. AddNumbers.

DATA DIVISION.
WORKING-STORAGE SECTION.
01 Number1 PIC 9(2).
01 Number2 PIC 9(2).
01 Sum PIC 9(3).

PROCEDURE DIVISION.
    MOVE 10 TO Number1.
    MOVE 20 TO Number2.
    ADD Number1 TO Number2 GIVING Sum.
    DISPLAY 'The sum of ' Number1 ' and ' Number2 ' is ' Sum.
    STOP RUN.

Example 4: Conditional Logic

This program checks if a number is greater than 50 and displays a message accordingly.

IDENTIFICATION DIVISION.
PROGRAM-ID. CheckNumber.

DATA DIVISION.
WORKING-STORAGE SECTION.
01 Number PIC 9(3).

PROCEDURE DIVISION.
  DISPLAY 'Enter a number: '.
  ACCEPT Number.

  IF Number > 50 THEN
      DISPLAY 'The number is greater than 50.'
  ELSE
      DISPLAY 'The number is 50 or less.'
  END-IF.

  STOP RUN.

Example 5: Loops Using PERFORM

This program loops from 1 to 5 and displays the current loop counter value.

IDENTIFICATION DIVISION.
PROGRAM-ID. LoopExample.

DATA DIVISION.
WORKING-STORAGE SECTION.
01 Counter PIC 9(1).

PROCEDURE DIVISION.
  MOVE 1 TO Counter.

  PERFORM UNTIL Counter > 5
      DISPLAY 'Counter: ' Counter
      ADD 1 TO Counter
  END-PERFORM.

  STOP RUN.

Example 6: Working with Arrays

This program defines an array of 5 student scores and displays them.

IDENTIFICATION DIVISION.
  PROGRAM-ID. ArrayExample.
  
  DATA DIVISION.
  WORKING-STORAGE SECTION.
  01 StudentScores.
      05 Score PIC 9(3) OCCURS 5 TIMES.
  01 Counter PIC 9(1).
  
  PROCEDURE DIVISION.
      MOVE 90 TO Score(1).
      MOVE 85 TO Score(2).
      MOVE 88 TO Score(3).
      MOVE 92 TO Score(4).
      MOVE 75 TO Score(5).
  
      PERFORM VARYING Counter FROM 1 BY 1 UNTIL Counter > 5
          DISPLAY 'Student ' Counter ' score: ' Score(Counter)
      END-PERFORM.
  
      STOP RUN.

Example 7: File Handling

This program reads and writes to a file.

IDENTIFICATION DIVISION.
PROGRAM-ID. FileIOExample.

ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
  SELECT StudentFile ASSIGN TO 'students.txt'
  ORGANIZATION IS LINE SEQUENTIAL.

DATA DIVISION.
FILE SECTION.
FD StudentFile.
01 StudentRecord PIC X(50).

WORKING-STORAGE SECTION.
01 WS-Student PIC X(50).

PROCEDURE DIVISION.
  OPEN OUTPUT StudentFile.
  MOVE 'John Doe' TO WS-Student.
  WRITE StudentRecord FROM WS-Student.
  CLOSE StudentFile.

  OPEN INPUT StudentFile.
  READ StudentFile INTO WS-Student.
  DISPLAY 'Read from file: ' WS-Student.
  CLOSE StudentFile.

  STOP RUN.

Example 8: Error Handling

This program demonstrates simple error handling by checking for division by zero.

IDENTIFICATION DIVISION.
PROGRAM-ID. ErrorHandlingExample.

DATA DIVISION.
WORKING-STORAGE SECTION.
01 Number1 PIC 9(2).
01 Number2 PIC 9(2).
01 Result PIC 9(3).

PROCEDURE DIVISION.
  MOVE 10 TO Number1.
  MOVE 0 TO Number2.

  IF Number2 = 0 THEN
      DISPLAY 'Error: Division by zero.'
  ELSE
      DIVIDE Number1 BY Number2 GIVING Result
      DISPLAY 'Result: ' Result
  END-IF.

  STOP RUN.

Example 9: Simple Payment Processing

This program simulates a simple payment processing system. It accepts a payment and checks if the user has enough balance. If the balance is sufficient, it deducts the payment amount; otherwise, it shows an error.

IDENTIFICATION DIVISION.
  PROGRAM-ID. SimplePaymentProcessing.
  
  DATA DIVISION.
  WORKING-STORAGE SECTION.
  01 CustomerBalance PIC 9(5)V99 VALUE 1000.50.
  01 PaymentAmount PIC 9(5)V99.
  01 RemainingBalance PIC 9(5)V99.
  
  PROCEDURE DIVISION.
    DISPLAY 'Customer Balance: ' CustomerBalance.
    
    DISPLAY 'Enter Payment Amount: '.
    ACCEPT PaymentAmount.
    
    IF PaymentAmount > CustomerBalance THEN
        DISPLAY 'Error: Payment exceeds available balance.'
    ELSE
        SUBTRACT PaymentAmount FROM CustomerBalance GIVING RemainingBalance
        DISPLAY 'Payment processed. Remaining Balance: ' RemainingBalance
    END-IF.
  
    STOP RUN.

Part I—COBOL Program Basics

Introduction to COBOL

COBOL (Common Business Oriented Language) is a high-level programming language designed for business applications. It was first introduced in 1959 and has been widely used in industries such as finance, government, and business data processing.

COBOL emphasizes structured programming, readability, and maintainability, making it suitable for large-scale and mission-critical applications. Despite its age, COBOL continues to be used in many legacy systems and is still taught in some computer science programs.

COBOL Syntax and Structure

A COBOL program is divided into four main divisions:

  1. Identification Division: Provides information about the program, such as its name and author.
  2. Environment Division: Describes the hardware and software environment in which the program will run.
  3. Data Division: Defines the data structures and variables used in the program.
  4. Procedure Division: Contains the executable statements that perform the program's logic.
IDENTIFICATION DIVISION.
PROGRAM-ID. HelloWorld.

PROCEDURE DIVISION.
    DISPLAY 'Hello, World!'.
    STOP RUN.

Data Types and Variables

COBOL supports various data types, including numeric and alphanumeric data. Variables are declared in the Data Division using level numbers and data description entries.

DATA DIVISION.
WORKING-STORAGE SECTION.
01 StudentName PIC X(20).
01 StudentAge PIC 99.

COBOL Purpose and History

COBOL (Common Business Oriented Language) was developed in 1959 to meet the needs of business data processing. Its creation was driven by the need for a high-level programming language to handle data-centric applications, particularly in business and government.

COBOL has been used for decades in mission-critical systems, such as banking, insurance, and government services, and is still widely used in legacy systems today.

COBOL: The Language of Business

COBOL was designed for business data processing, making it ideal for applications that handle large volumes of data. Its readability, strict format, and structure made it a preferred choice for large corporations and government institutions.

COBOL's syntax closely resembles the English language, making it more accessible for business analysts and non-programmers to understand.

Grace Hopper and the Origin of COBOL

Grace Hopper, a pioneering computer scientist, played a significant role in the development of COBOL. She contributed to the creation of early compilers and advocated for machine-independent programming languages, which led to COBOL's design.

Hopper's work laid the foundation for the development of COBOL, and she is often credited as one of the key figures in the history of the language.

COBOL Program Layout

A COBOL program is structured into four main divisions, each serving a different purpose. These divisions are:

  • Identification Division: Provides metadata about the program, such as its name, author, and version.
  • Environment Division: Describes the environment in which the program is running, such as hardware and software configurations.
  • Data Division: Defines all variables, data structures, and constants used in the program.
  • Procedure Division: Contains the code logic and instructions to execute the program.
IDENTIFICATION DIVISION.
PROGRAM-ID. HelloWorld.

ENVIRONMENT DIVISION.

DATA DIVISION.

PROCEDURE DIVISION.
    DISPLAY 'Hello, World!'.
    STOP RUN.

COBOL Data Types and The Picture Clause

COBOL supports various data types, primarily focused on business data such as numbers, strings, and edited fields. Variables are declared in the Data Division using level numbers and the PICTURE (PIC) clause, which defines the structure of the variable.

  • Numeric Fields: Used for storing numbers, either whole or with decimal points.
  • Alphanumeric Fields: Used for storing text or a mix of numbers and characters.
  • Edited Fields: Variables that format output for display purposes (e.g., adding commas to a number).
01 Price       PIC 9(5)V99.  *> Numeric field with 5 digits and 2 decimal places
01 CustomerName PIC X(20).    *> Alphanumeric field with a maximum length of 20 characters

Accepting User Input in COBOL

COBOL allows interaction with the user through the ACCEPT statement, which captures input from the user at runtime. Data can be accepted from the console or other sources, such as files or system variables.

PROCEDURE DIVISION.
    DISPLAY 'Enter your name: '.
    ACCEPT CustomerName.
    DISPLAY 'Hello, ' CustomerName.

Manipulating Data in COBOL

In COBOL, you can manipulate data using a variety of statements such as MOVE, ADD, SUBTRACT, MULTIPLY, and DIVIDE.

  • MOVE: Transfers data from one variable to another.
  • ADD, SUBTRACT, MULTIPLY, DIVIDE: Perform arithmetic operations.
  • COMPUTE: A general-purpose arithmetic operation, often used for complex calculations.
PROCEDURE DIVISION.
    MOVE 10 TO Number1.
    ADD 5 TO Number1 GIVING Total.
    DISPLAY 'Total: ' Total.

Conditional Statements in COBOL

COBOL uses the IF statement to perform conditional logic. It supports nested conditions and the use of 88 levels for specific value checks.

IF Amount > 1000
    DISPLAY 'High Amount'
ELSE
    DISPLAY 'Normal Amount'.

Loops and Perform Statements

COBOL uses the PERFORM statement to create loops. These loops can be used to repeat a section of code a specific number of times or until a condition is met.

PERFORM UNTIL Counter > 10
    ADD 1 TO Counter
    DISPLAY 'Counter: ' Counter
END-PERFORM.

Tables in COBOL

COBOL supports single-dimensional and multi-dimensional arrays, which are referred to as tables in COBOL. They are defined using the OCCURS clause.

01 StudentScores.
    05 Score PIC 9(3) OCCURS 10 TIMES.

Part II—File Handling

Sequential Files

In COBOL, sequential files are used to store data in a sequence, with each record following the previous one. Sequential files are the most common file format for reading and writing data in a linear order.

The key steps for working with sequential files are:

  • SELECT Statement: Connects your program to the external file.
  • OPEN Statement: Prepares the file for reading, writing, or both.
  • READ Statement: Reads data from the file into a COBOL variable.
  • WRITE Statement: Writes data from COBOL variables into the file.
  • CLOSE Statement: Closes the file once processing is complete.
SELECT CustomerFile ASSIGN TO 'customer.dat'.
FD CustomerFile.
01 CustomerRecord.
   05 CustomerID      PIC 9(5).
   05 CustomerName    PIC X(20).

PROCEDURE DIVISION.
   OPEN INPUT CustomerFile.
   READ CustomerFile INTO CustomerRecord.
   DISPLAY 'Customer: ' CustomerName.
   CLOSE CustomerFile.

Indexed Files

Indexed files in COBOL allow random access to records by associating each record with a key. These files are ideal for databases or applications where you need quick access to specific records.

Key steps for using indexed files:

  • Defining the file: Use the SELECT statement to specify the key field.
  • Reading records: You can read records in sequence or by searching for a specific key.
  • Creating or updating records: Write new records to the file or update existing ones using the key.
SELECT IndexedCustomerFile ASSIGN TO 'customer.dat'
    ORGANIZATION IS INDEXED
    ACCESS MODE IS DYNAMIC
    RECORD KEY IS CustomerID.
FD IndexedCustomerFile.
01 CustomerRecord.
   05 CustomerID      PIC 9(5).
   05 CustomerName    PIC X(20).

PROCEDURE DIVISION.
   OPEN I-O IndexedCustomerFile.
   READ IndexedCustomerFile KEY IS CustomerID.
   DISPLAY 'Customer: ' CustomerName.
   CLOSE IndexedCustomerFile.

Reading Indexed File Records

Reading records from an indexed file can be done in three different ways:

  • Sequential Access: Reads records in the order they were written.
  • Random Access: Reads a specific record by searching for its key.
  • Dynamic Access: Combines sequential and random access, allowing you to alternate between both methods as needed.
SELECT IndexedFile ASSIGN TO 'datafile.dat'
    ORGANIZATION IS INDEXED
    ACCESS MODE IS DYNAMIC
    RECORD KEY IS CustomerID.

PROCEDURE DIVISION.
   OPEN I-O IndexedFile.
   READ IndexedFile KEY IS CustomerID.
   DISPLAY 'Customer ID: ' CustomerID ' Name: ' CustomerName.
   CLOSE IndexedFile.

Updating Indexed File Records

Updating indexed files in COBOL involves modifying existing records, adding new records, or deleting records. The REWRITE statement allows you to update a record after reading it, while the DELETE statement removes a record.

SELECT IndexedFile ASSIGN TO 'datafile.dat'
    ORGANIZATION IS INDEXED
    ACCESS MODE IS DYNAMIC
    RECORD KEY IS CustomerID.

PROCEDURE DIVISION.
   OPEN I-O IndexedFile.
   READ IndexedFile KEY IS CustomerID.
   MOVE 'New Name' TO CustomerName.
   REWRITE CustomerRecord.
   CLOSE IndexedFile.

Sorting Files

Sorting in COBOL involves rearranging the records in a file according to a specific key, such as customer ID or name. The SORT statement allows you to define the key and the input/output procedures for sorting data.

SORT SortedCustomerFile
    ON ASCENDING KEY CustomerID
    USING CustomerFile
    GIVING SortedOutputFile.

PROCEDURE DIVISION.
   OPEN INPUT CustomerFile.
   SORT SortedCustomerFile
       ON ASCENDING KEY CustomerID
       USING CustomerFile
       GIVING SortedOutputFile.
   CLOSE CustomerFile.

Part III—Business Processing

Master File Updating

Master file updating is a critical business process in COBOL applications. It involves processing transaction records to update a master file, such as updating customer records with new purchases or payments.

PROCEDURE DIVISION.
   OPEN I-O MasterFile.
   OPEN INPUT TransactionFile.

   PERFORM UNTIL END-OF-TRANSACTION
       READ TransactionFile INTO TransactionRecord
       AT END MOVE 'YES' TO END-OF-TRANSACTION
       NOT AT END
           READ MasterFile KEY IS CustomerID
           REWRITE MasterRecord.
   CLOSE MasterFile.
   CLOSE TransactionFile.

Creating Reports in COBOL

COBOL excels in generating detailed reports for business applications. The WRITE statement is used to print records formatted for reports, and you can control page breaks, headings, and the structure of the report.

PROCEDURE DIVISION.
   OPEN OUTPUT ReportFile.
   WRITE ReportRecord FROM Header.
   PERFORM UNTIL END-OF-REPORT
       READ DataFile INTO DataRecord
       AT END MOVE 'YES' TO END-OF-REPORT
       NOT AT END
           WRITE ReportRecord FROM DataRecord.
   CLOSE ReportFile.

Advanced Reporting

Advanced reporting in COBOL includes handling control breaks, where the report is grouped and subtotaled based on key values. Control breaks allow you to summarize data within groups (e.g., totals by department or region).

Other advanced techniques include managing multiple control breaks, subtotals, and calculating grand totals.

PROCEDURE DIVISION.
   OPEN INPUT SalesFile.
   MOVE 0 TO TotalAmount.
   PERFORM UNTIL EOF
       READ SalesFile INTO SalesRecord
       AT END SET EOF TO TRUE
       NOT AT END
           IF SalesRegion NOT = PrevSalesRegion
               DISPLAY 'Region Subtotal: ' Subtotal
               MOVE 0 TO Subtotal
           END-IF
           ADD SalesAmount TO Subtotal
           ADD SalesAmount TO TotalAmount
           MOVE SalesRegion TO PrevSalesRegion.
   CLOSE SalesFile.
   DISPLAY 'Grand Total: ' TotalAmount.

Part IV—Miscellaneous Functions

Date Manipulation

COBOL includes intrinsic functions for working with dates, such as determining the current system date or calculating the number of days between dates. These functions are important for applications that process dates for billing, payroll, and reporting.

  • CURRENT-DATE: Retrieves the current date and time.
  • INTEGER-OF-DATE: Converts a date to an integer for calculations.
  • DATE-OF-INTEGER: Converts an integer back to a date.
PROCEDURE DIVISION.
   MOVE FUNCTION CURRENT-DATE TO CurrentDate.
   DISPLAY 'Today''s Date: ' CurrentDate.

   MOVE FUNCTION INTEGER-OF-DATE (20230901) TO DateInt.
   DISPLAY 'Days since 1/1/1601: ' DateInt.

   MOVE FUNCTION DATE-OF-INTEGER (DateInt) TO ActualDate.
   DISPLAY 'Converted Date: ' ActualDate.

Other Intrinsic Functions

COBOL provides a range of intrinsic functions for performing mathematical, statistical, financial, and string manipulations. These functions simplify calculations and string handling within your programs.

  • NUMVAL: Converts alphanumeric data to numeric.
  • MAX: Returns the maximum value from a list of numbers.
  • SUBSTR: Extracts a substring from a string.
  • REVERSE: Reverses the order of characters in a string.
PROCEDURE DIVISION.
   MOVE '123' TO AlphanumericValue.
   COMPUTE NumericValue = FUNCTION NUMVAL (AlphanumericValue).
   DISPLAY 'Numeric Value: ' NumericValue.

   COMPUTE MaximumValue = FUNCTION MAX (5, 10, 15).
   DISPLAY 'Maximum Value: ' MaximumValue.

   MOVE FUNCTION REVERSE ('COBOL') TO ReversedString.
   DISPLAY 'Reversed String: ' ReversedString.

Part V—Advanced Topics

The Call Interface

COBOL supports calling external programs or subprograms using the CALL statement. This allows you to build modular programs where tasks are separated into individual subprograms. Data can be passed between programs via the LINKAGE SECTION.

The CALL BY REFERENCE and CALL BY CONTENT methods determine how data is passed between the calling and called programs.

PROCEDURE DIVISION.
   CALL 'SubProgram' USING BY REFERENCE DataItem1
                            BY CONTENT DataItem2.
   DISPLAY 'Returned from SubProgram'.

The Future of COBOL

Despite its age, COBOL continues to play a crucial role in enterprise systems, especially in sectors like banking, insurance, and government. Efforts to modernize COBOL applications, integrate them with newer technologies, and train a new generation of developers ensure that COBOL will remain relevant for years to come.

Technologies like cloud computing, API integration, and modernization tools are enabling COBOL applications to work seamlessly with modern architectures, extending their lifespan in the business world.