This is a simple program that displays "Hello, World!" on the screen.
IDENTIFICATION DIVISION.
PROGRAM-ID. HelloWorld.
PROCEDURE DIVISION.
DISPLAY 'Hello, World!'.
STOP RUN.
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.
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.
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.
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.
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.
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.
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.
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.
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.
A COBOL program is divided into four main divisions:
IDENTIFICATION DIVISION.
PROGRAM-ID. HelloWorld.
PROCEDURE DIVISION.
DISPLAY 'Hello, World!'.
STOP RUN.
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 (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 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, 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.
A COBOL program is structured into four main divisions, each serving a different purpose. These divisions are:
IDENTIFICATION DIVISION.
PROGRAM-ID. HelloWorld.
ENVIRONMENT DIVISION.
DATA DIVISION.
PROCEDURE DIVISION.
DISPLAY 'Hello, World!'.
STOP RUN.
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.
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
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.
In COBOL, you can manipulate data using a variety of statements such as MOVE, ADD, SUBTRACT, MULTIPLY, and DIVIDE.
PROCEDURE DIVISION.
MOVE 10 TO Number1.
ADD 5 TO Number1 GIVING Total.
DISPLAY 'Total: ' Total.
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'.
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.
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.
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 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 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:
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 records from an indexed file can be done in three different ways:
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 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 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.
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.
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 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.
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.
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.
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.
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.
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'.
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.