Despite the rise of modern programming languages, COBOL (Common Business Oriented Language) remains mission-critical in industries like banking, insurance, and government systems, powering legacy mainframe applications with high reliability. Recruiters must identify professionals skilled in COBOL programming, data structures, and mainframe integrations to maintain, modernize, or migrate these applications efficiently.
This resource, "100+ COBOL Interview Questions and Answers," is tailored for recruiters to simplify the evaluation process. It covers topics from COBOL fundamentals to advanced data handling and real-world mainframe workflows, including JCL, CICS, and DB2 integrations.
Whether hiring for COBOL Developers, Mainframe Programmers, or Application Maintenance Engineers, this guide enables you to assess a candidate’s:
For a streamlined assessment process, consider platforms like WeCP, which allow you to:
✅ Create customized COBOL assessments tailored to your mainframe systems and business workflows.
✅ Include hands-on coding tasks, such as writing COBOL programs for file processing, DB2 queries, or JCL job setups.
✅ Proctor tests remotely with AI-based anti-cheating protections.
✅ Leverage automated grading to evaluate code correctness, data logic, and adherence to COBOL and mainframe best practices.
Save time, maintain mission-critical systems effectively, and confidently hire COBOL professionals who can manage, optimize, and modernize mainframe applications from day one.
COBOL (Common Business-Oriented Language) is one of the oldest high-level programming languages, created in the late 1950s and early 1960s. The language was developed as a result of the need for a standard programming language for business applications, especially for transaction processing and data processing systems. At the time, various government agencies, defense departments, and commercial organizations were using different programming languages, leading to a lack of interoperability between systems.
The U.S. Department of Defense played a key role in sponsoring the creation of COBOL to meet the growing need for business applications, especially for tasks like payroll, inventory management, and financial systems. COBOL was designed to be a readable, English-like language that could be used across different types of computers, making it easier for programmers to write and maintain software for large-scale business systems.
COBOL was created with the goal of simplifying the development of business applications and making them easier to maintain and understand. Its design emphasized structured programming, portability, and efficiency, making it ideal for processing large volumes of data, typically in batch and transaction-oriented systems.
COBOL has several key features that have contributed to its long-lasting relevance in business environments:
A COBOL program is divided into four main divisions, each serving a distinct purpose:
Each of these divisions has a specific role and provides structure to the COBOL program, which helps in organizing code efficiently and maintaining it over time.
The structure of a COBOL program follows a specific order and organization, which ensures clarity, modularity, and maintainability. A typical COBOL program includes the following sections:
Identification Division: This is the first division of a COBOL program and is used for program identification purposes. It is typically where metadata such as the program name, author, and date are specified.
IDENTIFICATION DIVISION.
PROGRAM-ID. MyFirstProgram.
AUTHOR. John Doe.
Environment Division: This division provides details about the external environment in which the program runs, including file handling and I/O device specifications. It has a Configuration Section and an Input-Output Section.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT customerFile ASSIGN TO 'CUSTFILE'.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 customer-name PIC X(50).
01 customer-age PIC 99.
Procedure Division: This is where the logic and processing instructions reside. It contains the sequence of operations to be performed, such as reading data, processing data, and displaying results.
PROCEDURE DIVISION.
DISPLAY "Enter customer name:".
ACCEPT customer-name.
DISPLAY "Enter customer age:".
ACCEPT customer-age.
These divisions ensure that the COBOL program is well-organized, modular, and maintainable.
The IDENTIFICATION DIVISION is the first division in a COBOL program and serves as a container for metadata or descriptive information about the program. Although it doesn't directly affect the program's execution, it plays a crucial role in documenting and identifying the program. It allows the programmer to define:
This division helps in organizing and identifying the program, particularly when dealing with large, multi-program systems or legacy codebases.
The ENVIRONMENT DIVISION provides information about the system environment in which the COBOL program runs. It defines external attributes, such as hardware, I/O devices, and file handling. The key sections in the ENVIRONMENT DIVISION are:
INPUT-OUTPUT SECTION: The I/O Section defines the files used in the program, including file organization and the mapping of logical file names to physical devices.Example:
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT customerFile ASSIGN TO 'CUSTFILE'.
The ENVIRONMENT DIVISION allows the program to be portable by abstracting hardware-specific information, making the COBOL program adaptable to different systems and devices.
In COBOL, data is defined in the DATA DIVISION, where all the variables, constants, and data structures used in the program are declared. COBOL provides several data types and structure formats to define variables:
Example:
DATA DIVISION.
WORKING-STORAGE SECTION.
01 customer-name PIC X(50).
01 customer-age PIC 99.
This allows COBOL to handle both simple and complex data structures with precision.
The DATA DIVISION is the part of the COBOL program where all data elements, variables, and file structures are declared and defined. It is a critical division for data management and typically contains several sections:
Each section is structured to define specific types of data, and their layout allows for efficient data access, manipulation, and storage in COBOL.
Example:
01 customer-record.
05 customer-id PIC 9(5).
05 customer-name PIC X(20).
Here, customer-record is a group item defined at level 01, and it contains two elementary items at level 05.
COBOL provides a variety of data types for defining variables:
Each data type is designed for specific business needs, making COBOL powerful for handling both simple and complex data structures in large-scale business applications.
In COBOL, a numeric variable is defined using the PIC (Picture) clause, which specifies the data type, size, and structure of the variable. For numeric values, you use the 9 symbol in the PIC clause. The number of 9s determines the size of the variable.
For example, to define a numeric variable for storing a 5-digit number:
01 num-variable PIC 9(5).
Here, PIC 9(5) specifies that the variable num-variable can hold a 5-digit number. The parentheses after the 9 indicate the length of the numeric value that can be stored.
01 signed-num PIC S9(3).
This means the variable signed-num can hold a 3-digit signed number (i.e., values can be positive or negative).
01 decimal-num PIC 9(3)V99.
This means the variable decimal-num can hold a number with up to 3 digits before the decimal point and 2 digits after it.
In COBOL, the difference between a group item and an elementary item lies in their structure and usage in the DATA DIVISION:
Elementary Item: An elementary item is a single, indivisible data item that holds a single value. It can be a numeric, alphabetic, or alphanumeric value. An elementary item is declared with a level number of 01 or higher. Examples include variables like PIC 9(3) for numeric or PIC X(10) for alphanumeric.Example of an elementary item:
01 customer-name PIC X(30).
01 age PIC 99.
Group Item: A group item is a collection of elementary items that are treated as a single entity. It is defined at level 01 or higher and can contain multiple elementary items or other group items. Group items allow for logical grouping of related data. The data is treated as a unit, and it is usually used to model complex structures.Example of a group item:
01 customer-record.
05 customer-name PIC X(30).
05 customer-age PIC 99.
05 customer-address PIC X(50).
In this case, customer-record is a group item that contains multiple elementary items (customer-name, customer-age, customer-address).
The VALUE clause in COBOL is used to assign initial values to variables when they are defined in the DATA DIVISION. The VALUE clause helps initialize a variable with a default value before the program starts execution. This is particularly useful for setting default values for variables or ensuring that a variable has a known state before it is used.
Example:
01 customer-status PIC X(1) VALUE 'A'.
01 total-amount PIC 9(5) VALUE 10000.
In the example above:
If the VALUE clause is not provided, variables in COBOL (especially in WORKING-STORAGE and LINKAGE sections) are usually initialized to spaces (for alphanumeric data) or zeros (for numeric data).
In COBOL, constants are usually defined using the VALUE clause in the DATA DIVISION. Although COBOL does not have a dedicated keyword for constants like some other languages, the VALUE clause is used to specify a fixed value that should not change throughout the program's execution.
Example:
01 MAXIMUM-AGE PIC 99 VALUE 100.
01 MINIMUM-SALARY PIC 9(5) VALUE 30000.
In this case, MAXIMUM-AGE is set to 100, and MINIMUM-SALARY is set to 30000. These values are constant throughout the program, meaning they cannot be changed during the program's execution.
For real constants, you could also use REDEFINES or simply VALUE with a PIC clause that matches the data type.
COBOL supports several types of file organizations, which determine how data is stored and accessed in files. The main types of file organizations in COBOL are:
Sequential Files: Data is stored and accessed in the order in which it is written. It is the most basic file organization type, and it is typically used when the program processes records in sequential order (e.g., reading a list of customer records one by one).Example:
SELECT customerFile ASSIGN TO 'CUSTFILE' ORGANIZATION IS SEQUENTIAL.
Indexed Files: Data is stored in a way that allows for fast, direct access to records based on an index key. Indexed files are useful when you need to perform random access to specific records without processing the entire file.Example:
SELECT employeeFile ASSIGN TO 'EMPFILE' ORGANIZATION IS INDEXED.
Relative Files: Data is stored in records that are accessed based on a relative key. A relative file uses a numeric index to access records, which can be faster than sequential access but less efficient than indexed files for larger datasets.Example:
SELECT studentFile ASSIGN TO 'STUFILE' ORGANIZATION IS RELATIVE.
A flat file is a type of file that contains data in a plain, sequential format without structured relationships between different parts of the data. Typically, a flat file consists of records (rows of data), and each record may contain multiple fields (columns of data).
In COBOL, flat files are handled as sequential files, meaning data is written and read sequentially, one record after another.
To define a flat file in COBOL:
Example of defining and handling a flat file:
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT customerFile ASSIGN TO 'CUSTFILE' ORGANIZATION IS SEQUENTIAL.
DATA DIVISION.
FILE SECTION.
FD customerFile.
01 customer-record.
05 customer-id PIC 9(5).
05 customer-name PIC X(30).
05 customer-age PIC 99.
PROCEDURE DIVISION.
OPEN INPUT customerFile.
READ customerFile INTO customer-record.
DISPLAY customer-id.
CLOSE customerFile.
In this example, the file customerFile is a flat file, and each record is structured with customer-id, customer-name, and customer-age.
The WORKING-STORAGE SECTION is part of the DATA DIVISION and is used to define variables that will be used during the execution of a COBOL program. Variables declared in the WORKING-STORAGE SECTION retain their values throughout the program's life cycle, and they are initialized when the program starts running.
Example:
DATA DIVISION.
WORKING-STORAGE SECTION.
01 customer-id PIC 9(5).
01 customer-name PIC X(30).
01 total-sales PIC 9(6)V99 VALUE 0.
In this example, the WORKING-STORAGE SECTION holds variables like customer-id, customer-name, and total-sales for temporary use during the execution of the program.
The difference between PIC 9(3) and PIC 9(03) lies in the leading zeroes in the output and how the number is displayed:
Example:
01 num1 PIC 9(3).
01 num2 PIC 9(03).
The PIC 9(03) format ensures the variable always occupies 3 spaces, padding with leading zeroes where necessary.
The PROCEDURE DIVISION is where the logic and processing instructions of a COBOL program are written. It is the part of the program where the actual execution of tasks happens. The PROCEDURE DIVISION contains statements to manipulate data, read or write to files, and control the flow of the program.
Examples of activities you might perform in the PROCEDURE DIVISION include:
For example:
PROCEDURE DIVISION.
DISPLAY "Enter Customer Name:".
ACCEPT customer-name.
DISPLAY "Customer Name: ", customer-name.
In this example, the program prompts the user for input, accepts the customer’s name, and then displays it.
The MOVE statement in COBOL is used to assign the value of one data item to another. It is the most common way to transfer data between variables.
The MOVE statement works by copying the value from the source variable (right-hand side) to the destination variable (left-hand side). The destination must be capable of holding the value assigned to it.
Example:
MOVE 100 TO total-sales.
MOVE customer-name TO new-customer-name.
In the first example, the value 100 is assigned to the variable total-sales. In the second example, the contents of customer-name are copied to new-customer-name.
In COBOL, both the MOVE and MOVE CORRESPONDING statements are used to assign values to data items, but they differ in the way they handle the data:
MOVE: The MOVE statement copies the value from a source data item to a single destination data item. The number of digits, length, and data types between the source and destination should match for the MOVE statement to work properly.Example:
MOVE employee-name TO new-employee-name.
MOVE CORRESPONDING: The MOVE CORRESPONDING statement is used when moving values between group items that share the same field names in a hierarchical structure. It matches fields with the same name in two group items and moves the corresponding data from one group to another.
Example:
cobol
Copy code
MOVE CORRESPONDING employee-record TO new-employee-record.
The ACCEPT statement in COBOL is used to get input from the environment or from external sources, such as the user, the system, or the operating system. The most common use of the ACCEPT statement is to get user input from the console or terminal.
The ACCEPT statement allows you to:
Example:
ACCEPT user-input.
This will read the user input from the terminal and store it in the variable user-input.
You can also use ACCEPT to get the system date or time:
ACCEPT system-date FROM DATE.
This will store the current date in the system-date variable.
The DISPLAY statement in COBOL is used to output data to the screen or to other output devices (e.g., printers). It is commonly used for printing messages, debugging information, or displaying the value of variables during the execution of the program.
DISPLAY <expression>.
Example:
DISPLAY "Hello, World!".
DISPLAY customer-name.
In this example:
You can also format the output with additional phrases or formatting, like WITH NO ADVANCING (to avoid moving to a new line after output), or UPON (to specify a particular output device).
To read from a file in COBOL, you use the READ statement. The READ statement is used to read records from files that have been opened for input (using the OPEN statement).
READ <file-name> INTO <data-record> [AT END ...].
Example:
OPEN INPUT customerFile.
READ customerFile INTO customer-record
AT END
DISPLAY "End of file reached."
NOT AT END
DISPLAY "Customer ID: ", customer-id
DISPLAY "Customer Name: ", customer-name.
CLOSE customerFile.
In this example:
The OPEN statement in COBOL is used to open a file for processing (i.e., reading, writing, or updating). The OPEN statement must be called before any READ, WRITE, or REWRITE statements are issued for a file.
OPEN [MODE] <file-name>.
Example:
OPEN INPUT customerFile.
In this example, the file customerFile is opened in INPUT mode, allowing the program to read data from the file.
In COBOL, the file access mode determines how a file is opened and interacted with during program execution. The types of file access modes include:
INPUT: This mode opens a file for reading only. The file must already exist, and no changes can be made to it. Example:
OPEN INPUT customerFile.
OUTPUT: This mode opens a file for writing only. If the file already exists, it will be overwritten. If the file does not exist, it will be created.Example:
OPEN OUTPUT customerFile.
I-O (Input-Output): This mode opens a file for both reading and writing. The file can be modified (rewritten), and records can be read and updated.Example:
OPEN I-O customerFile.
EXTEND: This mode is used to open a file for writing but will append data to the end of the file without overwriting existing records.Example:
OPEN EXTEND customerFile.
Each mode is used based on whether you need to read, write, or modify the file.
In COBOL, the CLOSE statement is used to close a file that has been opened for processing. It is important to close files after they are no longer needed, as this ensures that all data is written properly and system resources are released.
CLOSE <file-name>.
Example:
CLOSE customerFile.
In this example, the customerFile is closed after all operations (like reading or writing) are completed. Closing a file frees system resources and ensures that all changes made to the file are committed.
The READ statement in COBOL is used to retrieve a record from a file and move it into a data structure. It is most commonly used with files that have been opened for input (using the OPEN INPUT statement).
The READ statement reads the next record in a file sequentially.
READ <file-name> INTO <data-record> [AT END ...].
Example:
READ customerFile INTO customer-record.
In this example, the program reads the next record from customerFile and places it into the customer-record data structure. If there are no more records to read, the AT END condition will be triggered.
The STOP RUN statement in COBOL is used to end the execution of the program. When STOP RUN is encountered, the program terminates, and control is returned to the operating system or the calling environment (if there is one).
Syntax:
STOP RUN.
Example:
STOP RUN.
The STOP RUN statement indicates the program has completed all its processing and that no further statements will be executed.
The IF statement in COBOL is used for conditional processing. It allows the program to execute certain statements only when a specific condition is true.
Syntax:
IF <condition>
<statements to execute>
END-IF.
Example:
IF customer-age > 18
DISPLAY "Adult"
ELSE
DISPLAY "Minor"
END-IF.
In this example, the program checks if customer-age is greater than 18. If true, it displays "Adult"; otherwise, it displays "Minor".
You can also use IF with ELSE, ELSE IF, or NOT to create more complex branching logic.
The PERFORM statement in COBOL is used to call a paragraph or section of code for execution. It allows for the reuse of code and enables structured program flow by invoking blocks of logic repeatedly. This is similar to calling a function or method in other programming languages.
Basic Syntax:
PERFORM <paragraph-name>.
Example:
PERFORM process-customer.
In this example, the PERFORM statement calls the paragraph process-customer. The code defined in the process-customer paragraph will be executed.
You can also use PERFORM with loops and conditions to control repetitive actions.
PERFORM: The PERFORM statement calls a paragraph or section and executes it once. It is typically used for executing a block of code a single time or as part of a loop with a conditional check.Example:
PERFORM calculate-salary.
PERFORM UNTIL: The PERFORM UNTIL statement is used for repeated execution of a paragraph or section until a specific condition becomes true. It continues to perform the specified paragraph or section as long as the condition evaluates to FALSE.Syntax:
PERFORM <paragraph-name> UNTIL <condition>.
Example:
PERFORM process-record UNTIL end-of-file.
In this example, process-record is repeatedly called until the condition end-of-file is true. The PERFORM UNTIL statement allows for creating loops in the program.
In COBOL, conditional logic is typically handled using the IF statement, which allows the program to make decisions based on conditions. You can also use EVALUATE, which is similar to a switch-case or switch statement in other languages.
IF Statement: The IF statement checks a condition and executes statements based on whether the condition is true or false.Example:
IF customer-age > 18
DISPLAY "Adult".
ELSE
DISPLAY "Minor".
END-IF.
EVALUATE Statement: The EVALUATE statement is used for multiple conditions, much like a switch or case in other languages.Example:
EVALUATE customer-status
WHEN 'A'
DISPLAY "Active".
WHEN 'I'
DISPLAY "Inactive".
WHEN OTHER
DISPLAY "Unknown status".
END-EVALUATE.
Nested Conditions: You can also nest IF statements for more complex decision-making:
IF customer-age > 18
IF customer-status = 'A'
DISPLAY "Active Adult".
ELSE
DISPLAY "Inactive Adult".
END-IF.
In COBOL, a PERFORM loop is used to repeatedly execute a paragraph or section of code until a condition is met (using PERFORM UNTIL) or for a set number of iterations (using PERFORM with a range).
Example of a simple PERFORM loop:
01 counter PIC 9(2) VALUE 1.
PERFORM loop-process VARYING counter FROM 1 BY 1 UNTIL counter > 5.
DISPLAY "Loop finished."
STOP RUN.
loop-process.
DISPLAY "Counter is: " counter.
In this example:
The output will be:
Counter is: 1
Counter is: 2
Counter is: 3
Counter is: 4
Counter is: 5
Loop finished.
In COBOL, arrays are implemented using tables (or occurs clauses). Both subscripts and indexes are used to reference individual elements in these tables, but they are different in terms of behavior and performance:
MOVE customer-name(3) TO temp-name.
SET index TO 3
MOVE customer-name(index) TO temp-name.
In COBOL, arrays are implemented using tables, which are defined in the DATA DIVISION, under the WORKING-STORAGE SECTION or LINKAGE SECTION. A table is defined with the OCCURS clause, which specifies the number of elements the table can hold.
Syntax:
01 customer-names.
05 customer-name PIC X(30) OCCURS 100 TIMES.
In this example:
You can access individual elements using a subscript or an index.
Example with subscript:
MOVE "John Doe" TO customer-name(1).
Example with index:
SET index TO 1
MOVE "John Doe" TO customer-name(index).
A synonym in COBOL refers to creating an alternative name (alias) for a data item or a group of data items. This allows you to refer to the same data item with different names in different contexts, improving code clarity or accommodating different naming conventions in various sections of the program.
Syntax:
01 employee-data.
05 employee-id PIC 9(5).
05 employee-name PIC X(30).
01 employee-data-copy REDEFINES employee-data.
05 employee-id-copy PIC 9(5).
05 employee-name-copy PIC X(30).
In this example, employee-data-copy is a synonym for employee-data, meaning both can be used to refer to the same set of data. The REDEFINES clause is used to create synonyms, and it allows the program to manipulate data in different formats or ways without duplicating it.
In COBOL, the SIGN and USAGE clauses in a data description are used for different purposes:
Example:
USAGE: The USAGE clause defines the internal representation or format of the data. It is used to specify how COBOL should store the data in memory. Common usages include DISPLAY (default format), COMP (for binary storage), and COMP-3 (for packed decimal).Example:
01 packed-salary PIC 9(5) COMP-3.
The COMP-3 (or PACKED-DECIMAL) data type in COBOL represents a way to store numeric values in a compressed format. Each byte stores two digits, with one extra nibble (half byte) used for the sign of the number. This format is more memory-efficient compared to the standard DISPLAY format.
In COMP-3 format, the number is stored in packed decimal form, meaning each byte can hold two digits (one digit in each nibble). The last nibble of the last byte stores the sign of the number.Example:
01 salary PIC 9(5) COMP-3.
In COBOL, variables can be initialized either at the time of declaration using the VALUE clause, or dynamically during program execution.
Using the VALUE clause: The VALUE clause is used in the DATA DIVISION to assign an initial value to a variable at the time of its declaration.Example:
01 counter PIC 9(3) VALUE 10.
01 customer-id PIC X(10) VALUE "CUST1234".
Dynamically during execution: You can also assign values to variables in the PROCEDURE DIVISION using the MOVE statement.Example:
MOVE 0 TO counter.
MOVE "John" TO customer-name.
This approach allows more flexibility in managing initializations based on the execution context.
In COBOL, a program is divided into different sections, and the PROCEDURE DIVISION and DATA DIVISION are two of the main divisions that define how the program operates.
Example:
DATA DIVISION.
WORKING-STORAGE SECTION.
01 customer-name PIC X(30).
01 customer-age PIC 99.
Example:
PROCEDURE DIVISION.
DISPLAY "Enter customer name:".
ACCEPT customer-name.
Key difference: The DATA DIVISION deals with data definition and storage, while the PROCEDURE DIVISION handles the logic and actions to manipulate that data.
In COBOL, LEVEL numbers are used to define the hierarchy and structure of data items in the DATA DIVISION. They indicate the level of nesting or grouping of data items within a structure, particularly when defining group items and elementary items.
Example:
01 employee-record.
05 employee-name PIC X(30).
05 employee-id PIC 9(5).
05 employee-salary PIC 9(6)V99.
Importance: Level numbers establish the hierarchical structure of the data. The level hierarchy helps COBOL understand which fields are part of a group, which can be accessed sequentially, and how to manage memory allocation for different parts of the structure.
In COBOL, arrays are implemented using tables, which can be defined in the DATA DIVISION under the WORKING-STORAGE SECTION or LINKAGE SECTION. You can define arrays (or tables) using the OCCURS clause, which specifies the number of elements the array will contain.
Example:
01 employee-names.
05 employee-name PIC X(30) OCCURS 10 TIMES.
Example:
MOVE "John Doe" TO employee-name(1).
Example:
SET index TO 1.
MOVE "Jane Smith" TO employee-name(index).
COBOL does not have a native null data type as in other modern programming languages (like SQL or C#). However, you can simulate the handling of null values using various techniques:
Example:
IF customer-name = SPACES
DISPLAY "Name is missing."
END-IF.
Example:
IF employee-salary = ZERO
DISPLAY "Salary is missing."
END-IF.
Example:
01 null-flag PIC X VALUE "N".
01 customer-name PIC X(30).
IF null-flag = "N"
DISPLAY "Customer name is missing."
END-IF.
The INITIALIZE statement in COBOL is used to set all data items in a group to their initial values. For alphanumeric fields, the default value is spaces (SPACES), and for numeric fields, it is zero (ZERO).
Syntax:
INITIALIZE <data-item>.
Example:
01 employee-record.
05 employee-name PIC X(30).
05 employee-id PIC 9(5).
INITIALIZE employee-record.
Significance: It provides a simple way to ensure that data is reset to a known state, avoiding issues with uninitialized or stale data.
Both PIC X and PIC A are used in COBOL for defining alphanumeric data types, but they have subtle differences in usage:
Example:
01 customer-name PIC X(30).
Example:
01 employee-status PIC A(1).
Key difference: PIC A is stricter and only allows alphabetic characters, while PIC X allows any characters, including digits and spaces.
The EVALUATE statement in COBOL is used to perform multi-way branching (similar to a switch or case statement in other languages). It evaluates a condition and executes different actions based on the value of the condition.
Syntax:
EVALUATE <expression>
WHEN <value1>
<statements>
WHEN <value2>
<statements>
WHEN OTHER
<statements>
END-EVALUATE.
Example:
EVALUATE customer-status
WHEN 'A'
DISPLAY "Active".
WHEN 'I'
DISPLAY "Inactive".
WHEN OTHER
DISPLAY "Unknown".
END-EVALUATE.
Significance: The EVALUATE statement is useful for simplifying complex IF conditions and handling multiple cases cleanly in a single block of code.
In COBOL, string manipulation can be done using various built-in functions and techniques:
Example:
MOVE "John" TO customer-name.
Example:
STRING first-name DELIMITED BY SPACE
last-name DELIMITED BY SPACE
INTO full-name.
Example:
UNSTRING full-name DELIMITED BY SPACE
INTO first-name last-name.
Example:
MOVE FUNCTION LENGTH(full-name) TO string-length.
The REDEFINES clause in COBOL allows two or more data items to share the same memory space. It enables the reuse of the same memory location for different purposes. This can be useful for handling different data representations without allocating additional memory.
Syntax:
01 data-item1 PIC X(10).
01 data-item2 REDEFINES data-item1 PIC 9(10).
Significance: REDEFINES helps save memory and is used when you need to interpret the same data in different formats or representations.
COBOL supports several looping constructs, primarily:
Example:
PERFORM process-record UNTIL end-of-file.
Example:
PERFORM process-record VARYING index FROM 1 BY 1 UNTIL index > 10.
Example:
PERFORM process-record.
Key difference: PERFORM UNTIL and PERFORM VARYING are used for loops with conditions or iterations, while a simple PERFORM is used for calling a paragraph once.
COBOL traditionally doesn't support dynamic arrays (like in languages such as C or Java). However, dynamic arrays can be simulated using the OCCURS DEPENDING ON clause, which allows you to define an array whose size is determined at runtime. This gives a similar effect to dynamic arrays.
Example:
01 employee-records.
05 employee-name PIC X(30) OCCURS 0 TO 100 TIMES
DEPENDING ON employee-count.
To adjust the number of elements, you can change employee-count during the program execution:
MOVE 50 TO employee-count.
This allows for a "dynamic" effect, although COBOL doesn't inherently support true dynamic memory allocation like modern languages.
In COBOL, file structures are used to organize and manage data stored in files. These files can be categorized by how data is stored and accessed. The main file types in COBOL are Sequential Files, Indexed Files, and VSAM Files (Virtual Storage Access Method). Each type serves different purposes and supports specific ways of reading and writing data.
Example:
SELECT file-name ASSIGN TO 'data.txt'
ORGANIZATION IS SEQUENTIAL.
Example:
SELECT file-name ASSIGN TO 'data.idx'
ORGANIZATION IS INDEXED
ACCESS MODE IS DYNAMIC.
Example:
SELECT vsam-file ASSIGN TO 'data.vsam'
ORGANIZATION IS VSAM
ACCESS MODE IS SEQUENTIAL.
Each of these file types is suited for different applications based on the required speed of access, organization of data, and type of operations (sequential or random).
The CALL statement in COBOL is used to invoke a subprogram (or external program) from within the main program. This allows you to break your program into smaller, manageable parts and execute shared logic from other COBOL programs or subroutines.
Purpose: To execute code in another program or subprogram and pass control to that program. It helps in code reusability, modularization, and improved program maintenance.Syntax:
CALL 'subprogram-name' USING parameter1 parameter2.
Example:
CALL 'SUBPROG' USING input-data output-data.
In this example, the CALL statement invokes a subprogram called SUBPROG and passes input-data and output-data to it.
To call a subprogram in COBOL, you use the CALL statement, which passes control to the subprogram. The subprogram can receive parameters (input or output) through the USING clause, and it can return control back to the main program after executing.
Main Program Example:
CALL 'SUBPROGRAM' USING input-var output-var.
SUBPROGRAM.
01 input-var PIC X(10).
01 output-var PIC X(10).
PROCEDURE DIVISION.
MOVE "Processed" TO output-var.
The GOBACK statement is used to return control from a subprogram or a called program to the calling program. It is a way to exit a subprogram gracefully.
Example:
GOBACK.
The LINKAGE SECTION in COBOL is used in the subprogram to define variables that are passed from the main program to the subprogram. These variables are referred to as parameters.
Example:
LINKAGE SECTION.
01 passed-data PIC X(20).
01 result PIC X(20).
PROCEDURE DIVISION USING passed-data result.
In the main program, when calling the subprogram, the USING clause passes the actual values to the LINKAGE SECTION in the subprogram.
Main Program:
CALL 'SUBPROG' USING customer-name result.
Subprogram:
LINKAGE SECTION.
01 customer-name PIC X(20).
01 result PIC X(20).
PROCEDURE DIVISION USING customer-name result.
This enables the subprogram to work with data passed by the main program.
When passing parameters to a subprogram in COBOL, there are two main methods: Call by Value and Call by Reference.
Example:
CALL 'SUBPROGRAM' USING customer-name.
Example:
CALL 'SUBPROGRAM' USING BY VALUE customer-name.
Parameters can be passed to a COBOL subprogram using the USING clause in the CALL statement. When calling a subprogram, you list the variables that you want to pass as arguments, and they are received by the subprogram using the USING clause in its PROCEDURE DIVISION.
Main Program:
CALL 'SUBPROG' USING customer-id customer-name.
Subprogram:
LINKAGE SECTION.
01 customer-id PIC 9(5).
01 customer-name PIC X(30).
PROCEDURE DIVISION USING customer-id customer-name.
This allows the subprogram to work with the passed data.
COBOL does not have built-in exception handling like modern languages (e.g., Java or Python), but error handling can be done using:
Example:
IF FILE-STATUS NOT = '00'
DISPLAY 'File error.'
END-IF.
Example:
DECLARATIVES.
FILE-ERROR.
DISPLAY 'File not found.'
END-DECLARATIVES.
The SORT statement in COBOL is used to sort records in a file in either ascending or descending order. This is commonly used when you need to process data in a particular order, such as sorting employee records by salary or customer orders by date.
Syntax:
SORT file-name
ON ASCENDING KEY key1
ON DESCENDING KEY key2
USING input-file
GIVING output-file.
Example:
SORT employee-file
ON ASCENDING KEY employee-id
USING unsorted-employee-file
GIVING sorted-employee-file.
In this example:
The SORT operation is a built-in COBOL operation that can handle large datasets efficiently, and it works with both sequential and indexed files.
The OPEN statement in COBOL is used to open files for reading, writing, or both, depending on the required operation. There are three main modes:
Example:
OPEN INPUT file-name.
Example:
OPEN OUTPUT file-name.
Example:
OPEN I/O file-name.
These modes are used to control how files are accessed and manipulated in the program.
COBOL’s memory management capabilities are quite limited compared to modern programming languages. COBOL does not have direct support for dynamic memory allocation (e.g., through pointers or malloc). However, it provides a few ways to handle memory efficiently:
Example:
01 employee-record.
05 employee-id PIC 9(5).
05 employee-name PIC X(30).
The INSPECT statement in COBOL is used to manipulate strings. It can perform tasks like counting occurrences of a character, replacing characters, or converting the case of a string.
There are three main ways to use the INSPECT statement:
Syntax:
INSPECT string COUNTING FOR ALL 'X' IN string.
Example:
INSPECT customer-name COUNTING FOR ALL 'A' IN customer-name.
Syntax:
INSPECT string REPLACING ALL 'A' BY 'B' IN string.
Example:
INSPECT customer-name REPLACING ALL 'A' BY 'Z' IN customer-name.
Syntax:
INSPECT string CONVERTING 'a' TO 'A' IN string.
In COBOL, file access methods define how records are read or written to files. The two main types of file access are sequential access and indexed access.
In COBOL, Group Items and Elementary Items are used to describe different types of data items in the DATA DIVISION:
Example:
01 employee-record.
05 employee-id PIC 9(5).
05 employee-name PIC X(30).
Example:
01 employee-id PIC 9(5).
01 employee-name PIC X(30).
Error checking in COBOL for file I/O is typically done using the file status code, which indicates whether a file operation (e.g., read, write, open, close) was successful or encountered an error.
Example of error checking:
OPEN INPUT file-name
IF file-status NOT = '00'
DISPLAY 'Error opening file. Status code: ' file-status
END-IF.
The WRITE statement is used to write a record to a file in COBOL. The WRITE statement can be used with sequential and indexed files to add new records to the file.
Syntax:
WRITE record-name.
Example:
WRITE employee-record.
In this example, the contents of employee-record are written to the output file.
When working with multiple files in COBOL, you can perform various file operations (such as OPEN, READ, WRITE, CLOSE) for each file. Each file is assigned a unique file control entry in the FILE SECTION of the DATA DIVISION, and each file is accessed using specific file-handling operations.
Example of working with multiple files:
SELECT file1 ASSIGN TO 'file1.dat'.
SELECT file2 ASSIGN TO 'file2.dat'.
OPEN INPUT file1
OPEN OUTPUT file2
READ file1 INTO employee-record.
WRITE employee-record TO file2.
CLOSE file1
CLOSE file2.
Each file must be opened, processed, and closed individually, depending on the required operations.
A recursive subprogram is a subprogram that calls itself, either directly or indirectly, to solve problems that can be broken down into smaller subproblems (like calculating factorials or traversing tree structures).
Example of a simple recursive function to calculate factorial:
FACTORIAL-PROG.
01 result PIC 9(5).
01 number PIC 9(3).
PROCEDURE DIVISION.
IF number = 0
MOVE 1 TO result
ELSE
CALL 'FACTORIAL-PROG' USING (number - 1) RETURNING result
MULTIPLY result BY number GIVING result.
END-IF.
In this example, the subprogram calls itself to compute the factorial recursively.
In COBOL, concatenating two strings can be done using the STRING statement. This statement allows you to combine multiple strings into a single string.
Syntax:
STRING string1 DELIMITED BY size1
string2 DELIMITED BY size2
INTO result-string.
Example:
01 first-name PIC X(10) VALUE 'John'.
01 last-name PIC X(10) VALUE 'Doe'.
01 full-name PIC X(20).
STRING first-name DELIMITED BY SPACE
last-name DELIMITED BY SPACE
INTO full-name.
In this example:
In COBOL, the OPEN, READ, WRITE, and CLOSE statements are used to interact with files. These statements allow you to open a file, read data from it, write data to it, and finally close the file when you're done.
Syntax:
OPEN INPUT file-name (for reading)
OPEN OUTPUT file-name (for writing)
OPEN I/O file-name (for both reading and writing)
Syntax:
READ file-name INTO record-name
Syntax:
WRITE record-name.
Syntax:
CLOSE file-name.
Example of file handling:
OPEN INPUT input-file.
READ input-file INTO input-record.
IF NOT EOF
OPEN OUTPUT output-file.
WRITE output-record.
END-IF.
CLOSE input-file.
CLOSE output-file.
Yes, COBOL allows you to CALL subprograms (which can be thought of as functions) using the CALL statement. COBOL doesn’t have a specific concept of functions, but subprograms are used to encapsulate logic.
CALL Syntax:
CALL 'subprogram-name' USING parameter1 parameter2.
Example:
CALL 'ADD-NUMBERS' USING number1 number2 RETURNING result.
In this example, ADD-NUMBERS is a separate subprogram that takes two numbers, adds them, and returns the result to the main program.
Key Notes:
The Report Writer is a specialized COBOL feature used for generating reports from data files. It allows easy formatting and control of the layout of reports without manually writing complex print formatting code. It’s commonly used in business applications for generating financial reports, transaction summaries, and other structured reports.
Example:
REPORT SECTION.
01 report-heading.
05 line1 PIC X(50) VALUE 'Employee Report'.
05 line2 PIC X(50) VALUE '--------------------------------'.
01 report-line.
05 emp-id PIC 9(5).
05 emp-name PIC X(30).
05 emp-salary PIC 9(5)V99.
PROCEDURE DIVISION.
OPEN REPORT output-file.
WRITE report-heading.
PERFORM write-employee-records.
CLOSE REPORT.
In COBOL, string comparison is done using the IF statement and =, >, < operators. You can directly compare strings in a conditional statement.
Example:
IF string1 = string2
DISPLAY 'Strings are equal'.
ELSE
DISPLAY 'Strings are different'.
END-IF.
COBOL also supports comparison of strings using INSPECT or UNSTRING, but for simple equality checks, you use the comparison operators directly.
Example (lexicographical comparison):
IF string1 > string2
DISPLAY 'string1 is greater'.
ELSE
DISPLAY 'string1 is not greater'.
END-IF.
The evolution of COBOL from version 74 to 2002 introduced several new features and enhancements:
Each version introduced more modern programming features, making COBOL more adaptable to new technologies and use cases.
The NUMERIC data type in COBOL is used to define variables that hold numeric values. It ensures that the data items can only contain numbers (digits 0-9) and does not allow alphabetic or special characters.
Syntax:
01 total-sales PIC 9(5).
A binary search algorithm is a fast method for finding an item in a sorted list or array by repeatedly dividing the search interval in half.
Example (simplified):
01 number-array.
05 numbers OCCURS 10 TIMES PIC 9(3) VALUE ZEROS.
01 low-index PIC 9(2) VALUE 1.
01 high-index PIC 9(2) VALUE 10.
01 middle-index PIC 9(2).
01 target-item PIC 9(3).
PROCEDURE DIVISION.
MOVE 5 TO target-item.
PERFORM BINARY-SEARCH.
BINARY-SEARCH.
COMPUTE middle-index = (low-index + high-index) / 2
IF numbers(middle-index) = target-item
DISPLAY 'Item found at index ' middle-index
ELSE IF numbers(middle-index) < target-item
MOVE middle-index + 1 TO low-index
PERFORM BINARY-SEARCH
ELSE
MOVE middle-index - 1 TO high-index
PERFORM BINARY-SEARCH
END-IF.
This code performs binary search recursively, dividing the array until the target item is found or the search space is exhausted.
In COBOL, USAGE IS INDEX and USAGE IS POINTER are used to define how variables are stored and accessed in memory.
Syntax:
01 employee-table.
05 employee-record OCCURS 100 TIMES INDEXED BY emp-index.
Syntax:
01 ptr-variable POINTER.
SORT-MERGE in COBOL is used when you have multiple sorted input files and you need to merge them into a single sorted output file. The MERGE operation combines multiple sorted files, keeping the data sorted.
Syntax:
SORT file-name
ON ASCENDING KEY key1
MERGE file1 file2
GIVING output-file.
This operation reduces the complexity of merging sorted data manually and is optimized for performance.
Optimizing COBOL programs involves techniques to reduce CPU usage, memory consumption, and overall execution time. Here are some key strategies:
In COBOL, reentrant and non-reentrant refer to whether a subprogram can be safely executed concurrently by multiple users or programs without causing data corruption or inconsistencies.
Key Difference:
In COBOL, file organizations refer to how data is stored in a file and how records are accessed. Here are the common types:
Summary:
In COBOL, sorting is the process of arranging records in a particular order (e.g., ascending or descending) based on a specified key. Sorting can be internal or external:
Syntax:
SORT input-file
ON ASCENDING KEY key1
GIVING output-file.
Summary:
The SQL Precompiler in COBOL is used to embed SQL statements within a COBOL program. The SQL Precompiler converts embedded SQL statements into standard COBOL code that can interact with a database management system (DBMS).
Example:
EXEC SQL
SELECT emp-name, emp-salary
INTO :emp-name, :emp-salary
FROM employee
WHERE emp-id = :emp-id
END-EXEC.
COBOL provides several mechanisms for handling exceptions and errors, particularly in I/O operations or SQL interactions:
Use the STATUS variable to capture error information:
OPEN INPUT input-file.
IF NOT FILE-STATUS = '00'
DISPLAY 'Error opening file: ' FILE-STATUS.
END-IF.
When using SQL in COBOL (via the SQL Precompiler), errors are handled by checking SQLCODE or SQLSTATE:
EXEC SQL
SELECT COUNT(*)
INTO :count
FROM orders
END-EXEC.
IF SQLCODE NOT = 0
DISPLAY 'SQL Error: ' SQLCODE
END-IF.
You can also use the ON EXCEPTION clause with the PERFORM statement to handle specific conditions:
PERFORM PROCESS-DATA ON EXCEPTION
DISPLAY 'Error during processing'.
In COBOL, tables (also known as arrays) are used to store multiple values in a single data structure. Tables are used for organizing and manipulating large amounts of similar data, such as customer records or inventory items.
01 employee-table.
05 employee-record OCCURS 100 TIMES
INDEXED BY emp-index.
10 emp-id PIC 9(5).
10 emp-name PIC X(30).
10 emp-salary PIC 9(5)V99.
You can access and manipulate individual elements using the index or subscript:
MOVE 12345 TO employee-record(1) OF employee-table.
In COBOL, dynamic memory allocation (using pointers) is achieved through the ALLOCATE and FREE statements (available in some modern versions of COBOL, particularly when running on more advanced systems).
Example:
01 my-pointer POINTER.
01 my-memory POINTER.
CALL 'ALLOCATE' USING my-pointer.
MOVE my-pointer TO my-memory.
Deadlock occurs when two or more processes are waiting for each other to release resources, resulting in a standstill where none of the processes can proceed.