Вы находитесь на странице: 1из 171

Patni Computer Systems Ltd.

COBOL

Training Workshop

Student Guide

Copyright © 2005 Patni Computer Systems Ltd., Akruti, MIDC Cross Road No. 21, Andheri (E),
Mumbai 400 093. All rights reserved. No part of this publication can be reproduced in any way,
including but not limited to photocopy, photographic, magnetic, or other record, without the
prior agreement and written permission of Patni Computer Systems.

Patni Computer Systems considers information included in this document to be Confidential and
Proprietary.
COBOL

COBOL
Student Guide

Version 4.0
18th July 2005

Page 1 of 163
COBOL

Table of Contents
1. Introduction................................................................................... 5
2. Working with data ......................................................................... 12
3. ACCEPT/DISPLAY verbs ................................................................... 33
4. MOVE statements .......................................................................... 35
5. Arithmetic verbs ........................................................................... 41
6. Decision Making ............................................................................ 53
7. Iterations .................................................................................... 65
8. File Handling ................................................................................ 68
9. Sorting........................................................................................ 79
10. Trapping Runtime errors .............................................................. 82
11. REPORTS .................................................................................. 85
12. CONTROL BREAK PROCESSING ........................................................ 90
13. Indexed Files ............................................................................ 101
14. File updation ............................................................................ 119
15. Call statement .......................................................................... 126
16. Table Handling.......................................................................... 132
17. String Handling ......................................................................... 153
18. Appendix –A (Standards) .............................................................. 162
19. Appendix –B (Bibliography/References) ........................................... 163
20. Appendix –C (File Status codes) ..................................................... 164
21. Appendix – D (Syntax) ................................................................. 165

Page 2 of 163
COBOL

Day-Wise Schedule

Day 1
Introduction
Programming Structure, Coding Formats
Constants, Identifiers, Figurative Constants
Data Division
Level numbers
Elementary and group data names

Procedure Division
Input and Output verbs
Simple Programs

Day 2
Data Division (contd)
Picture clauses [Edit and computation]
Value clause, Usage clause, Redefines clause, Renames clause
Arithmetic verbs
Move
Numeric, Non numeric, Group
Control verbs
If, Condition names, Goto, Perform
Sample Programs

Day 3
File Organization Concepts
Sequential Files
Creation
Access
Query
Sort sequential files
Copy verb

Day 4
Trapping Runtime errors
Simple reports
Reports with page totals and net totals

Day 5
Single level control break
Double level control break
Index files

Page 3 of 163
COBOL

Creation [Record key and alternate keys]


Conversion of sequential to indexed files
Random and sequential access

Day 6
Start verb
Edit and deleted records in indexed files
File maintenance
Report generation with index files

Day 7
Master, Transaction files
File update
Update existing master
Create new master

Day 8
Table Handling
One and two dimensional arrays
Redefines clause
Files and tables
Search a table

Day 9
Subprograms
Call verb
Linkage section
String Handling verbs

Page 4 of 163
COBOL

1. Introduction
COBOL (Common Business Oriented Language) was developed in 1959 by a group
called the CODASYL Committee. CODASYL is an abbreviation for Conference on Data
Systems Languages. This committee included representatives from academia, user
groups, and computer manufacturers. The ultimate objective of this committee was
to develop a standard business-oriented language for which all major manufacturers
would provide compilers. The Department of Defense convened this conference since
it, as well as other government agencies, was particularly dissatisfied with the lack of
standards in the computing field.

1.1 Features of COBOL


Business-Oriented Language
As a business-oriented language COBOL is designed specifically for commercial
applications, such as payroll and inventory that typically operate on a large volume of
data. File handling, is an essential part of business programming. Most business
programming applications center around storing and retrieving information.

A Standard Language
COBOL compilers are available for most computers. The same COBOL program may be
compiled and run on a variety of different machines.
The universality of COBOL allows computer users greater flexibility than they would
have with many other languages. A company is free to acquire different brands of
computers while using a single programming language. Similarly, conversion from one
model computer to a more advanced or newer one presents no great problem as long
as there is a COBOL compiler for each model.

An English-like Language
COBOL is an English-like language. All instructions can be coded using English words
rather than complex codes. To add two numbers together, for example, we use the
word ADD. Similarly, the rules for programming in COBOL conform to many of the
rules for writing in English, making it a relatively simple language to learn.

Self Documenting
One advantage of COBOL computer programs is that they can be substantially self-
documenting. Self-documentation is a characteristic of a language that allows a
reader of a program to understand its function and follow its processing steps. The
language instructions are very English-like, but the programmer has substantial choice
as to whether to make a program self-documenting or obscure.

Page 5 of 163
COBOL

1.2 Coding a COBOL program


A COBOL program file will have an extension .CBL. A COBOL program needs to be
coded following the below mentioned coding rules.

Columns Use Explanation


1-6 Sequence numbers or Used for sequence-checking
Page and Line numbers
(optional)
7 Indicator column Denotes
* comments
/ page break
- continue strings
8-11 Area A DIVISION, SECTION, paragraph
names and level 01, 77 entries
12-72 Area B Statements and sentences
73-80 Comment Ignored by the compiler

Note : Division, Section, Paragraph Names and Sentences must end with a period followed by at least
one space.

Each line in a COBOL program can consist of up to 80 characters. This size reflects the
fact that all early COBOL programs were punched into standard IBM 80-column
computer cards. Despite the fact that much COBOL programming is now done on
terminals as well as mini- and microcomputers, the 80-column line length has been
maintained.

The first six characters in the line contain the line or sequence number. The sequence
numbers generally serve as references for inserting, deleting, and editing program
lines.

Column 7 is reserved for a continuation or comment character. When an * is typed in


column 7, the remainder of the line is treated by the COBOL compiler as a comment
of the programmer. That is, when the source code program is compiled, all lines with
an asterisk in column 7 are ignored.

When the – (hyphen) is found in column 7, this signals that the line contains the
remainder of a nonnumeric literal. In other words, a nonnumeric literal is being
continued on this line from the preceding line.

Column 8 is referred to as Margin A, and columns 8-11 are commonly Area A. A


number of entries must begin in this area – division names, section names, paragraph
names, FD entries, 01-level entries, and 77-level entries. These entries must begin
only in Area A, they can go beyond column 11 but must begin somewhere in Area A.
For example, a paragraph name could begin in column 11 and continue beyond.

Page 6 of 163
COBOL

Column 12 is known as Margin B, and columns 12-72 are commonly called Area B. Most
COBOL entries, particularly those in the Procedure Division, begin in this area. Margin
B entries include all sentences, statements, 02-49 level entries, and others. Note,
that these entries must begin in Area B and cannot extend beyond column 72.

Column 73-80 are referred to as the program-identification columns. These columns


are ignored by the compiler.

1.3 The COBOL Character set


The character set used in COBOL consists of the following :
Alphabetic characters
The capital letters of the English alphabets, A to Z.

Numeric characters
The first ten numerals, 0 to 9.

Punctuation characters
Comma ,
Semicolon ;
Period .
Blank or Space
Apostrophe ’
Left Parenthesis (
Right Parenthesis )

Special characters
Hyphen -
Equal =
Asterisk *
Plus +
Slash /
Greater Than >
Less Than <
Dollar $

1.4 COBOL Words


A sequence of continuous characters from the character set can form a word. Like any
other language, COBOL consists of words and symbols. There are rules for making
COBOL words. There are two types of COBOL words, reserved words and user-defined
words.

Reserved words are words that are defined both syntactically and semantically by the
COBOL language. The programmer cannot use any of these words except in the form
specified by the language.

Page 7 of 163
COBOL

User-defined words (data names) are words supplied by the programmer in order to
satisfy the format of a clause or statement in the language.

Rules for forming user-defined words

• 1 to 30 characters.
• Letters, digits, and hyphens (-) only.
• No embedded blanks.
• At least one alphabetic character.
• May not begin or end with a hyphen.
• No COBOL reserved words such as DATA, DIVISION, etc.

Valid datanames Invalid datanames


HOURS DISCOUNT-
SALES-TOTAL AUTHOR
SUBJECT1 BASIC+HRA
AMOUNT-OF-TRANSACTION-OUT 123

1.5 Structure of COBOL programs


COBOL programs are written according to a special structure, which is organized into
a hierarchy of parts.

A character is the lowest form in the program structure

A word is made up of one or more characters.

A clause consists of characters and words and is used to specify an attribute of an


entry.

A statement is a syntactically valid combination of words and characters written in


the PROCEDURE DIVISION of a COBOL program and beginning with a verb.

A sentence is a sequence of one or more statements, the last of which is terminated


by a period followed by a space.

A paragraph consists of one or more sentences.

A section consists of one or more paragraphs.

A division consists of one or more paragraphs or sections. Every COBOL program


consists of four divisions in the following order : IDENTIFICATION DIVISION,
ENVIRONMENT DIVISION, DATA DIVISION and PROCEDURE DIVISION.

Page 8 of 163
COBOL

1.6 Divisions
1.6.1 IDENTIFICATION DIVISION

The IDENTIFICATION DIVISION is the first division of a COBOL program. It supplies the
information about the program to others who may read or use the program. The
IDENTIFICATION DIVISION is divided into the following paragraphs :

PROGRAM-ID. Program-name.
Used to specify the program name. Use names of eight characters or less, letter and
digits only, because such names are accepted on all systems.

AUTHOR. author-name.
Used to specify the programmer’s name.

DATE-WRITTEN. Date.
Specify the date the program was coded.

DATE-COMPILED. Date.
Can be coded with an actual date. But if it is coded without a date entry, the
compiler itself will automatically fill in the actual date of compilation.

While PROGRAM-ID is the only required paragraph in the Identification Division, all
other entries should routinely be included. Only if the programmer includes the non-
required entries, which provide useful information, will COBOL be the self-
documenting language that it was designed to be.

1.6.2 ENVIRONMENT DIVISION

The ENVIRONMENT DIVISION is the only machine-dependent division of a COBOL


program. Machine dependent means that the entries are determined by the particular
type of computer equipment being used. While the sections and paragraph names will
always be the same, the entries themselves will depend on the type of equipment
used. This division is composed of two sections :

• CONFIGURATION SECTION.
SOURCE-COMPUTER. Computer.
Names the computer equipment used for compiling the program.

OBJECT-COMPUTER. Computer.
Names the computer equipment used for executing the program.

• INPUT-OUTPUT SECTION.

Page 9 of 163
COBOL

Supplies information concerning the input and output devices used. This section is
required only if the program uses files or prints reports.

FILE-CONTROL.
In this paragraph, a filename is selected for each file to be used in the program; in
addition, each file-name selected is assigned to a device.

1.6.3 DATA DIVISION

The DATA DIVISION provides detailed specifications for all the files and records within
the files that will be used in the program. In addition, all other data items required
by the program are named and described in this division. Commonly, it consists of the
following sections:

FILE SECTION.
Defines all input and output files.

WORKING-STORAGE SECTION.
Reserves storage for fields not part of input or output but nonetheless required for
processing. These include constants, end-of-file indicators, and work areas.

LINKAGE SECTION.
Used to identify items that will be passed to the called program from the calling
program and vice-versa.

These sections appear in the given order.

1.6.4 PROCEDURE DIVISION

The PROCEDURE DIVISION is divided into sections/paragraphs. Each paragraph is an


independent module or routine that includes a series of instructions designed to
perform specific set of operations. Paragraph names are coined by the programmer
following the rules for forming data-names.

A PROCEDURE DIVISION may also consist of several sections. A section may contain
several paragraphs.

1.7 COBOL Coding rules


Division and section names must
a. begin in Area A,
b. end with a period, and
c. appear on a line alone – that is, with no other entries.

Page 10 of 163
COBOL

Paragraph names
d. must begin in Area A,
e. must end with a period, and
f. may appear on a line alone or with other entries. There must be at least one
space between each entry on the line.

Sentences
g. must begin in Area B,
h. must end with a period, and
i. may appear on a line alone or with other entries. There must be at least one
space between each entry on a line.

IDENTIFICATION DIVISION.
PROGRAM-ID. CH01EX01.
*****************************************
*My first COBOL program *
*****************************************
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
SOURCE-COMPUTER. IBM-PC.
OBJECT-COMPUTER. IBM-PC.

DATA DIVISION.
WORKING-STORAGE SECTION.
01 WS-TEMP PIC X(01).

PROCEDURE DIVISION.
0000-MAIN.
DISPLAY 'MY FIRST COBOL PROGRAM'.
ACCEPT WS-TEMP.
STOP RUN.

Example 1.1

Page 11 of 163
COBOL

2. Working with data


Data Names

A data-storage item or variable, as it is sometime known, is a symbolic name that


references a particular memory location, or address, within the computer.
A data name is a COBOL word formed by the programmer to represent the data items
used in his program. A data name should adhere to the rules for naming a user-
defined word.

Hierarchical representation of data

Level numbers

The record description specifies the format of a record . Record description entries
indicate:
1. The items or fields to appear in the record
2. The order in which the fields appear
3. How these fields are related to one another

Data is grouped in COBOL using the concept of a level. Records are considered the
highest level of data in a file, and are coded on the 01 level. There can be only one
data-name at the 01 level for each record, as it is the all-inclusive data-name. A
field of data within the record is coded on a level subordinate to 01, i.e. 02, 03 and so
on. Any level number between 02 and 49 may be used to describe fields within a
record. Level numbers are used to indicate the relationship of one field to another.

The permissible level numbers are :


01 – 49
66 77 88

Elementary and Group Items

An elementary item has no subordinate parts. A group item may consist of one or
more group/elementary items. In the code below :
CUST-FIRST-NAME, CUST-ZIP-CODE are elementary items
CUST-ADDRESS, CUST-STREET are group items

Page 12 of 163
COBOL

01 CUST-ADDRESS.
05 CUST-NAME.
10 CUST-FIRST-NAME PIC X(10).
10 CUST-LAST-NAME PIC X(15).
05 CUST-STREET.
10 CUST-ST-NO PIC 9(03).
10 CUST-ST-NAME PIC X(20).
05 CUST-ZIP-CODE PIC 9(06).

Example 2.1
PICTURE Clauses

Group items are defined by a level number and a name, which is followed by a period.
Elementary items must be described with a PICTURE (or PIC, for short) clause. Group
items cannot have a PICTURE clause. The syntax for the PICTURE clause is simple the
word PICTURE or PIC followed by the type and field size.

PICTURE type(size)

There cannot be a space between the type symbol and the number enclosed in
parentheses.

Functions of the PICTURE Clause

1. Specifies the type of data contained within an elementary item.


2. Indicates the size of the field.

Types of data fields

Type Picture Explanation


clause
Alphabetic A A field that may contain only letters or blanks.
E.g. a name or item description field.
Alphanumeric X A field that may contain any character i.e.
letters, digits, blanks and/or special
characters. E.g. an address field.
Numeric 9 Any signed or unsigned field that will contain
only digits is considered numeric.

Size of data fields

The size of the field is denoted b the number of A’s, X’s, or 9’s used in the PICTURE.

05 W01-AMT PIC 99999.


Example 2.2

Page 13 of 163
COBOL

W01-AMT is an elementary field consisting of five positions of numeric data.


Alternatively, the same can be coded as follows :

05 W01-AMT PIC 9(05).


Example 2.3
At least one space must follow the word PIC. All A’s, X’s, or 9’s should appear
consecutively with no spaces between the characters. Similarly, if parentheses are
used to denote the size of a field, no spaces should appear between the type and size
or within the parentheses.

Alphanumeric and alphabetic fields can be a maximum of 120 characters in size while
numeric fields can be a maximum of 18 digits in size.

Each field can contain only one type of data. For example, PICTURE XXX99 is invalid.

WORKING-STORAGE SECTION

Defines and describes all data storage fields required for Processing (Including
constants). These fields are not part of any record in an input/output file.

Can be used for storing


• Intermediate results
• Counters, Flags
• Input/Output Records
• Tables etc.

2.1 Types of data


• Variable
Data entered by the user at run-time.

• Constant
Data required for processing that is not dependent on the input to the system.
There are 3 types of literals.

1. Numeric Literals
A numeric literal is a constant used primarily for arithmetic operations.

Rules for forming numeric literals


• 1 to 18 digits
• A + or – sign may be used, but it must appear to the left of the number.
• A decimal point is permitted within the literal. The decimal point, however
may not be the rightmost character of the literal.

Page 14 of 163
COBOL

+34
-8.6
.008

Example 2.4
2. Nonnumeric Literals
A nonnumeric literal is a constant that is used in the PROCEDURE DIVISION
for all operations except arithmetic.

Rules for forming nonnumeric literals


• The literal must be enclosed in quotation marks.
• A maximum of 120 characters are permitted.
• Any character permitted in the COBOL character set may be used except
the quotation mark.

‘CODE’ , ‘$ 123’

Example 2.5
3. Figurative Constants

A figurative constant is a COBOL reserved word that has special significance to the
compiler.

The figurative constants are :

ZERO, ZEROS, ZEROES references the value of zeros


SPACE, SPACES reference the value of blank
QUOTE, QUOTES references the quotation mark
used in nonnumeric literals to include a
quote.
LOW-VALUE , LOW-VALUES references the lowest value in the collating
sequence for the particular computer system
HIGH-VALUE, HIGH-VALUES references the highest value in the collating
sequence for the particular computer
system.
ALL references one or more occurrences of the
single character nonnumeric literal.
e.g. MOVE ALL ‘A’ TO HEAD-1, will result in
the field HEAD-1 being filled with A’s.

Page 15 of 163
COBOL

VALUE Clause

In addition to defining storage fields using the PICTURE clause it is often desirable to
assign initial values to elementary items in the WORKING-STORAGE SECTION. Such a
value may remain unchanged throughout the program, or it may change in the course
of program execution. Such initial values are generally not assigned to FILE SECTION
items, since such fields either receive their data from the external medium or from
other storage location as the result of program execution.

02 PAGE-TITLE PIC A(14) VALUE ‘SAMPLE PROGRAM’.


02 TAX-RATE PIC 99 VALUE IS 10.

Example 2.6
Continuation of Literals from one line to the next

A nonnumeric literal may contain up to 120 characters. The same applies to a


nonnumeric literal in a VALUE clause. Sometimes a nonnumeric literal may not fit on a
single line, hence it is necessary to continue this literal.

Rules for continuation of nonnumeric literals

1. Begin the literal in the VALUE clause with a quotation mark.

2. Continue the literal until position 72, the end of the line, is reached. Do not end
with a quotation mark on this line.

3. Place a hyphen on the next line in the position beginning in 7th column of the
second line. Begin with a quotation mark.

4. End the literal with a quotation mark.

Page 16 of 163
COBOL

IDENTIFICATION DIVISION.
PROGRAM-ID. CH02EX07.
*************************************************
*Continuation of a literal *
*************************************************

ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
SOURCE-COMPUTER. IBM-PC.
OBJECT-COMPUTER. IBM-PC.

DATA DIVISION.
WORKING-STORAGE SECTION.

01 H01-PAGE-HEADING PIC X(43) VALUE 'MONTHLY TRANSACTIONS FO


- 'R THE MONTH OF APRIL'.

PROCEDURE DIVISION.
0000-MAIN.
DISPLAY H01-PAGE-HEADING.
STOP RUN.

Example 2.7
Picture Clauses

2.2 Special Characters (Numeric Field) :

Implied decimal point

The symbol V denotes an implied decimal point, which does not occupy a storage
position. In the code below, W01-AMOUNT occupies 5 positions.

05 W01-AMOUNT PIC 999V99.

Example 2.8

IDENTIFICATION DIVISION.
PROGRAM-ID. CH02EX09.
*************************************************
*Using picture clause V (implied decimal point) *
*************************************************

ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
SOURCE-COMPUTER. IBM-PC.
OBJECT-COMPUTER. IBM-PC.

DATA DIVISION.
WORKING-STORAGE SECTION.

Page 17 of 163
COBOL

01 W01-NUMBERS.
05 W01-NUM1 PIC 99V9 VALUE 38.50.
05 W01-NUM2 PIC 9(04)V99 VALUE 452.39.
05 W01-NUM3 PIC 9(04)V99 VALUE 102.4.
01 WS-TEMP PIC X(01).

PROCEDURE DIVISION.
0000-MAIN.
DISPLAY 'NUM 1 :' W01-NUM1.
DISPLAY 'NUM 2 :' W01-NUM2.
DISPLAY 'NUM 3 :' W01-NUM3.
ACCEPT WS-TEMP.
STOP RUN.

Example 2.9

PIC Description Value Stored as


99V9 38.50 385
9(04)V99 452.39 045239
9(04)V99 102.4 010240

Signed numbers

If a numeric field can have negative contents, then it must have an S in its PIC clause.
It must be the leftmost character. It does not take any storage space.

05 W04-BALANCE PIC S999.

Example 2.10

IDENTIFICATION DIVISION.
PROGRAM-ID. CH02EX11.
*******************************************
*Using picture clause S (signed numbers) *
*******************************************

ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
SOURCE-COMPUTER. IBM-PC.
OBJECT-COMPUTER. IBM-PC.

DATA DIVISION.
WORKING-STORAGE SECTION.
01 W01-NUMBERS.
05 W01-NUM1 PIC S999 VALUE 105.
05 W01-NUM2 PIC S999 VALUE -452.

PROCEDURE DIVISION.
0000-MAIN.
DISPLAY 'NUM 1 :' W01-NUM1.

Page 18 of 163
COBOL

DISPLAY 'NUM 2 :' W01-NUM2.


DISPLAY 'W01-NUMBERS :' W01-NUMBERS.
STOP RUN.

Example 2.11

Edited fields
The purpose of editing is to make data more suitable for human reading. Thus editing
in its most common use is associated with printing data on the printer. For example,
we may suppress leading zeros, we may use commas to make long numeric values
more legible, we may insert a dollar sign in front of a value, etc.

The editing characters are Z * $ - + CR DB . , B 0 /

. - (Decimal Point)

The . (decimal) PICTURE character indicates the position of the decimal point and
serves to align the actual decimal values in the field, only one such character may
appear in a field. Further, a field cannot contain both a V and a . PICTURE character.
It cannot be the rightmost character. If all the digits before and after the decimal
point are zero, the resulting field will be blank.

IDENTIFICATION DIVISION.
PROGRAM-ID. CH02EX12.
*******************************************
*Using picture clause . (decimal point) *
*******************************************

ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
SOURCE-COMPUTER. IBM-PC.
OBJECT-COMPUTER. IBM-PC.

DATA DIVISION.
WORKING-STORAGE SECTION.
01 W01-NUMBERS.
05 W01-NUM1 PIC 9999.99 VALUE 2350.22.
05 W01-NUM2 PIC 9999.99 VALUE 150.31.
05 W01-NUM3 PIC 9999.99 VALUE 0.0.

PROCEDURE DIVISION.
0000-MAIN.
DISPLAY 'NUM 1 :' W01-NUM1.
DISPLAY 'NUM 2 :' W01-NUM2.
DISPLAY 'NUM 3 :' W01-NUM3.
STOP RUN.

Example 2.12

Page 19 of 163
COBOL

PIC Description Value Printed as


9999.99 2350.22 2350.22
9999.99 150.31 0150.31
9999.99 0.0 0000.00

Z - Suppressing leading zeros


The Z PICTURE character is used to replace leading zeros by blanks and thus performs
a function identical to that of the floating . Zero suppression terminates when the
first nonzero digit or the . character is encountered, whichever occurs first. When Z’s
have been designated for all positions in a field and the value to be inserted in that
field is zero, in that case the entire field is blanked. Z’s can appear before as well as
after the decimal point. The number of Z’s representing integers in the report-item
should be equal to the number of integers or 9’s in the sending field.

IDENTIFICATION DIVISION.
PROGRAM-ID. CH02EX13.
*************************************************
*Using picture clause Z (zero suppression)
*************************************************

ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
SOURCE-COMPUTER. IBM-PC.
OBJECT-COMPUTER. IBM-PC.

DATA DIVISION.
WORKING-STORAGE SECTION.
01 W01-NUMBERS.
05 W01-NUM1 PIC Z99 VALUE 25.
05 W01-NUM2 PIC Z(03).99 VALUE 25.
05 W01-NUM3 PIC Z(03).99 VALUE 0.10.
05 W01-NUM4 PIC Z(03).ZZ VALUE 0.052.
05 W01-NUM5 PIC Z(03).ZZ VALUE 0.0.

PROCEDURE DIVISION.
0000-MAIN.
DISPLAY 'NUM 1 :' W01-NUM1.
DISPLAY 'NUM 2 :' W01-NUM2.
DISPLAY 'NUM 3 :' W01-NUM3.
DISPLAY 'NUM 4 :' W01-NUM4.
DISPLAY 'NUM 5 :' W01-NUM5.
STOP RUN.

Example 2.13

Page 20 of 163
COBOL

PIC Description Value Printed as


Z99 25 b25
Z(03).99 25 b25.00
Z(03).99 0.10 bbb.10
Z(03).ZZ 0.052 bbb.05
Z(03).ZZ 0.00 bbbbbb

* - Check Protection

The * character is referred to as a check-protect character and is normally used to


protect dollar amounts written on checks or other negotiable documents. Asterisks
are zero-suppression characters that replace each non-significant zero and comma
with * instead of a space.

IDENTIFICATION DIVISION.
PROGRAM-ID. CH02EX14.
*************************************************
*Using picture clause * (check protection) *
*************************************************

ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
SOURCE-COMPUTER. IBM-PC.
OBJECT-COMPUTER. IBM-PC.

DATA DIVISION.
WORKING-STORAGE SECTION.
01 W01-NUMBERS.
05 W01-NUM1 PIC **999 VALUE 4678.
05 W01-NUM2 PIC ***99 VALUE 52.

PROCEDURE DIVISION.
0000-MAIN.
DISPLAY 'NUM 1 :' W01-NUM1.
DISPLAY 'NUM 2 :' W01-NUM2.
STOP RUN.

Example 2.14

PIC Description Value Printed as


**999 04678 *4678
***99 00052 ***52

$ - Dollar Sign

By use of the $ PICTURE character the dollar sign is written in the position in which it
is to appear in the output. Since the $ sign is counted in the size of the field, the field

Page 21 of 163
COBOL

should be assigned at least one more position than the maximum number of
significant digits expected. The $ may also be floated, by which we mean that it will
be entered to the left of the first significant digit in the field and be preceded by
blanks. The $ float stops when wither the first nonzero digit or the . or V is
encountered. When the $ sign appears in all positions and the value is zero, the
effect is to blank the entire field (including any . and ,).

IDENTIFICATION DIVISION.
PROGRAM-ID. CH02EX15.
*************************************************
*Using picture clause $ (dollar sign) *
*************************************************

ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
SOURCE-COMPUTER. IBM-PC.
OBJECT-COMPUTER. IBM-PC.

DATA DIVISION.
WORKING-STORAGE SECTION.
01 W01-NUMBERS.
05 W01-NUM1 PIC $999 VALUE 125.
05 W01-NUM2 PIC $9(05).99 VALUE 100.
05 W01-NUM3 PIC $$99.99 VALUE 12.49.
05 W01-NUM4 PIC $(04)9.99 VALUE 150.10.
05 W01-NUM5 PIC $(04).99 VALUE 0.15.
05 W01-NUM6 PIC $(04).$$ VALUE 0.0.

PROCEDURE DIVISION.
0000-MAIN.
DISPLAY 'NUM 1 :' W01-NUM1.
DISPLAY 'NUM 2 :' W01-NUM2.
DISPLAY 'NUM 3 :' W01-NUM3.
DISPLAY 'NUM 4 :' W01-NUM4.
DISPLAY 'NUM 5 :' W01-NUM5.
DISPLAY 'NUM 6 :' W01-NUM6.
STOP RUN.

Example 2.15
PIC Description Value Printed as
$999.99 125.13 $125.13
$9(05).99 100.00 $00100.00
$$99.99 12.49 b$12.49
$$$$9.99 150.10 $150.10
$$$$.99 0.15 bbb$.15
$$$$.$$ 0.0 bbbbb

, - (Comma)

The comma is placed in the positions in which it is desired. A field may include more
than one , (comma) PICTURE character if the size of the field warrants it. A comma

Page 22 of 163
COBOL

will be appropriately suppressed if no significant digit precedes it. It cannot appear as


the leftmost or rightmost character.

IDENTIFICATION DIVISION.
PROGRAM-ID. CH02EX16.
*************************************************
*Using picture clause , (comma) *
*************************************************

ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
SOURCE-COMPUTER. IBM-PC.
OBJECT-COMPUTER. IBM-PC.

DATA DIVISION.
WORKING-STORAGE SECTION.
01 W01-NUMBERS.
05 W01-NUM1 PIC $9,999.99 VALUE 2350.22.
05 W01-NUM2 PIC $9,999.99 VALUE 150.31.
05 W01-NUM3 PIC $$,999.99 VALUE 150.31.
05 W01-NUM4 PIC $$,$$$.99 VALUE 24.40.
05 W01-NUM5 PIC $$,$$$.999 VALUE 0.019.
05 W01-NUM6 PIC $$,$$$.$$$ VALUE 0.009.
05 W01-NUM7 PIC $$,$$$.$$$ VALUE 0.0.
05 W01-NUM8 PIC $$,$$9.999 VALUE 10.2.

PROCEDURE DIVISION.
0000-MAIN.
DISPLAY 'NUM 1 :' W01-NUM1.
DISPLAY 'NUM 2 :' W01-NUM2.
DISPLAY 'NUM 3 :' W01-NUM3.
DISPLAY 'NUM 4 :' W01-NUM4.
DISPLAY 'NUM 5 :' W01-NUM5.
DISPLAY 'NUM 6 :' W01-NUM6.
DISPLAY 'NUM 7 :' W01-NUM7.
DISPLAY 'NUM 8 :' W01-NUM8.
STOP RUN.

Example 2.16

PIC Description Value Printed as


$9,999.99 2350.22 $2,350.22
$9,999.99 150.31 $0,150.31
$$,999.99 150.31 bb$150.31
$$,$$$.99 24.40 bbb$25.40
$$,$$$.999 0.019 bbbbb$.019

$$,$$$.$$$ 0.009 bbbbb$.009


$$,$$$.$$$ 0.0 bbbbbbbbbb
$$,$$9.999 10.2 bbb$10.200

Page 23 of 163
COBOL

- (Minus) and + (Plus)

The – PICTURE character prints a minus sign only if the quantity is negative and omits
a sign for all other quantities. It can appear as the leftmost or rightmost character.
The – PICTURE insertion character differs from the S character in that the use of the S
character identifies a field as a signed one for computational purposes, but the sign
does not occupy a position. Use of the – PICTURE character leads to a field in which
the sign occupies a character position.

The + PICTURE character is used to print wither a plus sign or a minus sign for all
values. A + sign will be generated for positive or unsigned quantities, and a – sign will
be generated for negative quantities. The sending field should have an $ in its
PICTURE clause for it to be interpreted as a signed number.

The + or – PICTURE character can appear as the leftmost or rightmost character. They
can also be floated, similar to the $ character. However , the +, -, and $ are mutually
exclusive as floating characters. If we want to have both $ float and + or – sign
representation, we write the + or – to the right of the field.

IDENTIFICATION DIVISION.
PROGRAM-ID. CH02EX17.
*************************************************
*Using picture - (minus) and + (plus *
*************************************************

ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
SOURCE-COMPUTER. IBM-PC.
OBJECT-COMPUTER. IBM-PC.

DATA DIVISION.
WORKING-STORAGE SECTION.
01 W01-NUMBERS.
05 W01-NUM1 PIC +999.9 VALUE 35.2.
05 W01-NUM2 PIC 999.9+ VALUE 35.2.
05 W01-NUM3 PIC 999.9+ VALUE -35.2.
05 W01-NUM4 PIC ++9.9 VALUE -1.3.
05 W01-NUM5 PIC +++9.99 VALUE 0.05.
05 W01-NUM6 PIC +++9.99 VALUE -0.05.
05 W01-NUM7 PIC ++++.++ VALUE .01.
05 W01-NUM8 PIC ++++.++ VALUE 0.0.
05 W01-NUM1A PIC -999.9 VALUE 35.2.
05 W01-NUM2A PIC 999.9- VALUE 35.2.
05 W01-NUM3A PIC 999.9- VALUE -35.2.
05 W01-NUM4A PIC --9.9 VALUE -1.3.
05 W01-NUM5A PIC ---9.99 VALUE 0.05.
05 W01-NUM6A PIC ---9.99 VALUE -0.05.
05 W01-NUM7A PIC ----.-- VALUE .01.
05 W01-NUM8A PIC ----.-- VALUE 0.0.

PROCEDURE DIVISION.

Page 24 of 163
COBOL

0000-MAIN.
DISPLAY 'NUM 1 :' W01-NUM1.
DISPLAY 'NUM 2 :' W01-NUM2.
DISPLAY 'NUM 3 :' W01-NUM3.
DISPLAY 'NUM 4 :' W01-NUM4.
DISPLAY 'NUM 5 :' W01-NUM5.
DISPLAY 'NUM 6 :' W01-NUM6.
DISPLAY 'NUM 7 :' W01-NUM7.
DISPLAY 'NUM 8 :' W01-NUM8.
DISPLAY 'NUM 1A :' W01-NUM1A.
DISPLAY 'NUM 2A :' W01-NUM2A.
DISPLAY 'NUM 3A :' W01-NUM3A.
DISPLAY 'NUM 4A :' W01-NUM4A.
DISPLAY 'NUM 5A :' W01-NUM5A.
DISPLAY 'NUM 6A :' W01-NUM6A.
DISPLAY 'NUM 7A :' W01-NUM7A.
DISPLAY 'NUM 8A :' W01-NUM8A.
STOP RUN.

Example 2.17

PIC Description Value Printed as


+999.9 35.2 +035.2
999.9+ 35.2 035.2+
999.9+ -35.2 035.2-
++9.9 -001.3 b-1.3
+++9.99 .05 bb+0.05
+++9.99 -.05 bb-0.05
++++.++ .01 bbb+.01

++++.++ 0.0 bbbbbbb


-999.9 35.2 b035.2
999.9- 35.2 035.2b
999.9- -35.2 035.2-
--9.9 -001.3 b-1.3
---9.99 05 bbb0.05
---9.99 .05 bb-0.05
----.-- 01 bbbb.01

----.-- .0 bbbbbbb

DB/CR

In accounting applications there is often need to identify values that represent debits
or credits. The COBOL language facilitates such differentiation by means of the DB
(debit) and CR (CR) editing characters. The DB or CR symbol is written only to the
right of a field in the PICTURE clause, and in both cases it is represented in storage
for the purpose of subsequent output only when the value is negative.

Page 25 of 163
COBOL

Summary for use of + - DB CR

PIC Storage when Storage when


Character data positive data negative
+ + -
- Blank -
DB Blank DB
CR Blank CR
IDENTIFICATION DIVISION.
PROGRAM-ID. CH02EX18.
*************************************************
*Using picture clause DB/CR *
*************************************************

ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
SOURCE-COMPUTER. IBM-PC.
OBJECT-COMPUTER. IBM-PC.

DATA DIVISION.
WORKING-STORAGE SECTION.
01 W01-NUMBERS.
05 W01-NUM1 PIC $999.99DB VALUE 135.26.
05 W01-NUM2 PIC $999.99DB VALUE -135.26.
05 W01-NUM3 PIC $,$$99.99CR VALUE -10.50.

PROCEDURE DIVISION.
0000-MAIN.
DISPLAY 'NUM 1 :' W01-NUM1.
DISPLAY 'NUM 2 :' W01-NUM2.
DISPLAY 'NUM 3 :' W01-NUM3.
STOP RUN.

Example 2.18

PIC Description Value Printed as


$999.99DB 135.26 $135.26bb
$999.99DB -135.26 $135.26DB
$,$$99.99CR -10.50 bb$10.50CR

B – (blank)

The B insertion editing character results in blanks being entered in the designated
positions.

Page 26 of 163
COBOL

IDENTIFICATION DIVISION.
PROGRAM-ID. CH02EX19.
*************************************************
*Using picture clause B (blank) *
*************************************************

ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
SOURCE-COMPUTER. IBM-PC.
OBJECT-COMPUTER. IBM-PC.

DATA DIVISION.
WORKING-STORAGE SECTION.
01 W01-NAME PIC ABABA(10).

PROCEDURE DIVISION.
0000-MAIN.
MOVE 'RBSMITH' TO W01-NAME.
DISPLAY W01-NAME.
STOP RUN.

Example 2.19
W01-NAME = RbBbSMITHbbbbb

0 - (Zero)

The zero insertion character causes zeros to be inserted in the positions in which it
appears.

IDENTIFICATION DIVISION.
PROGRAM-ID. CH02EX20.
*************************************************
*Using picture clause 0 (zero) *
*************************************************
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
SOURCE-COMPUTER. IBM-PC.
OBJECT-COMPUTER. IBM-PC.

DATA DIVISION.
WORKING-STORAGE SECTION.
01 W01-AMOUNT PIC 9(4)000 VALUE 365.

PROCEDURE DIVISION.
0000-MAIN.
DISPLAY W01-AMOUNT.
STOP RUN.

Example 2.20
W01-AMOUNT = 0365000

Page 27 of 163
COBOL

/ - (stroke)

Each / (stroke) in the PICTURE character string represents a character position into
which the stroke character will be inserted.

IDENTIFICATION DIVISION.
PROGRAM-ID. CH02EX21.
*************************************************
*Using picture clause / (stroke) *
*************************************************

ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
SOURCE-COMPUTER. IBM-PC.
OBJECT-COMPUTER. IBM-PC.

DATA DIVISION.
WORKING-STORAGE SECTION.
01 W01-DATE PIC 99/99/99 VALUE 110601.

PROCEDURE DIVISION.
0000-MAIN.
DISPLAY W01-DATE.
STOP RUN.

Example 2.21
W01-DATE = 11/06/01

USAGE clause

The USAGE clause specifies the manner in which a data item is stored in memory. This
clause can be specified for group as well as for elementary items. If it is specified for
a group item, it applies to each elementary item within the group.

Numeric data in a computer may be represented in one of two basic modes. They may
be represented as character data or as numeric data. The arithmetic registers of
computers perform arithmetic with numeric data that is in numeric, not character
mode. If numeric data is represented in character mode, it must first be converted to
numeric mode before arithmetic computations can be performed.

In COBOL, data in character mode is described in DISPLAY mode, while data in


numeric mode is described as being COMPUTATIONAL MODE. All data items are
assumed to be in DISPLAY mode unless they are declared to be COMPUTATIONAL. The
declaration is done in the DATA DIVISION with the USAGE clause.

The following are the options available with the Usage clause :

Page 28 of 163
COBOL

DISPLAY
COMPUTATIONAL
COMPUTATIONAL-1
COMPUTATIONAL-2
COMPUTATIONAL-3
INDEX

DISPLAY

A DISPLAY data item is stored in memory in the character form where each character
occupies one byte. Non-numeric data items are all considered to be of usage DISPLAY.

02 AMOUNT-1 PIC 99.


02 AMOUNT-2 PIC 99 USAGE DISPLAY.
02 AMOUNT-3 PIC 99 USAGE COMPUTATIONAL.
02 AMOUNT-4 PIC 99 USAGE COMP.

Example 2.22
The usage for W01-AMOUNT-1 is taken as DISPLAY, as no usage is specified. This data
item occupies 2 bytes of memory.

COMPUTATIONAL or (COMP)

This usage is applicable only for numeric data items. The data items are stored in
binary (base 2) form. The item must be an integer (with no decimal point). Depending
on the size of the data item, it is stored either in a half word ( HALF WORD BINARY) or
a full-word (FULL WORD BINARY) of the machine. The maximum size of the picture
clause for half word binary is S9(4) and for full word binary is S9(8). The left-most bit
of a the word is reserved for the sign. Thus, the values of a data item, described by
usage COMPUTATIONAL, should be in the range of -32768 to 32767.

05 W02-BALANCE PIC S9999 USAGE IS COMP.


This item requires only 2 bytes of storage as distinct from 4 bytes, had usage DISPLAY
been specified.

COMPUTATIONAL-2 or (COMP-2)

This is the same as COMP-1 except that two words are used to store a number. Thus,
COMP-2 increases the precision of the number.

COMPUTATIONAL-3 or (COMP-3)

This usage is also applicable only to numeric data items and specifies that the data is
stored in packed decimal form. In packed decimal form, two numeric digits are
packed in one byte. One digit thus occupies one half byte (4 bits) of memory.

Page 29 of 163
COBOL

Memory is allocated only in terms of the whole number of bytes. The sign also
occupies one half byte of memory, even if no “S” appears in the PICTURE clause.
Thus, for any PICTURE clause specifying an even number of 9’s in the data item, only
one half byte of memory will be wasted. The right-most byte of the item contains the
digit and sign of the item.

Note : The picture clause cannot be specified for items with usage COMP-1 or COMP-
2.

SYNCHRONIZED clause

Most computer memories are organized in such a way that there are natural
addressing boundaries such as word boundaries. A word might for example contain 2,
4, 8 or 10 characters. If no special action is taken some data items will start on word
boundaries and some will start part way through a word and perhaps end part way
through another word. Since most computers can process whole words more
efficiently than individual characters there is an overhead in extracting the characters
from the words. Much of this overhead is avoided for data items which have the
SYNCHRONIZED or SYNC clause in their description. It causes the data item to be
aligned on the machine’s natural boundaries. This results in some character positions
being wasted. So the data occupies more space but it can be handled more
efficiently.

REDEFINES Clause

The REDEFINES clause can be used to allow the same storage location to be
referenced by different data-names or to allow a regrouping or different description
of the data in a particular storage location.

Restrictions

The REDEFINES clause cannot be used


- at the 01 level in the FILE SECTION.
- when the levels of data-name-1 and data-name-2 are different.
- When the level number is 66 or 88.

01 SAMPLE.
02 RECEIVABLE.
03 CUSTOMER-NUMBER PIC 9(8).
03 CUSTOMER-NAME PIC X(11).
03 AMOUNT PIC 9(4)V99.
02 PAYABLE REDEFINES RECEIVABLE.
03 VENDOR-NUMBER PIC 9(6).
03 VENDOR-NAME PIC X(12).
03 VENDOR-OWED-AMT PIC 9(5)V99.

Example 2.23

Page 30 of 163
COBOL

RENAMES Clause

The RENAMES clause provides the programmer with the capability of regrouping
elementary data items. It resembles the REDEFINES clause, except that it can form a
new grouping of data items which combines several items. Use of the RENAMES clause
is always signaled by the special 66 level number. Level 66 entry is written in margin
B.

01 TAX-RECORD.
02 SOC-SEC-NUMBER PIC X(9).
02 NAME.
03 FIRST-NAME PIC X(10).
03 LAST-NAME PIC X(15).
02 TOTAL-YTD.
03 GROSS-PAY PIC 9(8)V99.
03 NET-PAY PIC 9(8)V99.
03 TAX PIC 9(5)V99.
66 LAST-GROSS RENAMES LAST-NAME THRU NET-PAY.

Example 2.24
Consider another example of the RENAMES clause. Suppose an interactive program
asks the user : ‘Do you want to ADD, VIEW, or DELETE a record?’ The field in which
the user response is entered is as follows :

01 RESPONSE.
05 CHARS-1-TO-3 PIC XXX.
05 CHAR-4 PIC X.
05 CHARS-5-TO-6 PIC XX.
66 ADD-RESPONSE RENAMES CHARS-1-TO-3.
66 VIEW-RESPONSE RENAMES CHARS-1-TO-3 THRU CHAR-4.
66 DELETE-RESPONSE RENAMES CHARS-1-TO-3 THRU CHARS-5-TO-6.
Example 2.25

The response may be in the first 3, the first 4, or all 6 characters of RESPONSE
depending on whether the viewer responded with ‘ADD’, ‘VIEW’ or ‘DELETE’. The
procedure division statements to check which response was given are as follows :

IF ADD-RESPONSE = ‘ADD’….
IF VIEW-RESPONSE = ‘VIEW’….

This kind of a structure would be particularly useful in subprograms when passing


values of literals as arguments.

Qualification of names

Page 31 of 163
COBOL

A data name that is not unique must be qualified in COBOL verbs.

01 IN-REC
05 NAME PIC X(10).
05 AGE PIC 99.
01 OUT-REC.
05 NAME PIC X(10).
05 B-DATE PIC 9(6).

MOVE NAME OF IN-REC TO NAME OF OUT-REC.

Example 2.26

Page 32 of 163
COBOL

3. ACCEPT/DISPLAY verbs
The PROCEDURE DIVISION contains all the instructions required for processing. It is
divided into various paragraphs or modules. Each module consists of sentences.

The ACCEPT and DISPLAY verbs are used for input and output in conjunction with
storage fields that are not part of any files.

ACCEPT

The instruction ACCEPT identifier enable the user to enter input data directly from a
keyboard.

ACCEPT MY-NAME.

Example 3.1
DISPLAY

DISPLAY can reference a series of identifiers or literals.

DISPLAY MY-NAME.
DISPLAY ‘HELLO’.

Example 3.2
STOP RUN

The verb STOP RUN terminates program execution. A program may contain more than
one STOP RUN statement, depending on the logic of the program. STOP RUN signifies
the logical end of the program.

A program using DISPLAY and ACCEPT.

IDENTIFICATION DIVISION.
PROGRAM-ID. CH03EX03.
****************************************************
* Accept a name from the user. Display a greeting *
* "Hello" followed by the name. *
****************************************************

ENVIRONMENT DIVISION.

Contd.

Page 33 of 163
COBOL

DATA DIVISION.
WORKING-STORAGE SECTION.
01 W01-FIRST-NAME PIC X(15).

PROCEDURE DIVISION.
0000-MAIN.
DISPLAY 'ENTER YOUR NAME : ' WITH NO ADVANCING.
ACCEPT W01-FIRST-NAME.
DISPLAY 'HELLO ' W01-FIRST-NAME.
STOP RUN.

Example 3.3

Page 34 of 163
COBOL

4. MOVE statements
A value can be moved from one storage location to another by the move statement.
Contents of receiving field are changed after the operation.

Verb
Sending
field
Receiving field
MOVE AMT-IN TO AMT-OUT.

The contents of AMT-In will be copied to the second field, AMT-OUT, as a result of the
MOVE operation.

MOVE TOTAL TO PRINT-TOTAL


MOVE ‘INVALID’ TO MESSAGE.
MOVE ZEROS TO TOTAL

Example 4.1

Types of MOVE :

The MOVE statement can be categorized based on the receiving field : numeric MOVEs
and non-numeric MOVEs.

Numeric MOVE

A numeric move is one in which a numeric field or literal is moved to a numeric


receiving field.

When Sending and Receiving fields have the same PIC clauses
If the PIC clauses of both fields are identical, the contents of identifier-2 will be
replaced with the contents of identifier-1 and the sending field will be unchanged.

When Sending and Receiving fields have different PIC clauses

Rule 1 : Moving integer portions of numeric fields

When moving an integer sending field or an integer portion of a numeric sending field
to a numeric receiving field, move, movement is from right to left. All non-filled high-
order (leftmost) integer positions of the receiving field are replaced with zeros.

Page 35 of 163
COBOL

05 AMT-IN PIC 999 VALUE 123.


05 AMT-OUT PIC 9(4) VALUE 4567.

MOVE AMT-IN TO AMT-OUT.

Result :
AMT-OUT = 0123

Example 4.2
Avoiding truncation
In a numeric move, if the receiving field has fewer integer positions than the sending the field,
the most significant digits will be truncated.

05 AMT-IN PIC 999 VALUE 123.


05 AMT-OUT PIC 9(2) VALUE 45.

MOVE AMT-IN TO AMT-OUT.

Result :
AMT-OUT = 23

Example 4.3
Rule 2: Moving decimal portions of numeric fields

When moving a decimal portion of a numeric sending field to the decimal portion of a
numeric receiving field, movement is from left to right, beginning at the implied
decimal point. Low-order (rightmost) non-filled decimal portions of the receiving field
are replaced with zeros.

a.When receiving field has more decimal positions than the sending field

05 AMT-IN PIC 99V99 VALUE 12.34.


05 AMT-OUT PIC 99V999 VALUE 56.789.

MOVE AMT-IN TO AMT-OUT.

Result :
AMT-OUT = 12.340

Example 4.4

Page 36 of 163
COBOL

b. When receiving field has fewer decimal positions than the sending field

05 AMT-IN PIC V99 VALUE.34.


05 AMT-OUT PIC V9 VALUE .5.

MOVE AMT-IN TO AMT-OUT.

Result : AMT-OUT = .3

Example 4.5
Note : The same rules apply to numeric literals moved to numeric fields

Non-numeric MOVE

A non-numeric MOVE operation occurs in the following cases :

1. Moving an alphanumeric or alphabetic field, defined by a PICTURE of X’s or


A’s, to another alphanumeric or alphabetic field.
2. Moving a non-numeric literal to an alphanumeric or alphabetic field.
3. Moving a numeric field or numeric literal to an alphanumeric field or to any
group item.

Rule :

In a non-numeric move, data is transmitted from the sending field to the receiving
field from left to right. Low-order or rightmost positions of the receiving field that
are not replaced with sending field characters are filled with spaces.

a. When receiving field is larger than the sending field

05 NAME-IN PIC XXX VALUE ‘ABC’.


05 NAME-OUT PIC X(5) VALUE ‘DEFGH’.

MOVE NAME-IN TO NAME-OUT.

Result : NAME-OUT = ABCbb

Example 4.6
b. When receiving field is smaller than the sending field

05 NAME-IN PIC XXX VALUE ‘ABC’.


05 NAME-OUT PIC XX VALUE ‘PQ’.

MOVE NAME-IN TO NAME-OUT.

Result : NAME-OUT = AB

Example 4.7

Page 37 of 163
COBOL

c. When the sending field is numeric integer and the receiving field is non-
numeric

05 NAME-IN PIC 999 VALUE 321


05 NAME-OUT PIC X(5) VALUE ‘DEFGH’.

MOVE NAME-IN TO NAME-OUT.

Result :
NAME-OUT = 321bb

Example 4.8

d. When the sending field is a non-numeric literal

05 NAME-OUT PIC X(5) VALUE ‘DEFGH’.

MOVE ‘XYZ’ TO NAME-OUT.

Result :
NAME-OUT = XYZbb

Example 4.9

e. When the sending field is a figurative constant

05 NAME-OUT PIC X(5) VALUE ‘DEFGH’.

MOVE SPACES TO NAME-OUT.

Result :
NAME-OUT = bbbbb

Example 4.10

A group move is considered a non-numeric move

All group items, even those with numeric subfields, are treated as alphanumeric
fields.

Page 38 of 163
COBOL

05 DATE-OUT.
10 MONTH-OUT PIC 99 .
10 YEAR-OUT PIC 99.

a. MOVE 1 TO MONTH-OUT.MOVE 94 TO YEAR-OUT.

Result :
DATE-OUT = 0194

b. MOVE 194 TO DATE-OUT.

Result : DATE-OUT = 194b

Example 4.11

Moving part of the field


The following program code show how you can move part of a field. The code below moves 2
characters starting from the 2nd character of the field W01-NAME-IN.

IDENTIFICATION DIVISION.
PROGRAM-ID. SUB.
ENVIRONMENT DIVISION.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 W01-NAME-IN PIC X(10) VALUE "PATNI".
01 W01-NAME-OUT PIC X(10).
01 TEMP PIC X.

PROCEDURE DIVISION.
0000-MAIN.
MOVE W01-NAME-IN(2:2) TO W01-NAME-OUT.
DISPLAY W01-NAME-OUT.
ACCEPT TEMP.
STOP RUN.

Permissible MOVE operations

Sending Field Receiving Field


Numeric Alphabetic Alphanumeric Group item
Numeric √ x √* √
Alphabetic X √ √ √
Alphanumeric x √ √ √
ZEROS √ x √ √
SPACES x √ √ √
Group item x √ √ √
* Numeric integer fields can be moved to alphanumeric fields but numeric fields
with a V in the PIC clause cannot be moved to alphanumeric fields.

Page 39 of 163
COBOL

The MOVE CORRESPONDING statement

In the MOVE CORRESPONDING statement, all elementary items within the sending
group-item that have the same names as corresponding elementary items in the
receiving group-item will be moved. The same-named fields in the receiving group-
item need not be in any specific order. Any fields of the sending record, that are not
matched by the same-named fields in the receiving record are ignored.

MOVE CORRESPONDING WORKER-REC TO EMP-REC.

The values of items in the group item WORKER-REC are moved to corresponding items
in the group item EMP-REC.

Page 40 of 163
COBOL

5. Arithmetic verbs
All the basic arithmetic operations of ADD, SUBTRACT, MULTIPLY, and DIVIDE require
that the fields operated on (1) have numeric PIC clauses and (2) actually have
numeric data when the program is executed.

In all cases, the resultant field must be an identifier or data-name, not a literal.

ADD statement

The result, or sum, of an ADD operation is always placed in the last field mentioned.
The only field that is altered as a result of the ADD operation is this last field, which
is the one directly following the word TO.

When using the TO format in an ADD statement, all the data-names and literals are
added together, and the result placed in the last field specified.

When using the GIVING format, all fields and literals preceding the word GIVING are
added together and the sum is placed in the field following the word GIVING.

05 EMP-BASIC PIC 9(5) VALUE 4000.


05 EMP-HRA PIC 9(3) VALUE 650.
05 EMP-TOTAL PIC 9(6) VALUE 100.

a. ADD EMP-BASIC TO EMP-TOTAL.

Result :
EMP-TOTAL = 4100

b. ADD EMP-BASIC EMP-HRA GIVING EMP-TOTAL.

Result :
EMP-TOTAL = 4650

Example 5.1

Page 41 of 163
COBOL

IDENTIFICATION DIVISION.
PROGRAM-ID. CH05EX02.
***************************************************************
* This program accepts 2 numbers from the user and displays *
* the sum of the numbers. *
***************************************************************

ENVIRONMENT DIVISION.

DATA DIVISION.
WORKING-STORAGE SECTION.
01 W01-NOS.
05 W01-NO-1 PIC 9(02).
05 W01-NO-2 PIC 9(02).
05 W01-TOT PIC 9(03) VALUE ZEROES.

PROCEDURE DIVISION.
0000-MAIN.
DISPLAY 'ENTER THE FIRST NO. : ' WITH NO ADVANCING.
ACCEPT W01-NO-1.
DISPLAY 'ENTER THE SECOND NO. : ' WITH NO ADVANCING.
ACCEPT W01-NO-2.
ADD W01-NO-1 W01-NO-2 GIVING W01-TOT.
DISPLAY 'THE SUM OF ' W01-NO-1 ' AND '
W01-NO-2 ' IS ' W01-TOT.
STOP RUN.

Example 5.2

SUBTRACT statement
All fields and literals preceding the word FROM will be added together and the sum
subtracted from the field following the word FROM. The result, or difference, will be
placed in this same field if no GIVING option is used. All other fields will remain
unchanged.

Page 42 of 163
COBOL

05 EMP-GROSS PIC 9(5) VALUE 4250.


05 EMP-PF PIC 9(3) VALUE 250.
05 EMP-ITAX PIC 9(3) VALUE 100.
05 EMP-NET PIC 9(6) VALUE 100.

a. SUBTRACT EMP-PF FROM EMP-GROSS.

Result :
EMP-BASIC = 4000

b. SUBTRACT EMP-PF EMP-ITAX FROM EMP-GROSS.

Result :
EMP-GROSS = 3900

SUBTRACT EMP-PF EMP-ITAX FROM EMP-GROSS GIVING EMP-NET.

Result :
EMP-GROSS = 4250
EMP-NET = 3900

Example 5.3

MULTIPLY and DIVIDE statements

With each MULTIPLY or DIVIDE statement specified, only two operands can be
multiplied or divided. Always make sure the receiving fields is large enough to store
the result. The preposition used with the MULTIPLY verb is always BY. In the DIVIDE
operation, the preposition is either BY or INTO.

Page 43 of 163
COBOL

05 EMP-GROSS PIC 9(5) VALUE 4000.


05 EMP-ANN-SAL PIC 9(5) VALUE ZERO.
05 EMP-NEW-SAL PIC 9(5) .
05 EMP-REM PIC 9(3).

a. MULTIPLY 12 BY EMP-GROSS.
Result :
EMP-GROSS = 48000

b. MULTIPLY EMP-GROSS BY 12 GIVING EMP-ANN-SAL.


Result :
EMP-GROSS = 4000
EMP-ANN-SAL=48000

c. DIVIDE 4 INTO EMP-GROSS.


Result :
EMP-GROSS = 1000

d. DIVIDE 4 INTO EMP-GROSS GIVING EMP-NEW-SAL.


Result :
EMP-GROSS = 4000
EMP-NEW-SAL = 1000

e. DIVIDE EMP-GROSS BY 4 GIVING EMP-NEW-SAL.


Result :
EMP-NEW-SAL = 1000
Example 5.4

Use of the REMAINDER clause in the DIVIDE operation


When performing a division operation, the result will be placed in the receiving field
according to the PIC specifications of that field.

DIVIDE 130 BY 40 GIVING WS-TOTAL.

Example 5.5

After the operation is performed, 03 is placed in WS-TOTAL.

It is sometimes useful to store the remainder of a division operation for additional


processing. The DIVIDE can be used for this purpose by including a REMAINDER clause.

Page 44 of 163
COBOL

IDENTIFICATION DIVISION.
PROGRAM-ID. CH05EX06.
***************************************************************
* This program accepts the basic pay from the user. Display *
* basic pay(per day). Display the remainder if any. *
***************************************************************

ENVIRONMENT DIVISION.

DATA DIVISION.
WORKING-STORAGE SECTION.
01 W01-NOS.
05 W01-BASIC-PAY PIC 9(05).
05 W01-PER-DAY PIC 9(04).
05 W01-REM PIC 9(04).

PROCEDURE DIVISION.
0000-MAIN.
DISPLAY 'ENTER THE BASIC PAY : ' WITH NO ADVANCING.
ACCEPT W01-BASIC-PAY.

DIVIDE W01-BASIC-PAY BY 30
GIVING W01-PER-DAY
REMAINDER W01-REM.

DISPLAY 'THE PER DAY BASIC IS - ' W01-PER-DAY.


DISPLAY 'THE REMAINDER IS - ' W01-REM.
STOP RUN.

Example 5.6

ROUNDED Option

A frequent need exists for rounding numeric values. COBOL provides automatic
rounding by use of the ROUNDED clause, which can be used with all arithmetic verbs.

Page 45 of 163
COBOL

IDENTIFICATION DIVISION.
PROGRAM-ID. CH05EX07.
***************************************************************
* This program accepts 2 numbers from the user and displays *
* the sum of the numbers. *
***************************************************************

ENVIRONMENT DIVISION.

DATA DIVISION.
WORKING-STORAGE SECTION.
01 W01-NOS.
05 W01-NO-1 PIC 9(02)V999.
05 W01-NO-2 PIC 9(02)V999.

01 W02-PRT-NOS.
05 W02-PRT-NO1 PIC 9(02).999.
05 W02-PRT-NO2 PIC 9(02).999.
05 W02-PRT-TOT PIC 9(03).99.

PROCEDURE DIVISION.
0000-MAIN.
DISPLAY 'ENTER THE FIRST NO. : ' WITH NO ADVANCING.
ACCEPT W01-NO-1.
DISPLAY 'ENTER THE SECOND NO. : ' WITH NO ADVANCING.
ACCEPT W01-NO-2.
ADD W01-NO-1 W01-NO-2 GIVING W02-PRT-TOT.

MOVE W01-NO-1 TO W02-PRT-NO1.


MOVE W01-NO-2 TO W02-PRT-NO2.

DISPLAY 'THE SUM OF ' W02-PRT-NO1 ' AND '


W02-PRT-NO2 ' IS ' W02-PRT-TOT.
STOP RUN.

1000-ERROR.
DISPLAY 'SIZE ERROR'.

1000-EXIT.
EXIT.

Example 5.7

Page 46 of 163
COBOL

Sample data
W01-NO-1 W01-NO-2 W02-PRT-TOT
12.857 25.142 37.99
10.33 35.20 45.53
8.515 43.223 51.73

In the code given above, if 12.857 and 25.142 are entered, the result 37.999 is placed
in an accumulator. When this value is move to the field W02-PRT-TOT, the low-order
decimal position is truncated and 37.99 is stored in the field. A more desirable result
would be 38.00 since, 38 is closer to the sum of 37.999. We consider results more
accurate if they are rounded to the nearest decimal position.

To obtain rounded results, the ROUNDED option may be specified with any arithmetic
statement. In all case, it directly follows the resultant data-name.

IDENTIFICATION DIVISION.
PROGRAM-ID. CH05EX08.
***************************************************************
* This program accepts 2 numbers from the user and displays *
* the sum of the numbers(Using ROUNDED). *
***************************************************************

ENVIRONMENT DIVISION.

DATA DIVISION.
WORKING-STORAGE SECTION.
01 W01-NOS.
05 W01-NO-1 PIC 9(02)V999.
05 W01-NO-2 PIC 9(02)V999.

01 W02-PRT-NOS.
05 W02-PRT-NO1 PIC 9(02).999.
05 W02-PRT-NO2 PIC 9(02).999.
05 W02-PRT-TOT PIC 9(03).99.

PROCEDURE DIVISION.
0000-MAIN.
DISPLAY 'ENTER THE FIRST NO. : ' WITH NO ADVANCING.
ACCEPT W01-NO-1.
DISPLAY 'ENTER THE SECOND NO. : ' WITH NO ADVANCING.
ACCEPT W01-NO-2.
ADD W01-NO-1 W01-NO-2 GIVING W02-PRT-TOT ROUNDED.
Contd.

Page 47 of 163
COBOL

MOVE W01-NO-1 TO W02-PRT-NO1.


MOVE W01-NO-2 TO W02-PRT-NO2.

DISPLAY 'THE SUM OF ' W02-PRT-NO1 ' AND '


W02-PRT-NO2 ' IS ' W02-PRT-TOT.
STOP RUN.

1000-ERROR.
DISPLAY 'SIZE ERROR'.

1000-EXIT.
EXIT.

Example 5.8
If the ROUNDED option is not specified, truncation of decimal positions will occur if
the resultant field cannot accommodate all the decimal positions in the result. With
the ROUNDED option, the computer will always round the result to the PICTURE
specification of the receiving field.

If ROUNDED and REMAINDER are to be used in the same DIVIDE statement, ROUNDED
must appear first.

DIVIDE Z BY 12.2 GIVING Y ROUNDED REMAINDER X

ON SIZE ERROR
Consider the following :

IDENTIFICATION DIVISION.
PROGRAM-ID. CH05EX09.
***************************************************************
* This program accepts 2 numbers from the user and displays *
* the sum of the numbers. *
***************************************************************

ENVIRONMENT DIVISION.

DATA DIVISION.
WORKING-STORAGE SECTION.
01 W01-NOS.
05 W01-NO-1 PIC 9(02).
05 W01-NO-2 PIC 9(02).
05 W01-TOT PIC 9(02) VALUE ZEROES.
Contd.

Page 48 of 163
COBOL

PROCEDURE DIVISION.
0000-MAIN.
DISPLAY 'ENTER THE FIRST NO. : ' WITH NO ADVANCING.
ACCEPT W01-NO-1.
DISPLAY 'ENTER THE SECOND NO. : ' WITH NO ADVANCING.
ACCEPT W01-NO-2.
ADD W01-NO-1 W01-NO-2 GIVING W01-TOT.

DISPLAY 'THE SUM OF ' W01-NO-1 ' AND '


W01-NO-2 ' IS ' W01-TOT.
STOP RUN.

Example 5.9

If 80 and 35 are entered in the above program, the effect of the ADD statement would
be the same as coding MOVE 115 TO W01-TOT. In this case, the resultant field is not
large enough to store the accumulated sum. In other words , an overflow or size error
condition has occurred. This will produce erroneous results.

In the above program, the leading digits would be truncated. Hence, the contents of
W01-TOT would be 15.

IDENTIFICATION DIVISION.
PROGRAM-ID. CH05EX10.
***************************************************************
* This program accepts 2 numbers from the user and displays *
* the sum of the numbers. (Using ON SIZE ERROR ) *
***************************************************************

ENVIRONMENT DIVISION.

DATA DIVISION.
WORKING-STORAGE SECTION.
01 W01-NOS.
05 W01-NO-1 PIC 9(02).
05 W01-NO-2 PIC 9(02).
05 W01-TOT PIC 9(02) VALUE ZEROES.

PROCEDURE DIVISION.
0000-MAIN.
DISPLAY 'ENTER THE FIRST NO. : ' WITH NO ADVANCING.
ACCEPT W01-NO-1.
DISPLAY 'ENTER THE SECOND NO. : ' WITH NO ADVANCING.
ACCEPT W01-NO-2.
ADD W01-NO-1 TO W01-NO-2 GIVING W01-TOT
Contd.

Page 49 of 163
COBOL

ON SIZE ERROR
PERFORM 1000-ERROR THRU 1000-EXIT.
DISPLAY 'THE SUM OF ' W01-NO-1 ' AND '
W01-NO-2 ' IS ' W01-TOT.
STOP RUN.

1000-ERROR.
DISPLAY 'SIZE ERROR'.

1000-EXIT.
EXIT.

Example 5.10
In the above program, in case of a size error condition, the erroneous value is not
moved to the resultant field i.e. the original contents of W01-TOT is retained.

In a divide, the size error condition has additional significance. If an attempt is made
to divide by zero, a size error condition will occur. This is because division by zero
yields a result of infinity, which makes it impossible to define a sufficiently large
receiving field.

If the ON SIZE ERROR option is employed along with the ROUNDED option, the word
ROUNDED always precedes ON SIZE ERROR.

COMPUTE statement

If complex or extensive arithmetic operations are required in a program, the use of


the four arithmetic verbs may prove cumbersome. The COMPUTE verb provides
another method of performing arithmetic. The COMPUTE statement uses the following
arithmetic symbols :

+ Add
- Subtract
* Multiply
/ Divide
** exponentiation

COMPUTE TOTAL = AMT1 + AMT2 – AMT3.


Example 5.11

To round the results in a COMPUTE statement to the specifications of the receiving


field, use the ROUNDED option directly following the receiving field.

COMPUTE Y ROUNDED = Z/12.2

Page 50 of 163
COBOL

In the above example, value of Y is 003^28 if the picture clause of Z is 999 and the
value of Z is 040.

Note : “^” in 00328 shows the implied decimal point.

If we need to test for a size error condition we may use the ON SIZE ERROR clause as
the last one in the statement.

COMPUTE Y ROUNDED = Z/12.2 ON SIZE ERROR PERFORM ERR-PARA.

The sequence in which operations are performed in a COMPUTE statement

**
* or / (whichever appears first from left to right)
+ or - (whichever appears first from left to right)
The use of parentheses overrides rules 1-3. That is, operations with parentheses are
performed first.

The following program calculates the simple interest for a principal amount of 1000.
The period (in years) and rate of interest is accepted from the user.

IDENTIFICATION DIVISION.
PROGRAM-ID. INTCOMP.
ENVIRONMENT DIVISION.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 W01-VARS.
05 W01-PRINCIPAL PIC 9999 VALUE 1000.
05 W01-YEARS PIC 99.
05 W01-RATE PIC 99V99.
05 W01-INT PIC 999.
05 W01-TEMP PIC X.

PROCEDURE DIVISION.
0000-MAIN.
DISPLAY "ENTER RATE OF INTEREST ".
ACCEPT W01-RATE.
DISPLAY "ENTER NO. OF YEARS ".
ACCEPT W01-YEARS.

COMPUTE W01-INT rounded =


(W01-PRINCIPAL * W01-YEARS * W01-RATE) / 100
ON SIZE ERROR MOVE 100 TO W01-INT.

DISPLAY "INTEREST : " W01-INT.


ACCEPT W01-TEMP.
STOP RUN.

Page 51 of 163
COBOL

The output for varying input values is given below :

Rate of No. of years Interest Interest Remarks


interest amount amount as per
compute verb
9 5 450.00 450
9.25 5 462.50 463 Effect of
rounding
9.25 15 1387.50 100 Effect of on
size error

Page 52 of 163
COBOL

6. Decision Making
A conditional statement is one that performs operations depending on the existence
of some condition. In COBOL, such statements generally begin with the word IF and
are called IF-THEN-ELSE or selection structures.

An imperative statement , as opposed to a conditional statement, is one that


performs an operation regardless of any existing condition.
A condition may test for a specific relation. A simple condition may be a single
relational test of the following form :

IDENTIFICATION DIVISION.
PROGRAM-ID. CH06EX01.
***************************************************************
* This program accepts 2 numbers from the user and displays *
* the maximum. If both the numbers are equal, it displays the *
* message 'EQUAL'. *
***************************************************************
ENVIRONMENT DIVISION.

DATA DIVISION.
WORKING-STORAGE SECTION.
01 W01-NOS.
05 W01-NO-1 PIC 9(02).
05 W01-NO-2 PIC 9(02).

PROCEDURE DIVISION.
0000-MAIN.
PERFORM 1000-ACPT-DATA THRU 1000-EXIT.
PERFORM 2000-COMPARE THRU 2000-EXIT.
STOP RUN.

1000-ACPT-DATA.
DISPLAY 'ENTER THE FIRST NO. : ' WITH NO ADVANCING.
ACCEPT W01-NO-1.
DISPLAY 'ENTER THE SECOND NO. : ' WITH NO ADVANCING.
ACCEPT W01-NO-2.

1000-EXIT.
EXIT.

2000-COMPARE.
IF W01-NO-1 = W01-NO-2
DISPLAY 'EQUAL'
ELSE
IF W01-NO-1 > W01-NO-2
DISPLAY W01-NO-1 ' IS GREATER'
ELSE
DISPLAY W01-NO-2 ' IS GREATER'.
2000-EXIT.
EXIT.

Example 6.1

Page 53 of 163
COBOL

The following symbols for simple relational conditions are valid within a COBOL
statement :
< IS LESS THAN
> IS GREATER THAN
= IS EQUAL TO

The NEXT SENTENCE or CONTINUE clause


There are times when you might want to execute a series of steps only if a certain
condition does not exist. The COBOL expression NEXT SENTENCE will enable you (1) to
avoid performing any operation if a condition exists and (2) to execute instructions
only if the ELSE condition is met, (3) to associate an ELSE with the proper IF. If NEXT
SENTENCE is coded, it must be the only imperative statement following the condition.

IF AMT1 = AMT2
NEXT SENTENCE
ELSE
ADD 1 TO TOTAL.

In the code above, if AMT1 is equal to AMT2, no operation will be performed and the
computer will continue execution with the next sentence, which follows the period. If
AMT1 is not equal to AMT2, 1 is added to TOTAL and the next sentence will be
executed.

Page 54 of 163
COBOL

Shown below is the flowchart for a sample Nested Structure

T
F Good
risk

F T
Quant
> 1000

Move low-rate to Move high-rate


discount to discount

Perform
Gross

Perform Net

Perform
Invoice

Page 55 of 163
COBOL

The above flowchart in code would be as follows :

IF GOOD-RISK
IF QUANT > 1000
MOVE HIGH-RATE TO DISCOUNT
PERFORM GROSS
PERFORM NET
ELSE
MOVE LOW-RATE TO DISCOUNT
PERFORM GROSS
PERFORM NET
ELSE
PERFORM BAD-RISK.
PERFORM INVOICE.

Shown below is a sample program that uses NEXT SENTENCE.

IDENTIFICATION DIVISION.
PROGRAM-ID. CH06EX02.
***************************************************************
* This program accepts the invoice no, customer code, invoice *
* amount from the user and calculates the payable amount. *
* Discount is 3% of the amount for amounts exceeding 5000. Tax*
* 1% of the amount except for customer codes 'X','P'. *
***************************************************************
ENVIRONMENT DIVISION.

DATA DIVISION.
WORKING-STORAGE SECTION.
01 W01-INVOICE-REC.
05 W01-INV-NO PIC 9(04).
05 W01-CUST-CODE PIC X(01).
05 W01-INV-AMOUNT PIC 9(05).
05 W01-AMT-PAYABLE PIC 9(05).

01 W02-OTHERS.
05 W02-DISCOUNT PIC 9(03) VALUE ZEROS.
05 W02-TAX PIC 9(03) VALUE ZEROS.

PROCEDURE DIVISION.
0000-MAIN.
PERFORM 1000-ACPT-DATA THRU 1000-EXIT.
PERFORM 2000-CALCULATE THRU 2000-EXIT.
PERFORM 3000-DISPLAY THRU 3000-EXIT.
STOP RUN.

1000-ACPT-DATA.
DISPLAY 'ENTER THE INVOICE NO. : ' WITH NO ADVANCING.
ACCEPT W01-INV-NO.

Page 56 of 163
COBOL

DISPLAY 'ENTER THE CUSTOMER CODE : ' WITH NO ADVANCING.


ACCEPT W01-CUST-CODE.
DISPLAY 'ENTER THE INVOICE AMOUNT : ' WITH NO ADVANCING.
ACCEPT W01-INV-AMOUNT.

1000-EXIT.
EXIT.

2000-CALCULATE.
IF W01-INV-AMOUNT > 5000
MULTIPLY W01-INV-AMOUNT BY 0.03
GIVING W02-DISCOUNT ROUNDED.

IF W01-CUST-CODE = 'X' OR W01-CUST-CODE = 'P'


NEXT SENTENCE
ELSE
MULTIPLY W01-INV-AMOUNT BY 0.01
GIVING W02-TAX.

COMPUTE W01-AMT-PAYABLE =
W01-INV-AMOUNT - (W02-DISCOUNT + W02-TAX).

2000-EXIT.
EXIT.

3000-DISPLAY.
DISPLAY 'DISCOUNT : ' W02-DISCOUNT.
DISPLAY 'TAX : ' W02-TAX.
DISPLAY 'AMOUNT PAYABLE : ' W01-AMT-PAYABLE.

3000-EXIT.
EXIT.

Example 6.2

Compound conditional
The compound conditional offers even greater flexibility for selection and enables the
IF statement to be used for more complex problems. The compound conditionals are
as follows :

OR

Performs an operation or a series of operations if any one of several conditions


exists.

AND
If a statement or statements are to be executed only when all of several conditions
are met.

Page 57 of 163
COBOL

Negating conditionals

NOT

All simple relation, class or sign tests may be coded using a negated conditional
(NOT).

IF AMT1 IS NOT EQUAL TO AMT2


PERFORM 200-NOT-EQUAL-RTN.

Example 6.3

Hierarchy rules for compound conditionals

1. NOT is evaluated first.


2. Conditions surrounding the word AND are evaluated first.
3. Conditions surrounding the word OR are evaluated last.
4. When there are several AND or OR connectors, the AND conditions are
evaluated first, as they appear in the statement, from left to right. Then the
OR conditions are evaluated, also from left to right.
5. To override Rules 1-3, use parentheses around conditions you want to be
evaluated first.

Negating Compound Conditionals


Negating compound conditionals can cause a logic error. The following example will
explain the error and how it can be avoided :

The following is a routine to perform 200-MARRIED-RTN if MARITAL-CODE is not equal


to ‘S’ (single) or ‘D’ (divorced); otherwise 100-UNMARRIED-RTN is performed :

IF MARITAL-CODE IS EQUAL TO ‘S’


OR MARITAL-CODE IS EQUAL TO ‘D’
PERFORM 100-UNMARRIED-RTN
ELSE
PERFORM 200-MARRIED-RTN.

Example 6.4 (a)

But suppose we want to use negated conditionals. On first thought, you may decide
simply to negate each simple condition :

Page 58 of 163
COBOL

IF MARITAL-CODE IS NOT EQUAL TO ‘S’


OR MARITAL-CODE IS NOT EQUAL TO ‘D’
PERFORM 200-MARRIED-RTN
ELSE
PERFORM 100-UNMARRIED-RTN.

Example 6.4 (b)

An evaluation of this statement will show that the preceding is not correct. As coded,
one of two conditions must exist for 200-MARRIED-RTN to be executed:

a. MARITAL-CODE IS NOT EQUAL TO ‘S’


OR b. MARITAL-CODE IS NOT EQUAL TO ‘D’

Suppose MARITAL-CODE is ‘M’ (for married); 200-MARRIED-RTN will be executed,


which is what we want. If MARITAL-CODE is ‘S’, however, we wish 100-UNMARRIED-
RTN to be executed. In the preceding conditional, condition (a) is not met since
MARITAL-CODE DOES NOT EQUAL ‘s’. however, condition (b) is met since MARITAL-
CODE is not equal to ‘D’, but is equal to ‘S’. Only one condition needs to be satisfied
for 200-MARRIED-RTN to be executed, and since condition (b) is satisfied, 200-
MARRIED-RTN to be executed instead of 100-unmarried-rtn, which is really the
procedure we should execute.

Similarly, suppose MARITAL-CODE is ‘D’. We want 100-UNMARRIED-RTN to be


executed, but note again that 200-MARRIED-RTN is executed. Condition (a) is
satisfied, because MARITAL-CODE is not equal to ‘S’ (it is equal to ‘D’). Since only one
condition needs to be satisfied, 200-MARRIED-RTN is executed. In fact, you can now
see that the sentence as coded will always cause 200-MARRIED-RTN to be executed,
regardless of the contents of MARITAL-CODE.

When negating conditions separated by OR : IF NOT (CONDITION1 OR CONDITION2…),


the stated conditions become : IF NOT CONDITION1 AND NOT CONDITION2 AND ….
Hence, the IF statement could be coded as IF NOT (MARITAL-CODE = ‘S’ OR MARITAL-
CODE = ‘D’) or as :

IF MARITAL-CODE IS NOT EQUAL TO ‘S’


AND MARITAL-CODE IS NOT EQUAL TO ‘D’
PERFORM 200-MARRIED-RTN
ELSE
PERFORM 100-UNMARRIED-RTN.

Example 6.4 (c)

Page 59 of 163
COBOL

Sign test

We can test whether a field is POSITIVE, NEGATIVE, or ZERO with a sign test.
If a numeric field contains an amount less than zero, it is considered negative. If it
has an amount greater than zero, then it is considered positive.

IF AMT IS POSITIVE
PERFORM 200-CALC-RTN.

Ex 6.4 (d)

Class test
We can test for the type of data (ALPHABETIC or NUMERIC) using the class test.
IF AMT-IN IS NUMERIC
PERFORM 300-CALC-RTN.

Ex 6.4 (e)
IDENTIFICATION DIVISION.
PROGRAM-ID. CLSCHK.
ENVIRONMENT DIVISION.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 W01-NUM.
05 W01-NUM1 PIC 99.
05 W01-NUM2 REDEFINES W01-NUM1 PIC XX.

01 W02-TEMP PIC X.

PROCEDURE DIVISION.
0000-MAIN.
DISPLAY "ENTER THE MARKS : ".
ACCEPT W01-NUM2.
IF W01-NUM1 IS NOT NUMERIC
DISPLAY "ONLY NUMBERS SHOULD HAVE BEEN ENTERED".
ACCEPT W02-TEMP.
STOP RUN.
Example 6.5

Condition names
A condition-name is a user-defined word established in the DATA DIVISION that gives a
name to a specific value that an identifier can assume. An 88-level coded in the DATA
DIVISION is a condition-name that denotes a possible value for an identifier. A
condition-name is always coded on the 88 level and has only a VALUE clause
associated with it. Since a condition-name is not the name of a field, it will not
contain a PICTURE clause.

Page 60 of 163
COBOL

05 MARITAL-STATUS PIC X.
88 SINGLE VALUE ‘S’.

Example 6.6
Either of the following tests may be used in the PROCEDURE DIVISION .

IF MARITAL-STATUS = ‘S’
PERFORM 1000-SINGLE-ROUTINE.

Example 6.6a:
or

IF SINGLE
PERFORM 1000-SINGLE-ROUTINE.

Example 6.6b

IDENTIFICATION DIVISION.
PROGRAM-ID. CH06EX07.
***************************************************************
* This program accepts the sexcode, age, place, and health *
* code from the user and calculates the insurance amount. *
* Display an error message for rejected customers. *
* SEXCODE AGE HEALTH CODE PLACE AMOUNT *
* ------- ---- ----------- ------ ------- *
* (M)ale 20-45 (G)ood (C)ity 1,25,000 *
* (M)ale 20-50 (G)ood (V)illage 1,50,000 *
* (M)ale 25-35 (P)oor (V)illage 25,000 *
* (F)emale 22-40 (G)ood (C)ity 1,00,000 *
* (F)emale 20-45 (G)ood (V)illage 1,25,000 *
***************************************************************
ENVIRONMENT DIVISION.

DATA DIVISION.
WORKING-STORAGE SECTION.
01 W01-INS-REC.
05 W01-SEX-CODE PIC A(01).
88 88-MALE VALUE 'M'.
88 88-FEMALE VALUE 'F'.
05 W01-AGE PIC 9(02).
88 88-20-TO-45 VALUE 20 THRU 45.
88 88-20-TO-50 VALUE 20 THRU 50.
88 88-25-TO-35 VALUE 25 THRU 35.
88 88-22-TO-40 VALUE 22 THRU 40.
05 W01-PLACE PIC A(01).
88 88-CITY VALUE 'C'.
88 88-VILLAGE VALUE 'V'.
05 W01-HEALTH-CODE PIC A(01).
88 88-GOOD-HEALTH VALUE 'G'.
88 88-POOR-HEALTH VALUE 'P'.
05 W01-INS-AMOUNT PIC 9(06) VALUE ZEROS.

Page 61 of 163
COBOL

PROCEDURE DIVISION.
0000-MAIN.
PERFORM 1000-ACPT-DATA THRU 1000-EXIT.
PERFORM 2000-CHECK THRU 2000-EXIT.
PERFORM 3000-DISPLAY THRU 3000-EXIT.
STOP RUN.

1000-ACPT-DATA.
DISPLAY 'ENTER THE SEXCODE : ' WITH NO ADVANCING.

ACCEPT W01-SEX-CODE.
DISPLAY 'ENTER THE AGE : ' WITH NO ADVANCING.
ACCEPT W01-AGE.
DISPLAY 'ENTER THE PLACE : ' WITH NO ADVANCING.
ACCEPT W01-PLACE.
DISPLAY 'ENTER THE HEALTH CODE : ' WITH NO ADVANCING.
ACCEPT W01-HEALTH-CODE.

1000-EXIT.
EXIT.

2000-CHECK.
IF 88-MALE
PERFORM 2100-MALE THRU 2100-EXIT
ELSE
PERFORM 2200-FEMALE THRU 2200-EXIT.

2000-EXIT.
EXIT.

2100-MALE.

IF 88-GOOD-HEALTH
IF 88-20-TO-45 AND 88-CITY
MOVE 125000 TO W01-INS-AMOUNT
ELSE
IF 88-20-TO-50 AND 88-VILLAGE
MOVE 15000 TO W01-INS-AMOUNT
ELSE
NEXT SENTENCE
ELSE
IF 88-POOR-HEALTH
IF 88-20-TO-45 AND 88-VILLAGE
MOVE 25000 TO W01-INS-AMOUNT.

2100-EXIT.
EXIT.

Page 62 of 163
COBOL

2200-FEMALE.
IF 88-GOOD-HEALTH
IF 88-22-TO-40 AND 88-CITY
MOVE 100000 TO W01-INS-AMOUNT
ELSE
IF 88-20-TO-45 AND 88-VILLAGE
MOVE 125000 TO W01-INS-AMOUNT.

2200-EXIT.
EXIT.

3000-DISPLAY.
IF W01-INS-AMOUNT = ZEROS
DISPLAY 'CUSTOMER REJECTED'
ELSE
DISPLAY 'INSURANCE AMOUNT : ' W01-INS-AMOUNT.

3000-EXIT.
EXIT.

Example 6.7

Nested IF
The program given below calculates the Grade based on the attendance and marks
entered. The criteria for calculating the grade is as follows :
Attendance –100 and Marks > 50 ---------- PASS
Attendance – 100 and Marks <= 50 --------- ZZ
Attendance <> 100 ---------- FAIL

Try out the following code and not your findings for the given input values.

Attendance Marks Grade


100 60
80 60
100 40

IDENTIFICATION DIVISION.
PROGRAM-ID. NESTEDIF.
ENVIRONMENT DIVISION.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 W01-DETAILS.
05 W01-ATTD PIC 9(03).
05 W01-MARKS PIC 9(03).
05 W01-GRADE PIC X(04).

01 W02-TEMP PIC X.
Contd..

Page 63 of 163
COBOL

PROCEDURE DIVISION.
0000-MAIN.
DISPLAY "ENTER THE ATTENDANCE % : ".
ACCEPT W01-ATTD.
DISPLAY "ENTER THE MARKS : ".
ACCEPT W01-MARKS.

MOVE 'ZZ' TO W01-GRADE.


IF W01-ATTD = 100
IF W01-MARKS > 50
MOVE "PASS" TO W01-GRADE
* ELSE
* NEXT SENTENCE
ELSE
MOVE "FAIL" TO W01-GRADE.

DISPLAY "GRADE : " W01-GRADE.


ACCEPT W02-TEMP.
STOP RUN.

Remove the comment characters, and try executing the program with the input values
given above and note your findings.

Page 64 of 163
COBOL

7. Iterations
PERFORM statement
The simple PERFORM statement, is used to execute a specified routine from one or
more points in a program.

The PERFORM statement will :


1. Execute all instructions in the named paragraph.
2. Transfer control to the next instruction in sequence, after the PERFORM.

PROCEDURE DIVISION.
100-MAIN-MODULE.
:
PERFORM 400-HEADING-RTN.
:
200-CALC-RTN.
:
:
400-HEADING-RTN.
:
:

Example 7.1

PERFORM..THRU
The PERFORM executes all statement beginning at pargraph-name-1 until the end of
paragraph-name-2 is reached. Control is then transferred to the statement directly
following the PERFORM.

100-MAIN.
PERFORM 300-PARA THRU 500-PARA.
:
200-PARA.
:
300-PARA.
:
400-PARA.
:
500-PARA.
EXIT.
600-PARA.
:

Example 7.2

Page 65 of 163
COBOL

The EXIT statement


EXIT is a COBOL reserved word that performs no operation. It is used to allow
execution to pass over other statements or to transfer control back to the statement
following the original PERFORM. It is used, when necessary, as an end point in a
paragraph.

PERFORM..UNTIL
Iteration may be performed in COBOL using a PERFORM..UNTIL statement. The
contents of the identifiers used in the UNTIL clause should be changed within the
paragraph(s) being performed. The condition in a PERFORM .. UNTIL is tested before
the named paragraph is executed even once. If the condition indicated in the UNTIL
clause is met at the time of execution, then the name paragraph(s) will not be
executed.

Procedure used in Looping

Paragraph containing the PERFORM that “Loops”

1. Initialize the field to be tested (e.g., MOVE 0 TO COUNTER1).


2. Code a PERFORM..UNTIL using a separate paragraph. For example, PERFORM
UNTIL COUNTER1 = 5.

Loop to be performed

1. Code the steps required in the loop as a separated paragraph.


2. Increase or decrease the value in the field to be tested (e.g., ADD 1 TO
COUNTER1).

IDENTIFICATION DIVISION.
PROGRAM-ID. CH07EX03.
*************************************************
* This program displays the series 1,2,3...25. *
*************************************************

ENVIRONMENT DIVISION.

DATA DIVISION.
WORKING-STORAGE SECTION.
01 W01-CNT PIC 9(02) VALUE 1.
01 W02-PRT-CNT PIC Z9.

PROCEDURE DIVISION.
0000-MAIN.
PERFORM 1000-DISP THRU 1000-EXIT UNTIL W01-CNT > 25.
STOP RUN.

Page 66 of 163
COBOL

1000-DISP.
MOVE W01-CNT TO W02-PRT-CNT.
DISPLAY W02-PRT-CNT.
ADD 1 TO W01-CNT.

1000-EXIT.
EXIT.

Example 7.3

PERFORM..TIMES
The PERFORM..TIMES construct is used to execute a sequence of steps a fixed number
of times. It is not necessary to establish a counter that must be incremented each
time through the loop. When using the TIMES format (PERFORM paragraph-name-1
identifier-1 TIMES) : (1) the identifier must be specified in the DATA DIVISION; (2) it
must have a numeric PICTURE clause; and (3) it must contain only integers or zeros.

* This program displays the Hello 3 times.


MOVE 3 TO COUNTER1.
PERFORM 200-DISP-RTN COUNTER1 TIMES.
:
STOP RUN.
200-DISP-RTN.
DISPLAY ‘HELLO’.

Example 7.4

GO TO
A GO TO permanently transfers control to another paragraph. It does not return
control to the paragraph from where it was issued.

Page 67 of 163
COBOL

8. File Handling
File Organization method
It is important that file be so organized that efficient processing can be accomplished
by matching the file data characteristics, processing method, and file organization.
Basically, three methods of file organization are available on disk systems :
sequential, indexed sequential, and relative file organization.

Sequential file organization

Sequential file organization indicates that the records in the file are positioned in a
sequential order, such as according to part number.

Indexed sequential file organization

Indexed sequential file organization is one in which the records are filed sequentially,
but a table (index is available which identifies the location of groups of records,
thereby reducing access time.

Relative file organization

Relative file organization is such that the logical order and physical order of the
records do not necessarily correspond with one another. For such a file, a technique,
or rule, is required to determine the location of the record in the disk system.

This chapter shows you how to process sequential files in COBOL.

Any program that (1) reads data from input files or (2) produces output files, requires
an INPUT-OUTPUT SECTION and a FILE SECTION to describe the input and output
areas.

INPUT-OUTPUT SECTION
The INPUT-OUTPUT SECTION of the ENVIRONMENT DIVISION follows the
CONFIGURATION SECTION and supplies information concerning the input and output
devices used in the program. In the FILE-CONTROL paragraph, a file-name is selected
for each file to be used in the program; in addition, each file-name selected is
assigned to a device. The SELECT statement is coded in Area B.

Page 68 of 163
COBOL

ENVIRONMENT DIVISION.
:
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT EMPLOYEE-FILE
ASSIGN TO ‘EMP.DAT’
ORGANIZATION IS SEQUENTIAL.

Example 8.1

FILE SECTION.
Each file is described in the FILE SECTION with an FD sentence that may consist of a
series of clauses. After the clauses are specified, the FD sentence ends with a period.
FD is an abbreviation for File Description. Each FD entry will describe a file defined in
a SELECT statement in the ENVIRONMENT DIVISION.

The two entries, DATA DIVISION and FILE SECTION, are coded in Area A. FD is also
coded in Area A. The file-name, however, is typically coded in Area B.

DATA DIVISION.
FILE SECTION.
FD EMPLOYEE-FILE
LABEL RECORDS ARE STANDARD
RECORD CONTAINS 70 CHARACTERS
BLOCK CONTAINS 10 RECORDS.

Example 8.2
Label Records

Label records are usually created as the first and last records of a disk or tape to
provide identifying information about the file on disk or tape. Labels are created on
output files so that, when the same file is later read as input, the labels may be
checked to ensure that the file being accessed is the correct one. Labels are created
on output files and checked on input files. The COBOL compiler will supply the
routine for writing labels on output files or for checking labels on input file if the
entry LABEL RECORDS ARE STANDARD is included.

This LABEL RECORDS clause will result in the following :


1. For output files, the first record on disk or tape file will be created as a
standard 80-position header label identifying the file to the system; similarly,
the last record on the disk or tape will be created as a trailer label.

2. For input files, these labels will be computer-checked to ensure that the file
being processed is the correct one.

Page 69 of 163
COBOL

The clause LABEL RECORDS ARE STANDARD is permitted for disk and tape files only.
Devices such as printers do not use label records, since identifying information is
unnecessary where data is visible to the human eye. The clause LABEL RECORDS ARE
OMITTED is used for such files.

RECORD CONTAINS clause

The RECORD CONTAINS clause indicates the size of each record. For printer files the
RECORD CONTAINS clause may include one extra position that is used to control the
spacing of the form (e.g., single spacing, double spacing). Thus, for 132 character
printers, a record size is sometimes set as 133 characters. In such cases, the first or
leftmost position in these 133-position print records is the form control position; it is
not actually printed.

BLOCK CONTAINS clause


The BLOCK CONTAINS clause is included in the File Description entry only for files in
which disk or tape records have been blocked. Blocking is a technique that increases
the speed of input/output operations and makes more effective use of storage space
on disk and tape. A group of logical records is included within one block to maximize
the efficient use of a disk or tape area. For example, reading in a block of 10 disk
records, is more efficient than reading in each disk record separately. Even if blocking
is used, the program processes records in the standard way, that is, one logical record
at a time.

Record Description entries

A record is a unit of information consisting or related data items within a file. Most
often, a file consists of records that all have the same length and format. These are
called fixed-length records.

For each file defined, we have one record format.

01 EMPLOYEE-REC.
05 EMP-NAME.
10 EMP-FIRST-NAME PIC X(10).
10 EMP-LAST-NAME PIC X(15).
05 EMP-DEPT PIC X(4).
05 EMP-SALARY PIC 9(5)V99.
05 EMP-DOJ PIC 9(6).

Example 8.3

Input/output verbs

There are 4 input/output verbs : OPEN, READ, WRITE, CLOSE.

Page 70 of 163
COBOL

OPEN statement

Before an input or an output file can be used by the program it must be opened. An
OPEN statement, designates files as either input or output. It also accesses the
specific devices, and makes the files available for processing. It performs header label
routines if label records are STANDARD. The OPEN statement checks the header label
to determine if the correct file has been accessed.

OPEN INPUT EMPLOYEE-FILE.


OPEN OUTPUT REPORT-FILE.

Example 8.4

The order in which files are opened is not significant. The only restriction is that a file
must be opened before it may be read or written; a file must be accessed before it
may be processed. Since the OPEN statement accesses the files, it is generally on of
the first instructions coded in the PROCEDURE DIVISION.

READ statement

After an input file has been opened, it may be read. A READ statement transmits data
from the input device, assigned in the ENVIRONMENT DIVISION, to the input storage
area, defined in the FILE SECTION of the DATA DIVISION.

The primary function of the READ statement is to transmit one data record to the
input area reserved for that file. That is, each time a READ statement is executed,
one record is read into primary storage.

The READ statement has, however, several other functions. Like the OPEN
statement, it performs certain checks. It checks the length of each input
record to ensure that it corresponds to the length specified in a RECORD
CONTAINS clause in the data DIVISION. If a discrepancy exists, an error
message prints, and a program interrupt occurs.

The READ statement will also use the BLOCK CONTAINS clause, if specified, to
perform a check on the blocking factor.

The AT END clause in the READ statement tests to determine if there is any more
input. An AT END clause of the READ statement tells the computer what to do if there
is no more data to be read.

Page 71 of 163
COBOL

READ EMPLOYEE-FILE
AT END
MOVE ‘YES’ TO END-OF-FILE.

Example 8.5
WRITE statement

The WRITE instruction takes data in the output area defined in the DATA DIVISION and
transmits it to the device specified in the ENVIRONMENT DIVISION.

Note that although files are read, we write records. The record-name appear on the
01 level and is generally subdivided into fields. The record description specifies the
format of the output.

WRITE EMPLOYEE-REC.

Example 8.6
CLOSE statement

A CLOSE statement is coded at the end of the job after all records have been
processed to release these files and deactivate the devices. All files that have been
opened at the beginning of the program are closed at the end of a program. The
CLOSE statement, like the OPEN, will perform additional functions. When creating
disk or tape records, for example, the CLOSE will create trailer labels; it will also
rewind a tape.

CLOSE EMPLOYEE-FILE.

Example 8.7
A program to create an employee file.

IDENTIFICATION DIVISION.
PROGRAM-ID. CH08EX08.
*****************************************************************
* This program creates a employee file containing the following *
* details : *
* Empcode (2001 onwards, should be generated) *
* Name *
* Department (Sales,Purchase,Admin,S/W) *
* Designation (Programmer,Analyst,Consultant for S/W department)*
* (Jr.Officer,Sr.Officer,Manager for other departments)*
* Salary (Should be between 2000 to 20000). *
* Accept details till the user enters 'N'. *
*****************************************************************
Contd.

Page 72 of 163
COBOL

ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT EMP-FILE ASSIGN TO 'EMPL.DAT'
ORGANIZATION IS SEQUENTIAL.

DATA DIVISION.
FILE SECTION.
FD EMP-FILE
LABEL RECORDS STANDARD
BLOCK CONTAINS 0 RECORDS
RECORD CONTAINS 80 CHARACTERS.
01 EMP-REC.
05 EMP-CODE PIC 9(04).
05 EMP-NAME.
10 EMP-FIRST-NAME PIC X(10).
10 EMP-LAST-NAME PIC X(15).
05 EMP-DEPT PIC X(08).
88 88-SW VALUE 'S/W'.
88 88-VALID-DEPT VALUE 'SALES', 'PURCHASE', 'ADMIN',
'S/W'.
05 EMP-DESIG PIC X(12).
88 88-SW-DESIG VALUE 'PROGRAMMER', 'ANALYST',
'CONSULTANT'.
88 88-OTH-DESIG VALUE 'JR.OFFICER', 'SR.OFFICER',
'MANAGER'.
05 EMP-SALARY PIC 9(5).
88 88-VALID-SALARY VALUE 2000 THRU 20000.
05 FILLER PIC X(26).

WORKING-STORAGE SECTION.
01 W01-FLAG.
05 W01-ANS PIC X(01) VALUE 'Y'.
88 88-VALID-ANS VALUE 'Y', 'y', 'N', 'n'.
88 88-ANS-NO VALUE 'N', 'n'.

PROCEDURE DIVISION.
0000-MAIN.
PERFORM 1000-INIT THRU 1000-EXIT.
PERFORM 2000-PROCESS THRU 2000-EXIT UNTIL 88-ANS-NO.
PERFORM 3000-TERM THRU 3000-EXIT.
STOP RUN.
Contd.

Page 73 of 163
COBOL

1000-INIT.
OPEN OUTPUT EMP-FILE.
MOVE 2000 TO EMP-CODE.

1000-EXIT.
EXIT.

2000-PROCESS.
ADD 1 TO EMP-CODE.
DISPLAY 'ENTER FIRST NAME : '.
ACCEPT EMP-FIRST-NAME.
DISPLAY 'ENTER LAST NAME : '.
ACCEPT EMP-LAST-NAME.

MOVE SPACES TO EMP-DEPT.


PERFORM 2100-ACPT-DEPT THRU 2100-EXIT UNTIL 88-VALID-DEPT.

MOVE SPACES TO EMP-DESIG.


IF 88-SW
PERFORM 2200-ACPT-SW-DESG THRU 2200-EXIT
UNTIL 88-SW-DESIG
ELSE
PERFORM 2300-ACPT-OTH-DESG THRU 2300-EXIT
UNTIL 88-OTH-DESIG.

MOVE ZEROES TO EMP-SALARY.


PERFORM 2400-ACPT-SALARY THRU 2400-EXIT UNTIL 88-VALID-SALARY.

WRITE EMP-REC.

MOVE SPACES TO W01-ANS.


PERFORM 2500-ACPT-ANS THRU 2500-EXIT UNTIL 88-VALID-ANS.

2000-EXIT.
EXIT.

2100-ACPT-DEPT.
DISPLAY 'ENTER THE DEPARTMENT : '.
ACCEPT EMP-DEPT.

2100-EXIT.
EXIT.
Contd.

Page 74 of 163
COBOL

2200-ACPT-SW-DESG.
DISPLAY 'ENTER THE DESIGNATION : '.
ACCEPT EMP-DESIG.

2200-EXIT.
EXIT.

2300-ACPT-OTH-DESG.
DISPLAY 'ENTER THE DESIGNATION : '.
ACCEPT EMP-DESIG.

2300-EXIT.
EXIT.

2400-ACPT-SALARY.
DISPLAY 'ENTER SALARY (2000-20000) :'.
ACCEPT EMP-SALARY.

2400-EXIT.
EXIT.

2500-ACPT-ANS.
DISPLAY 'DO YOU WANT TO ENTER MORE DATA ? '.
ACCEPT W01-ANS.

2500-EXIT.
EXIT.

3000-TERM.
CLOSE EMP-FILE.
3000-EXIT.
EXIT.

Example 8.8

COPY statement
A COPY statement is used to bring into a program a series of prewritten COBOL
entries that have been stored in a library. Copying entries from a library, rather than
coding them, has the following benefits : (1) it could save a programmer a
considerable amount of coding and debugging time; (2) it promotes program
standardization since all programs that copy entries from a library will be using
common data-names and/or procedures; (3) it reduces the time it takes to make
modifications and reduces duplication of effort; if a change needs to be made to a
data entry, it can be made just once in the library without the need to alter
individual programs; and (4) library entries are extensively annotated so that they
are meaningful to all users; this annotation results in better-documented programs
and systems.

Most often, the COPY statement is used to copy FD and 01 entries that define and
describe files and records. In addition, standard modules to be used in the

Page 75 of 163
COBOL

PROCEDURE DIVISION of several programs may also be stored in a library and copied as
needed.

Contents of EMP01

SELECT EMP-FILE ASSIGN TO 'EMPL.DAT'


ORGANIZATION IS SEQUENTIAL.

Example 8.9a

The ENVIRONMENT DIVISION entry using a COPY statement

ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
COPY EMP01.

Example 8.9b
Contents of EMP02

FD EMP-FILE
LABEL RECORDS STANDARD
BLOCK CONTAINS 0 RECORDS
RECORD CONTAINS 80 CHARACTERS.
01 EMP-REC.
05 EMP-CODE PIC 9(04).
05 EMP-NAME.
10 EMP-FIRST-NAME PIC X(10).
10 EMP-LAST-NAME PIC X(15).
05 EMP-DEPT PIC X(08).
88 88-SW VALUE 'S/W'.
88 88-VALID-DEPT VALUE 'SALES', 'PURCHASE', 'ADMIN',
'S/W'.
05 EMP-DESIG PIC X(12).
88 88-SW-DESIG VALUE 'PROGRAMMER', 'ANALYST',
'CONSULTANT'.
88 88-OTH-DESIG VALUE 'JR.OFFICER', 'SR.OFFICER',
'MANAGER'.
05 EMP-SALARY PIC 9(5).
88 88-VALID-SALARY VALUE 2000 THRU 20000.
05 FILLER PIC X(26).

Example 8.9c

Page 76 of 163
COBOL

The DATA DIVISION entry using a COPY statement

DATA DIVISION.
FILE SECTION.
COPY EMP02.

Example 8.9d

A program to read from the employee file.

IDENTIFICATION DIVISION.
PROGRAM-ID. CH08EX10.
****************************************************************
* This program displays the details of employees in the *
* SALES department and the average salary for the *
* department. *
****************************************************************

ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
COPY EMP01.

DATA DIVISION.
FILE SECTION.
COPY EMP02.
WORKING-STORAGE SECTION.
01 W02-EOF.
05 W02-EMP-EOF PIC X(01) VALUE 'N'.
88 88-EMP-EOF VALUE 'Y'.
01 W03-TOTALS.
05 W03-TOT-SALARY PIC 9(07).
05 W03-TOT-EMP PIC 9(03) VALUE ZEROS.
05 W03-AVG-SALARY PIC Z(05)9.99.

PROCEDURE DIVISION.
0000-MAIN.
PERFORM 1000-INIT THRU 1000-EXIT.
PERFORM 2000-PROCESS THRU 2000-EXIT UNTIL 88-EMP-EOF.
PERFORM 3000-TERM THRU 3000-EXIT.
STOP RUN.
Contd.

Page 77 of 163
COBOL

1000-INIT.
OPEN INPUT EMP-FILE.
PERFORM 4000-READ-EMP THRU 4000-EXIT.

1000-EXIT.
EXIT.

2000-PROCESS.
IF EMP-DEPT = 'SALES'
DISPLAY EMP-NAME ' ' EMP-SALARY
ADD 1 TO W03-TOT-EMP
ADD EMP-SALARY TO W03-TOT-SALARY.

PERFORM 4000-READ-EMP THRU 4000-EXIT.

2000-EXIT.
EXIT.

3000-TERM.
CLOSE EMP-FILE.
DIVIDE W03-TOT-SALARY BY W03-TOT-EMP
GIVING W03-AVG-SALARY.
DISPLAY 'THE AVERAGE SALARY IS : ' W03-AVG-SALARY.

3000-EXIT.
EXIT.

4000-READ-EMP.
READ EMP-FILE
AT END
MOVE 'Y' TO W02-EMP-EOF.

4000-EXIT.
EXIT.

Example 8.10

Page 78 of 163
COBOL

9. Sorting
Sorting
Records in files frequently must be sorted into specific sequences for updating,
answering inquiries, or generating reports. Sorting is a common procedure used for
arranging records into a specific order so that sequential processing can be
performed.

COBOL has a SORT verb, which can make it very useful as part of a COBOL program.

The programmer must specify whether the key field is to be an ASCENDING KEY or a
DESCENDING KEY, depending on which sequence is required :
ASCENDING : From lowest to highest
DESCENDING : From highest to lowest

The SORT verb may be used to sequence records with more than one key field. For
example, to sort an employee file so that it is in alphabetic sequence by name within
each department.

SORT SORT-FILE
ON ASCENDING KEY S-EMP-DEPT
ON ASCENDING KEY S-EMP-NAME
USING EMPLOYEE-FILE
GIVING SORT-EMPLOYEE-FILE.

Example 9.1
There are three major files used in a sort :
1. Input file : File of unsorted input records.
2. Work or sort file : File used to store records temporarily during the sorting
process.
3. Output file: File of sorted output records.

All these files would be defined in the ENVIRONMENT DIVISION using standard ASSIGN
clauses, which are system dependent. The SORT-FILE is actually assigned to a
temporary work area that is used during processing but not saved. Only the unsorted
disk file and the sorted output disk file are assigned standard file-names so that they
can be permanently stored.

FDs are used in the DATA DIVISION to define and describe the input and output files in
the usual way. The sort or work file is described with an SD (sort file description)
entry. The only difference between SD and FD entries is that an SD must not have a
LABEL RECORDS clause. Note, too, that the field(s) specified as the KEY field(s) for
sorting purposes must be defined as part of the sort record format.

Page 79 of 163
COBOL

ENVIRONMENT DIVISION.
:
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT SORT-FILE
ASSIGN TO DISK.
:
DATA DIVISION.
FILE SECTION.
SD SORT-FILE.
01 SORT-REC.
05 S-EMP-NAME.
10 S-EMP-FIRST-NAME PIC X(10).
10 S-EMP-LAST-NAME PIC X(15).
05 S-EMP-DEPT PIC X(4).
05 FILLER PIC 9(13).

Example 9.2
The SORT statement can, however, be used in conjunction with procedures that
process records just before they are sorted and/or process records after they are
sorted.

IDENTIFICATION DIVISION.
PROGRAM-ID. CH09EX03.
****************************************************************
* This program sorts the employee file *
****************************************************************

ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT IN-EMP-FILE ASSIGN TO 'EMPL.DAT'
ORGANIZATION IS SEQUENTIAL.

SELECT SORT-FILE ASSIGN TO DISK.

SELECT OUT-EMP-FILE ASSIGN TO 'SRTEMPL.DAT'


ORGANIZATION IS SEQUENTIAL.

DATA DIVISION.
FILE SECTION.
FD IN-EMP-FILE
LABEL RECORDS STANDARD
BLOCK CONTAINS 0 RECORDS
RECORD CONTAINS 80 CHARACTERS.
Contd.

Page 80 of 163
COBOL

01 IN-EMP-REC.
05 IN-EMP-CODE PIC 9(04).
05 IN-EMP-NAME.
10 IN-EMP-FIRST-NAME PIC X(10).
10 IN-EMP-LAST-NAME PIC X(15).

05 IN-EMP-DEPT PIC X(08).


05 IN-EMP-DESIG PIC X(12).
05 IN-EMP-SALARY PIC 9(5).
05 FILLER PIC X(26).

SD SORT-FILE.
01 SORT-REC.
05 SRT-EMP-CODE PIC 9(04).
05 SRT-EMP-NAME.
10 SRT-EMP-FIRST-NAME PIC X(10).
10 SRT-EMP-LAST-NAME PIC X(15).
05 SRT-EMP-DEPT PIC X(08).
05 SRT-EMP-DESIG PIC X(12).
05 SRT-EMP-SALARY PIC 9(5).
05 FILLER PIC X(26).

FD OUT-EMP-FILE
LABEL RECORDS STANDARD
BLOCK CONTAINS 0 RECORDS
RECORD CONTAINS 80 CHARACTERS.
01 OUT-EMP-REC.
05 OUT-EMP-CODE PIC 9(04).
05 OUT-EMP-NAME.
10 OUT-EMP-FIRST-NAME PIC X(10).
10 OUT-EMP-LAST-NAME PIC X(15).
05 OUT-EMP-DEPT PIC X(08).
05 OUT-EMP-DESIG PIC X(12).
05 OUT-EMP-SALARY PIC 9(5).
05 FILLER PIC X(26).

WORKING-STORAGE SECTION.
PROCEDURE DIVISION.
0000-MAIN.
SORT SORT-FILE
ASCENDING KEY SRT-EMP-DEPT
USING IN-EMP-FILE
GIVING OUT-EMP-FILE.
STOP RUN.

Example 9.3

Page 81 of 163
COBOL

10. Trapping Runtime errors

The FILE STATUS clause


The FILE STATUS clause can be used with the SELECT statement to determine the
exact type of input or output error that has occurred when either reading from or
writing to a file. The SELECT statement could include FILE STATUS as its last clause.
The data name specified with the FILE STATUS clause must appear in the WORKING-
STORAGE as a two-position alphanumeric field.

SELECT EMPLOYEE-FILE
ASSIGN TO ‘EMP.DAT’
ORGANIZATION IS SEQUENTIAL
FILE STATUS IS WS-STATUS.
:
WORKING-STORAGE SECTION.
01 WS-STATUS PIC X(2).

Example 10.1
The possible values that may be placed in the FILE STATUS field when an input or
output operation is performed are listed in Appendix – D.

OPEN INPUT EMPLOYEE-FILE.


IF WS-STATUS NOT = ‘00’
DISPLAY ‘ERROR OPENING EMPLOYEE FILE’
STOP RUN.
READ EMPLOYEE-FILE ….
:
:

Example 10.2

IDENTIFICATION DIVISION.
PROGRAM-ID. CH10EX03.
**********************************************************
* This program appends data to the EMPLOYEE file. *
* If the file does not exist, the file is created before *
* adding the data. *
**********************************************************
Contd.

Page 82 of 163
COBOL

ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT EMPLOYEE-FILE ASSIGN TO 'EMP.DAT'
ORGANIZATION IS SEQUENTIAL
FILE STATUS IS W01-EMP-STAT.

DATA DIVISION.
FILE SECTION.
FD EMPLOYEE-FILE
LABEL RECORDS STANDARD.
01 EMPLOYEE-REC.
05 EMP-NO PIC 9(04).
05 EMP-NAME.
10 EMP-FIRST-NAME PIC X(10).
10 EMP-LAST-NAME PIC X(15).
05 EMP-DEPT PIC X(04).
05 EMP-SALARY PIC 9(05)V99.
05 EMP-DOJ PIC 9(06).

WORKING-STORAGE SECTION.
01 W01-EMP-STAT PIC X(02) VALUE SPACES.
01 W02-ANS PIC X(01) VALUE 'Y'.
88 88-ANS-NO VALUE 'N' 'n'.

PROCEDURE DIVISION.
0000-MAIN.
OPEN EXTEND EMPLOYEE-FILE.
IF W01-EMP-STAT NOT = '00'
OPEN OUTPUT EMPLOYEE-FILE.
PERFORM 1000-ACPT-PARA THRU 1000-EXIT UNTIL 88-ANS-NO.
CLOSE EMPLOYEE-FILE.
STOP RUN.

1000-ACPT-PARA.
DISPLAY 'ENTER YOUR EMP CODE : ' WITH NO ADVANCING.
ACCEPT EMP-NO.
DISPLAY 'ENTER YOUR FIRST NAME : ' WITH NO ADVANCING.
ACCEPT EMP-FIRST-NAME.
DISPLAY 'ENTER YOUR LAST NAME : ' WITH NO ADVANCING.
ACCEPT EMP-LAST-NAME.
DISPLAY 'ENTER YOUR DEPARTMENT : ' WITH NO ADVANCING.
ACCEPT EMP-DEPT.
DISPLAY 'ENTER YOUR SALARY : ' WITH NO ADVANCING.
Contd.

Page 83 of 163
COBOL

ACCEPT EMP-SALARY.
DISPLAY 'ENTER YOUR DATE OF JOINING : ' WITH NO ADVANCING.
ACCEPT EMP-DOJ.
WRITE EMPLOYEE-REC.
DISPLAY 'DO YOU WANT TO ADD MORE RECORDS : '
WITH NO ADVANCING.
ACCEPT W02-ANS.

1000-EXIT.
EXIT.

Example 10.3

Page 84 of 163
COBOL

11. REPORTS
IDENTIFICATION DIVISION.
PROGRAM-ID. CH11EX01.
****************************************************************
* This program displays the details of employees in the *
* SALES department and the average salary for the *
* department. Print 10 records on each page. *
****************************************************************

ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT EMP-FILE ASSIGN TO 'EMPL.DAT'
ORGANIZATION IS SEQUENTIAL
FILE STATUS IS W01-EMP-STAT.

SELECT REPORT-FILE ASSIGN TO 'REP1101.DAT'


ORGANIZATION IS SEQUENTIAL
FILE STATUS IS W01-REP-STAT.

DATA DIVISION.
FILE SECTION.
FD EMP-FILE
LABEL RECORDS STANDARD
BLOCK CONTAINS 0 RECORDS
RECORD CONTAINS 80 CHARACTERS.
01 EMP-REC.
05 EMP-CODE PIC 9(04).
05 EMP-NAME.
10 EMP-FIRST-NAME PIC X(10).
10 EMP-LAST-NAME PIC X(15).
05 EMP-DEPT PIC X(08).
88 88-SW VALUE 'S/W'.
88 88-VALID-DEPT VALUE 'SALES', 'PURCHASE', 'ADMIN',
'S/W'.
05 EMP-DESIG PIC X(12).
88 88-SW-DESIG VALUE 'PROGRAMMER', 'ANALYST',
'CONSULTANT'.
88 88-OTH-DESIG VALUE 'JR.OFFICER', 'SR.OFFICER',
'MANAGER'.
Contd.

Page 85 of 163
COBOL

05 EMP-SALARY PIC 9(05).


88 88-VALID-SALARY VALUE 2000 THRU 20000.
05 FILLER PIC X(26).

FD REPORT-FILE
LABEL RECORDS OMITTED
RECORD CONTAINS 80 CHARACTERS.
01 REPORT-REC PIC X(80).

WORKING-STORAGE SECTION.
01 W01-STATUS.
05 W01-EMP-STAT PIC X(02) VALUE SPACES.
05 W01-REP-STAT PIC X(02) VALUE SPACES.

01 W02-EOF.
05 W02-EMP-EOF PIC X(01) VALUE 'N'.
88 88-EMP-EOF VALUE 'Y'.

01 W03-TOTALS.
05 W03-TOT-SALARY PIC 9(07).
05 W03-TOT-EMP PIC 9(03) VALUE ZEROS.

01 W04-DEPT-LIT PIC X(08).

01 W05-OTHERS.
05 W05-REMAINDER PIC 9(02) VALUE ZERO.
05 W05-QUOT PIC 9(02) VALUE ZERO.

01 H01-CO-HEAD.
05 FILLER PIC X(35) VALUE SPACES.
05 FILLER PIC X(11) VALUE 'XYZ CO. LTD'.

01 H02-DEPT-HEAD.
05 FILLER PIC X(13) VALUE 'DEPARTMENT : '.
05 H02-DEPT PIC X(08).

01 H03-LINE.
05 FILLER PIC X(80) VALUE ALL '-'.

01 H04-COL-HEAD.
05 FILLER PIC X(06) VALUE SPACES.
05 FILLER PIC X(06) VALUE 'SR.NO.'.
05 FILLER PIC X(05) VALUE SPACES.
05 FILLER PIC X(08) VALUE 'EMP CODE'.

Contd.

Page 86 of 163
COBOL

05 FILLER PIC X(15) VALUE SPACES.


05 FILLER PIC X(04) VALUE 'NAME'.
05 FILLER PIC X(15) VALUE SPACES.
05 FILLER PIC X(06) VALUE 'SALARY'.

01 D01-EMP-DET.
05 FILLER PIC X(07) VALUE SPACES.
05 D01-SR-NO PIC Z9.
05 FILLER PIC X(10) VALUE SPACES.
05 D01-EMP-CODE PIC 9(04).
05 FILLER PIC X(07) VALUE SPACES.
05 D01-EMP-NAME PIC X(25).
05 FILLER PIC X(05).
05 D01-EMP-SALARY PIC $(5)9.

01 F01-REP.
05 FILLER PIC X(10) VALUE SPACES.
05 FILLER PIC X(17) VALUE 'AVERAGE SALARY : '.
05 FILLER PIC X(33) VALUE SPACES.
05 F01-AVG-SAL PIC $(5)9.

PROCEDURE DIVISION.
0000-MAIN.
PERFORM 1000-INIT THRU 1000-EXIT.
PERFORM 2000-PROCESS THRU 2000-EXIT UNTIL 88-EMP-EOF.
PERFORM 3000-TERM THRU 3000-EXIT.
STOP RUN.

1000-INIT.
OPEN INPUT EMP-FILE.
IF W01-EMP-STAT NOT = '00'
DISPLAY 'UNABLE TO OPEN EMPLOYEE FILE'
STOP RUN.

MOVE 'SALES' TO W04-DEPT-LIT.


OPEN OUTPUT REPORT-FILE.
IF W01-REP-STAT NOT = '00'
DISPLAY 'UNABLE TO CREATE REPORT FILE'
CLOSE EMP-FILE
STOP RUN.

PERFORM 1100-REP-HEADER THRU 1100-EXIT.


PERFORM 4000-READ-EMP THRU 4000-EXIT.
Contd.

Page 87 of 163
COBOL

1000-EXIT.
EXIT.

1100-REP-HEADER.
MOVE H01-CO-HEAD TO REPORT-REC.
WRITE REPORT-REC.

MOVE W04-DEPT-LIT TO H02-DEPT.


WRITE REPORT-REC FROM H02-DEPT-HEAD.
WRITE REPORT-REC FROM H03-LINE.
WRITE REPORT-REC FROM H04-COL-HEAD.
WRITE REPORT-REC FROM H03-LINE.

1100-EXIT.
EXIT.

2000-PROCESS.
IF EMP-DEPT = W04-DEPT-LIT
ADD 1 TO W03-TOT-EMP
ADD EMP-SALARY TO W03-TOT-SALARY
PERFORM 2100-REP-DETAIL THRU 2100-EXIT.

PERFORM 4000-READ-EMP THRU 4000-EXIT.

2000-EXIT.
EXIT.

2100-REP-DETAIL.
DIVIDE W03-TOT-EMP BY 11
GIVING W05-QUOT REMAINDER W05-REMAINDER.

IF W05-REMAINDER = ZERO
WRITE REPORT-REC FROM H03-LINE
MOVE SPACES TO REPORT-REC
WRITE REPORT-REC AFTER PAGE
PERFORM 1100-REP-HEADER.

MOVE W03-TOT-EMP TO D01-SR-NO.


MOVE EMP-CODE TO D01-EMP-CODE.
MOVE EMP-NAME TO D01-EMP-NAME.
MOVE EMP-SALARY TO D01-EMP-SALARY.
WRITE REPORT-REC FROM D01-EMP-DET.
Contd.

Page 88 of 163
COBOL

2100-EXIT.
EXIT.

3000-TERM.
DIVIDE W03-TOT-SALARY BY W03-TOT-EMP
GIVING F01-AVG-SAL ROUNDED.
PERFORM 3100-REP-FOOTER THRU 3100-EXIT.

CLOSE EMP-FILE
REPORT-FILE.

3000-EXIT.
EXIT.

3100-REP-FOOTER.
WRITE REPORT-REC FROM H03-LINE.
WRITE REPORT-REC FROM F01-REP.
WRITE REPORT-REC FROM H03-LINE.

3100-EXIT.
EXIT.

4000-READ-EMP.
READ EMP-FILE
AT END
MOVE 'Y' TO W02-EMP-EOF.

4000-EXIT.
EXIT.

Example 11.1

Page 89 of 163
COBOL

12. CONTROL BREAK PROCESSING


What is a control break procedure ?
A control break procedure is used if records are in sequence by a control field and the
number of records in each control field is variable.

Steps for a Control Break


1. Read the initial record.
2. Move the control field to a hold area in WORKING-AREA.
3. As long as the control field is equal to the hold area, execute the detail routine
for the input record. This means : Add the appropriate amount to a control
total, print the detail record and read the next record.
4. If the control field is not equal to the hold area :
Print the control total.
Initialize the control total field to zero.
Reinitialize the hold field with the new control field value if there are more
records.
Process the detail record as in step 3.
Print headings on a new page if each control total is to appear on a separate
page.
5. If required, after all records have been processed perform a control break to
print the last control group.

IDENTIFICATION DIVISION.
PROGRAM-ID. CH12EX01.
****************************************************************
* This program displays the details of employees *
* departmentwise. (Single level control break) *
****************************************************************

ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
COPY EMP01.

SELECT REPORT-FILE ASSIGN TO 'REP1201.DAT'


ORGANIZATION IS SEQUENTIAL
FILE STATUS IS W06-REP-FS.

DATA DIVISION.
FILE SECTION.
COPY EMP02.
Contd.

Page 90 of 163
COBOL

FD REPORT-FILE
LABEL RECORDS OMITTED
RECORD CONTAINS 80 CHARACTERS.
01 REPORT-REC PIC X(80).

WORKING-STORAGE SECTION.
01 W02-EOF.
05 W02-EMP-EOF PIC X(01) VALUE 'N'.
88 88-EMP-EOF VALUE 'Y'.

01 W03-TOTALS.
05 W03-TOT-SALARY PIC 9(07).
05 W03-TOT-EMP PIC 9(03) VALUE ZEROS.
05 W03-GRAND-TOT PIC 9(08) VALUE ZEROS.

01 W04-PREV-DEPT PIC X(08).

01 W05-DATE.
05 W05-YY PIC 9(02).
05 W05-MM PIC 9(02).
05 W05-DD PIC 9(02).

01 W06-REP-FS PIC X(02) VALUE SPACES.

01 H01-CO-HEAD.
05 FILLER PIC X(35) VALUE SPACES.
05 FILLER PIC X(11) VALUE 'XYZ CO. LTD'.

01 H02-DEPT-HEAD.
05 FILLER PIC X(13) VALUE 'DEPARTMENT : '.
05 H02-DEPT PIC X(08).

01 H03-LINE.
05 FILLER PIC X(80) VALUE ALL '-'.

01 H04-COL-HEAD.
05 FILLER PIC X(06) VALUE SPACES.
05 FILLER PIC X(06) VALUE 'SR.NO.'.
05 FILLER PIC X(05) VALUE SPACES.
05 FILLER PIC X(08) VALUE 'EMP CODE'.
05 FILLER PIC X(15) VALUE SPACES.
05 FILLER PIC X(04) VALUE 'NAME'.
05 FILLER PIC X(15) VALUE SPACES.
05 FILLER PIC X(06) VALUE 'SALARY'.
Contd.

Page 91 of 163
COBOL

01 H05-DATE-HEAD.
05 FILLER PIC X(64) VALUE SPACES.
05 FILLER PIC X(07) VALUE 'DATE : '.
05 H05-DATE.
10 H05-DD PIC 9(02)/.
10 H05-MM PIC 9(02)/.
10 H05-YY PIC 9(02).

01 D01-EMP-DET.
05 FILLER PIC X(07) VALUE SPACES.
05 D01-SR-NO PIC Z9.
05 FILLER PIC X(10) VALUE SPACES.
05 D01-EMP-CODE PIC 9(04).
05 FILLER PIC X(07) VALUE SPACES.
05 D01-EMP-NAME PIC X(25).
05 FILLER PIC X(05).
05 D01-EMP-SALARY PIC $(5)9.

01 F01-DEPT.
05 FILLER PIC X(10) VALUE SPACES.
05 FILLER PIC X(19) VALUE 'DEPARTMENT TOTAL : '.
05 FILLER PIC X(31) VALUE SPACES.
05 F01-DEPT-TOT PIC $(5)9.

01 F02-REP.
05 FILLER PIC X(10) VALUE SPACES.
05 FILLER PIC X(14) VALUE 'GRAND TOTAL : '.
05 FILLER PIC X(34) VALUE SPACES.
05 F02-GRAND-TOT PIC $(7)9.

PROCEDURE DIVISION.
0000-MAIN.
PERFORM 1000-INIT THRU 1000-EXIT.
PERFORM 2000-PROCESS THRU 2000-EXIT UNTIL 88-EMP-EOF.
PERFORM 3000-TERM THRU 3000-EXIT.
STOP RUN.

1000-INIT.
OPEN INPUT EMP-FILE.
IF W01-EMP-FS NOT = '00'
Contd.

Page 92 of 163
COBOL

DISPLAY 'UNABLE TO OPEN EMPLOYEE FILE'


STOP RUN.

OPEN OUTPUT REPORT-FILE


IF W06-REP-FS NOT = '00'
DISPLAY 'UNABLE TO CREATE REPORT FILE'
CLOSE EMP-FILE
STOP RUN.

PERFORM 5000-ACPT-DATE THRU 5000-EXIT.


PERFORM 4000-READ-EMP THRU 4000-EXIT.
PERFORM 1100-REP-HEADER THRU 1100-EXIT.
PERFORM 1200-DEPT-HEADER THRU 1200-EXIT.

1000-EXIT.
EXIT.

1100-REP-HEADER.
MOVE H01-CO-HEAD TO REPORT-REC.
WRITE REPORT-REC.
WRITE REPORT-REC FROM H05-DATE-HEAD.

1100-EXIT.
EXIT.

1200-DEPT-HEADER.
MOVE EMP-DEPT TO W04-PREV-DEPT, H02-DEPT.
MOVE ZEROS TO W03-TOT-EMP, W03-TOT-SALARY.
WRITE REPORT-REC FROM H02-DEPT-HEAD.
WRITE REPORT-REC FROM H03-LINE.
WRITE REPORT-REC FROM H04-COL-HEAD.
WRITE REPORT-REC FROM H03-LINE.

1200-EXIT.
EXIT.

2000-PROCESS.
IF EMP-DEPT NOT = W04-PREV-DEPT
PERFORM 2200-DEPT-BREAK.

ADD 1 TO W03-TOT-EMP
ADD EMP-SALARY TO W03-TOT-SALARY
PERFORM 2100-REP-DETAIL THRU 2100-EXIT.
Contd.

Page 93 of 163
COBOL

PERFORM 4000-READ-EMP THRU 4000-EXIT.

2000-EXIT.
EXIT.

2100-REP-DETAIL.
MOVE W03-TOT-EMP TO D01-SR-NO.
MOVE EMP-CODE TO D01-EMP-CODE.
MOVE EMP-NAME TO D01-EMP-NAME.
MOVE EMP-SALARY TO D01-EMP-SALARY.
WRITE REPORT-REC FROM D01-EMP-DET.

2100-EXIT.
EXIT.

2200-DEPT-BREAK.
PERFORM 2300-DEPT-FOOTER THRU 2300-EXIT.
PERFORM 1200-DEPT-HEADER THRU 1200-EXIT.

2200-EXIT.
EXIT.

2300-DEPT-FOOTER.
MOVE W03-TOT-SALARY TO F01-DEPT-TOT.
ADD W03-TOT-SALARY TO W03-GRAND-TOT.
WRITE REPORT-REC FROM H03-LINE.
WRITE REPORT-REC FROM F01-DEPT.
WRITE REPORT-REC FROM H03-LINE.

2300-EXIT.
EXIT.

3000-TERM.
PERFORM 2300-DEPT-FOOTER THRU 2300-EXIT.
PERFORM 3100-REP-FOOTER THRU 3100-EXIT.

CLOSE EMP-FILE
REPORT-FILE.

3000-EXIT.
EXIT.
Contd.

Page 94 of 163
COBOL

3100-REP-FOOTER.
MOVE W03-GRAND-TOT TO F02-GRAND-TOT.
WRITE REPORT-REC FROM F02-REP.
WRITE REPORT-REC FROM H03-LINE.

3100-EXIT.
EXIT.

4000-READ-EMP.
READ EMP-FILE
AT END
MOVE 'Y' TO W02-EMP-EOF.

4000-EXIT.
EXIT.

5000-ACPT-DATE.
ACCEPT W05-DATE FROM DATE.
MOVE W05-YY TO H05-YY.
MOVE W05-MM TO H05-MM.
MOVE W05-DD TO H05-DD.

5000-EXIT.
EXIT.

Example 12.1

IDENTIFICATION DIVISION.
PROGRAM-ID. CH12EX02.
****************************************************************
* This program displays the details of employees in the order *
* of department, designation. (2 level control break) *
****************************************************************

ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
COPY EMP01A.

SELECT REPORT-FILE ASSIGN TO 'REP1202.DAT'


ORGANIZATION IS SEQUENTIAL
FILE STATUS IS W05-REP-FS.

DATA DIVISION.
FILE SECTION.
COPY EMP02A.
Contd.

Page 95 of 163
COBOL

FD REPORT-FILE
LABEL RECORDS OMITTED
RECORD CONTAINS 80 CHARACTERS.
01 REPORT-REC PIC X(80).

WORKING-STORAGE SECTION.
01 W02-EOF.
05 W02-EMP-EOF PIC X(01) VALUE 'N'.
88 88-EMP-EOF VALUE 'Y'.

01 W03-TOTALS.
05 W03-DESIG-TOT-SALARY PIC 9(07).
05 W03-DEPT-TOT-SALARY PIC 9(07).
05 W03-SR-NO PIC 9(03) VALUE ZEROS.
05 W03-GRAND-TOT PIC 9(08) VALUE ZEROS.

01 W04-PREV.
05 W04-PREV-DEPT PIC X(08).
05 W04-PREV-DESIG PIC X(12).

01 W05-REP-FS PIC X(02) VALUE SPACES.

01 H01-CO-HEAD.
05 FILLER PIC X(35) VALUE SPACES.
05 FILLER PIC X(11) VALUE 'XYZ CO. LTD'.

01 H02-DEPT-HEAD.
05 FILLER PIC X(13) VALUE 'DEPARTMENT : '.
05 H02-DEPT PIC X(08).

01 H03-LINE.
05 FILLER PIC X(80) VALUE ALL '-'.

01 H04-COL-HEAD.
05 FILLER PIC X(06) VALUE SPACES.
05 FILLER PIC X(06) VALUE 'SR.NO.'.
05 FILLER PIC X(05) VALUE SPACES.
05 FILLER PIC X(08) VALUE 'EMP CODE'.
05 FILLER PIC X(15) VALUE SPACES.
05 FILLER PIC X(04) VALUE 'NAME'.

05 FILLER PIC X(15) VALUE SPACES.


05 FILLER PIC X(06) VALUE 'SALARY'.

01 H05-DESIG-HEAD.
05 FILLER PIC X(14) VALUE 'DESIGNATION : '.
05 H05-DESIG PIC X(12).

Contd.

Page 96 of 163
COBOL

05 FILLER PIC X(07) VALUE SPACES.


05 D01-EMP-NAME PIC X(25).
05 FILLER PIC X(05).
05 D01-EMP-SALARY PIC $(5)9.

01 F01-DEPT.
05 FILLER PIC X(10) VALUE SPACES.
05 FILLER PIC X(19)
VALUE 'DEPARTMENT TOTAL : '.
05 FILLER PIC X(31) VALUE SPACES.
05 F01-DEPT-TOT PIC $(5)9.

01 F02-REP.
05 FILLER PIC X(10) VALUE SPACES.
05 FILLER PIC X(14) VALUE 'GRAND TOTAL : '.
05 FILLER PIC X(34) VALUE SPACES.
05 F02-GRAND-TOT PIC $(7)9.

01 F03-DESIG.
05 FILLER PIC X(10) VALUE SPACES.
05 FILLER PIC X(20)
VALUE 'DESIGNATION TOTAL : '.
05 FILLER PIC X(30) VALUE SPACES.
05 F03-DESIG-TOT PIC $(5)9.

PROCEDURE DIVISION.
0000-MAIN.
PERFORM 1000-INIT THRU 1000-EXIT.
PERFORM 2000-PROCESS THRU 2000-EXIT UNTIL 88-EMP-EOF.
PERFORM 3000-TERM THRU 3000-EXIT.
STOP RUN.

1000-INIT.
OPEN INPUT EMP-FILE.
IF W01-EMP-FS NOT = '00'
DISPLAY 'UNABLE TO OPEN EMPLOYEE FILE'
STOP RUN.

OPEN OUTPUT REPORT-FILE


IF W05-REP-FS NOT = '00'
DISPLAY 'UNABLE TO CREATE REPORT FILE'
CLOSE EMP-FILE
STOP RUN.

PERFORM 4000-READ-EMP THRU 4000-EXIT.


PERFORM 1100-REP-HEADER THRU 1100-EXIT.
PERFORM 1200-DEPT-HEADER THRU 1200-EXIT.

1000-EXIT.
EXIT.
Contd.

Page 97 of 163
COBOL

1100-REP-HEADER.
MOVE H01-CO-HEAD TO REPORT-REC.
WRITE REPORT-REC.

1100-EXIT.
EXIT.

1200-DEPT-HEADER.
MOVE EMP-DEPT TO W04-PREV-DEPT, H02-DEPT.
MOVE ZEROS TO W03-DEPT-TOT-SALARY.
WRITE REPORT-REC FROM H02-DEPT-HEAD.
WRITE REPORT-REC FROM H03-LINE.
PERFORM 1300-DESIG-HEADER THRU 1300-EXIT.

1200-EXIT.
EXIT.

1300-DESIG-HEADER.
MOVE EMP-DESIG TO W04-PREV-DESIG, H05-DESIG.
MOVE ZEROS TO W03-DESIG-TOT-SALARY, W03-SR-NO.
WRITE REPORT-REC FROM H05-DESIG-HEAD.
WRITE REPORT-REC FROM H03-LINE.
WRITE REPORT-REC FROM H04-COL-HEAD.
WRITE REPORT-REC FROM H03-LINE.

1300-EXIT.
EXIT.

2000-PROCESS.
IF EMP-DEPT NOT = W04-PREV-DEPT
PERFORM 2200-DEPT-BREAK.
IF EMP-DESIG NOT = W04-PREV-DESIG
PERFORM 2400-DESIG-BREAK.

ADD 1 TO W03-SR-NO.
ADD EMP-SALARY TO W03-DESIG-TOT-SALARY.
PERFORM 2100-REP-DETAIL THRU 2100-EXIT.

PERFORM 4000-READ-EMP THRU 4000-EXIT.

2000-EXIT.
EXIT.

2100-REP-DETAIL.
MOVE W03-SR-NO TO D01-SR-NO.
MOVE EMP-CODE TO D01-EMP-CODE.
MOVE EMP-NAME TO D01-EMP-NAME.
MOVE EMP-SALARY TO D01-EMP-SALARY.
WRITE REPORT-REC FROM D01-EMP-DET.
Contd.

Page 98 of 163
COBOL

2100-EXIT.
EXIT.
2200-DEPT-BREAK.
PERFORM 2300-DEPT-FOOTER THRU 2300-EXIT.
PERFORM 1200-DEPT-HEADER THRU 1200-EXIT.

2200-EXIT.
EXIT.

2300-DEPT-FOOTER.
PERFORM 2500-DESIG-FOOTER THRU 2500-EXIT.
MOVE W03-DEPT-TOT-SALARY TO F01-DEPT-TOT.
ADD W03-DEPT-TOT-SALARY TO W03-GRAND-TOT.
WRITE REPORT-REC FROM F01-DEPT.
WRITE REPORT-REC FROM H03-LINE.

2300-EXIT.
EXIT.

2400-DESIG-BREAK.
PERFORM 2500-DESIG-FOOTER THRU 2500-EXIT.
PERFORM 1300-DESIG-HEADER THRU 1300-EXIT.

2400-EXIT.
EXIT.

2500-DESIG-FOOTER.
MOVE W03-DESIG-TOT-SALARY TO F03-DESIG-TOT.
ADD W03-DESIG-TOT-SALARY TO W03-DEPT-TOT-SALARY.
WRITE REPORT-REC FROM H03-LINE.
WRITE REPORT-REC FROM F03-DESIG.
WRITE REPORT-REC FROM H03-LINE.

2500-EXIT.
EXIT.

3000-TERM.
PERFORM 2300-DEPT-FOOTER THRU 2300-EXIT.
PERFORM 3100-REP-FOOTER THRU 3100-EXIT.

CLOSE EMP-FILE
REPORT-FILE.

3000-EXIT.
EXIT.
Contd.

Page 99 of 163
COBOL

3100-REP-FOOTER.
MOVE W03-GRAND-TOT TO F02-GRAND-TOT.
WRITE REPORT-REC FROM F02-REP.
WRITE REPORT-REC FROM H03-LINE.

3100-EXIT.
EXIT.

4000-READ-EMP.
READ EMP-FILE
AT END
MOVE 'Y' TO W02-EMP-EOF.

4000-EXIT.
EXIT.

Example 12.2

Page 100 of 163


COBOL

13. Indexed Files


An indexed file is really two files – the data file, which is created in sequence but can
be accessed randomly, and the index file, which contains the value of each key field
and the disk address of the record with that corresponding key field. To access an
indexed record randomly, the key field is looked up in the index file to find the disk
address of the record; then the record is accessed in the indexed data file directly.

The index on a disk is similar to a book’s index, which has unique subjects (keys) and
their corresponding page numbers (addresses). There would be two ways to find a
topic in the book. You can read the book sequentially, from the beginning, until that
topic is found, but this would be very time consuming and inefficient. The best
method would be to look up the topic in the index, find the corresponding page
number, and go directly to that page. This is precisely how records can be accessed
on a disk file that has an index.

With an indexed file, records can be accessed either sequentially or randomly,


depending on the user’s needs. The term random access implies that records are to
be processed or accessed in some order other than the one in which they were
physically written on the disk.

Creating an Indexed File


Indexed files are created in sequence; that is, the indexed file is created by reading
each record from an input file, in sequence by the key field, and writing the output
indexed disk records in the same sequence. Note, however, once the indexed file is
created, it can be accessed randomly.

The ORGANIZATION clause

The clause ORGANIZATION IS INDEXED indicates that the file is to be created with an
index.

The ACCESS clause

Since indexed files may be accessed either sequentially or randomly, the ACCESS
clause is used to denote which method will be used in the specific program. If the
ACCESS clause is omitted, the compiler will assume that the file is being processed in
SEQUENTIAL mode.

Page 101 of 163


COBOL

The RECORD KEY clause

The RECORD KEY clause names the key field within the disk record that will be used
to form the index. This field must be in the same physical location in each index
record. Usually, it is the first field. It must have a unique value for each record.

ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT IND-EMP-FILE
ASSIGN TO ‘INDEMP.DAT’
ORGANIZATION IS INDEXED
ACCESS IS SEQUENTIAL
RECORD KEY IS I-EMP-NO.
DATA DIVISION.
FILE SECTION.
FD IND-EMP-FILE
LABEL RECORDS STANDARD.
01 IND-EMP-REC.
05 I-EMP-NO PIC 9(4).
05 I-EMP-NAME PIC X(25).
05 I-EMP-DEPT PIC X(4).
05 I-EMP-SAL PIC 9(5)V99.

Example 13.1

The INVALID KEY clause

With WRITE

The INVALID KEY clause is used with a WRITE instruction to test for two possible errors
: (1) a key field that is not in sequence or (2) a key field that is the same as one
already on the indexed file. If any of these conditions exist, we call this an INVALID
KEY condition. The computer checks for an INVALID KEY prior to writing the record.

Thus, if you use an INVALID KEY clause with the WRITE statement and a records has an
erroneous key, the record is not written and the statement(s) following INVALID KEY
would be executed.

WRITE IND-EMP-REC
INVALID KEY
PERFORM 2000-ERROR-PARA.

Example 13.2

IDENTIFICATION DIVISION.
PROGRAM-ID. CH13EX03.
****************************************************************
* This program creates an indexed employee file *
****************************************************************

Page 102 of 163


COBOL

ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.

SELECT EMP-FILE ASSIGN TO 'INDEMPL.DAT'


ORGANIZATION IS INDEXED
ACCESS IS SEQUENTIAL
RECORD KEY IS EMP-CODE
ALTERNATE RECORD KEY IS EMP-NAME
ALTERNATE RECORD KEY IS EMP-DEPT WITH DUPLICATES
FILE STATUS IS W01-EMP-STAT.

DATA DIVISION.
FILE SECTION.
COPY EMP02.

WORKING-STORAGE SECTION.
01 W01-EMP-STAT PIC X(02) VALUE SPACES.
01 W02-ANS PIC X(01).
88 88-ANS-NO VALUE 'N' 'n'.
88 88-VALID-ANS VALUE 'y' 'Y' 'n' 'N'.

PROCEDURE DIVISION.
0000-MAIN.
PERFORM 1000-INIT THRU 1000-EXIT.
PERFORM 2000-PROCESS THRU 2000-EXIT UNTIL 88-ANS-NO.
PERFORM 3000-TERM THRU 3000-EXIT.
STOP RUN.

1000-INIT.
OPEN I-O EMP-FILE.
IF W01-EMP-STAT NOT = '00'
OPEN OUTPUT EMP-FILE.

1000-EXIT.
EXIT.

2000-PROCESS.
DISPLAY 'ENTER EMP CODE : ' WITH NO ADVANCING.
ACCEPT EMP-CODE.
DISPLAY 'ENTER FIRST NAME : ' WITH NO ADVANCING.
ACCEPT EMP-FIRST-NAME.
DISPLAY 'ENTER LAST NAME : ' WITH NO ADVANCING.
Contd.

Page 103 of 163


COBOL

ACCEPT EMP-LAST-NAME.
DISPLAY 'ENTER DEPARTMENT : ' WITH NO ADVANCING.
ACCEPT EMP-DEPT.
DISPLAY 'ENTER DESIGNATION : ' WITH NO ADVANCING.
ACCEPT EMP-DESIG.
DISPLAY 'ENTER SALARY : ' WITH NO ADVANCING.
ACCEPT EMP-SALARY.

WRITE EMP-REC
INVALID KEY
PERFORM 2100-ERROR THRU 2100-EXIT.

MOVE SPACES TO W02-ANS.


PERFORM 2500-ACPT-ANS THRU 2500-EXIT UNTIL 88-VALID-ANS.

2000-EXIT.
EXIT.

2100-ERROR.
DISPLAY 'ERROR WRITING RECORD'.

2100-EXIT.
EXIT.

2500-ACPT-ANS.
DISPLAY 'DO YOU WANT TO ENTER MORE DATA ? '.
ACCEPT W02-ANS.

2500-EXIT.
EXIT.

3000-TERM.
CLOSE EMP-FILE.

3000-EXIT.
EXIT.

Example 13.3
With READ

When reading a disk file randomly, we do not test for an AT END condition because we
are not reading the file in sequence; instead, we include an INVALID KEY test. If there
is no record in the INDEXED-FILE with a RECORD KEY equal to T-EMP-NO, the INVALID
KEY clause will be executed.

Page 104 of 163


COBOL

DISPLAY ‘ENTER EMPLOYEE CODE :’


ACCEPT T-EMP-EMP-NO.
MOVE T-EMP-NO TO I-EMP-NO.
READ IND-EMP-FILE
INVALID KEY
PERFORM 600-ERR-RTN.

Example 13.4

IDENTIFICATION DIVISION.
PROGRAM-ID. CH13EX05.
****************************************************************
* This program accepts an employee code from the user and *
* displays the employee record. *
****************************************************************

ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.

SELECT EMP-FILE ASSIGN TO 'INDEMPL.DAT'


ORGANIZATION IS INDEXED
ACCESS IS RANDOM
RECORD KEY IS EMP-CODE
ALTERNATE RECORD KEY IS EMP-NAME
ALTERNATE RECORD KEY IS EMP-DEPT WITH DUPLICATES
FILE STATUS IS W01-EMP-STAT.

* The ALTERNATE keys are not being used in this program. COBOL requires
* that all the keys be mentioned during creation of the indexed file.
* The SELECT entry has to be the same across all the programs that
* use the same data file.

DATA DIVISION.
FILE SECTION.
COPY EMP02.
WORKING-STORAGE SECTION.
01 W01-EMP-STAT PIC X(02) VALUE SPACES.
01 W02-FOUND PIC X(01) VALUE 'Y'.
88 88-FOUND VALUE 'Y'.

PROCEDURE DIVISION.
0000-MAIN.
PERFORM 1000-INIT THRU 1000-EXIT.
PERFORM 2000-PROCESS THRU 2000-EXIT.
PERFORM 3000-TERM THRU 3000-EXIT.
STOP RUN.
Contd.

Page 105 of 163


COBOL

1000-INIT.
OPEN INPUT EMP-FILE.
IF W01-EMP-STAT NOT = '00'
DISPLAY 'ERROR OPENING EMPLOYEE FILE'
STOP RUN.

1000-EXIT.
EXIT.

2000-PROCESS.
DISPLAY 'ENTER EMP CODE : ' WITH NO ADVANCING.
ACCEPT EMP-CODE.

READ EMP-FILE
INVALID KEY
MOVE 'N' TO W02-FOUND
DISPLAY 'EMPLOYEE RECORD DOES NOT EXIST'.

IF 88-FOUND
DISPLAY 'NAME : ' EMP-NAME
DISPLAY 'DESIGNATION : ' EMP-DESIG
DISPLAY 'DEPARTMENT : ' EMP-DEPT
DISPLAY 'SALARY : ' EMP-SALARY.

2000-EXIT.
EXIT.
3000-TERM.
CLOSE EMP-FILE.
3000-EXIT.
EXIT.

Example 13.5

DELETE verb

The DELETE verb can be used to delete records from indexed files. Note that we use
the file-name with the DELETE verb, but the word RECORD can be specified as well.
That is, both the statements DELETE INDEXED-FILE and DELETE INDEXED-FILE RECORD
can be used to delete the record in the INDEXED-FILE storage area.

To delete a record from an indexed file, you should first read the record into storage
and then instruct the computer to delete it.

Page 106 of 163


COBOL

MOVE ‘Y’ TO WS-FOUND.


MOVE 1001 TO I-EMP-NO.
READ IND-EMP-FILE
INVALID KEY
MOVE ‘N’ TO WS-FOUND.
IF WS-FOUND = ‘Y’
DELETE IND-EMP-FILE
INVALID KEY
DISPLAY ‘ERROR DELETING RECORD’.

Example 13.6
Sample Indexed File Updation Program

This program updates an Indexed employee file using the REC-STATUS field in the transaction
file. The Transaction file has details has Employee no, name, salary and rec-status (indicating
whether the transaction is pertaining to add - 1, delete – 2, update/modify – 3. If REC-STATUS is 2,
the transaction record will only contain the employee code. For REC-STATUS 1, all details
pertaining to the employee are present in the transaction file. For REC-STATUS 3, the transaction
record will contain the employee code and salary. Depending on the value in the REC-STATUS
field, a new employee record is added, or an existing employee record is either deleted or updated
in the indexed file. For example, if the value of the REC-STATUS field is 1, then the employee
transaction record data is to be added in the indexed file, if the REC-STATUS field is 2, then the
employee transaction record is to be deleted from the indexed file and REC-STATUS = 3.

The transaction file is read sequential from the beginning to the end. For each Transaction record
read, the record for that employee is looked up in the Indexed file. For adding a record in the
indexed file the employee record should not be present. For deleting/modifying a record the
employee record should be present in the indexed file.

IDENTIFICATION DIVISION
PROGRAM-ID. INDLUPD.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
INPUT-OUTPUT SECTION.
SELECT EMPFILE ASSIGN TO 'EMPFILE'
ORGANIZATION IS INDEXED
ACCESS IS RANDOM
RECORD KEY IS EMPNO.
Contd.

Page 107 of 163


COBOL

SELECT TRANSFILE ASSIGN TO 'TFILE.DAT'


ORGANIZATION IS SEQUENTIAL
ACCESS IS SEQUENTIAL.
DATA DIVISION.
FILE SECTION.
FD EMPFILE
LABEL RECORDS ARE STANDARD
RECORD CONTAINS 80 CHARACTERS.
01 EMP-REC.
05 EMPNO PIC 9(04).
05 EMPNAME PIC X(10).
05 SALARY PIC 9(05)V99.
05 FILLER PIC X(59).
FD TRANSFILE
LABEL RECORDS ARE STANDARD
RECORD CONTAINS 80 CHARACTERS.
01 TRANS-REC.
05 ENO PIC 9(04).
05 ENAME PIC X(10).
05 SAL PIC 9(05)V99.
05 REC-STATUS PIC X(01).
88 88-ADD VALUE '1'.
88 88-DELETE VALUE '2'.
88 88-MODIFY VALUE '3'.
05 FILLER PIC X(58).
WORKING-STORAGE SECTION.
01 ARE-THERE-MORE-RECORDS PIC X(01) VALUE 'Y'.
88 88-MORE-RECORDS VALUE 'Y'.
88 88-NO-MORE-RECORDS VALUE 'N'.
01 WS-ERROR-SWITCH PIC X(01) VALUE '0'.
88 88-NO-ERROR VALUE '0'.
PROCEDURE DIVISION.
0000-MAIN-PARA.
PERFORM 1000-INIT-RTN.
PERFORM 2000-CALC-RTN UNTIL 88-NO-MORE-RECORDS.
PERFORM 9000-END-OF-JOB-RTN.
STOP RUN.
1000-INIT-RTN.
OPEN I-O EMPFILE
INPUT TRANSFILE.
PERFORM 6000-READ-RTN.
2000-CALC-RTN.
IF 88-ADD
PERFORM 3000-ADD-RTN
ELSE
IF 88-DELETE
Contd.

Page 108 of 163


COBOL

PERFORM 4000-DELETE-RTN
ELSE
IF 88-MODIFY
PERFORM 5000-MODIFY-RTN
ELSE
DISPLAY 'INVALID OPTION FOR RECORD'.
PERFORM 6000-READ-RTN.
6000-READ-RTN.
READ TRANSFILE AT END
MOVE 'N' TO ARE-THERE-MORE-RECORDS.
3000-ADD-RTN.
MOVE ENO TO EMPNO.
MOVE ENAME TO EMPNAME.
MOVE SAL TO SALARY.
WRITE EMP-REC
INVALID KEY DISPLAY 'RECORD ALREADY EXISTS' EMPNO.
4000-DELETE-RTN.
MOVE ENO TO EMPNO.
READ EMPFILE
INVALID KEY PERFORM ERR-RTN.
IF 88-NO-ERROR
DELETE EMPFILE RECORD
INVALID KEY DISPLAY 'UNABLE TO DELETE RECORD'
ELSE
MOVE '0' TO WS-ERROR-SWITCH.
5000-MODIFY-RTN.
MOVE ENO TO EMPNO.
READ EMPFILE
INVALID KEY PERFORM ERR-RTN.
IF 88-NO-ERROR
ADD SAL TO SALARY
REWRITE EMP-REC
INVALID KEY DISPLAY 'CANNOT REWRITE'
ELSE
MOVE '0' TO WS-ERROR-SWITCH.
9000-END-OF-JOB-RTN.
CLOSE EMPFILE
TRANSFILE.
ERR-RTN.
DISPLAY 'RECORD NOT FOUND'.
MOVE '1' TO WS-ERROR-SWITCH.

Using ALTERNATE RECORD KEYs

Indexed files may be created with, and accessed by, more than one identifying key
field. That is, we may want to access employee records using the name as the key
field. To enable a file to be accessed randomly using more than one key field, we
would need to establish an ALTERNATE RECORD KEY.

To establish multiple key fields for indexing, we use an ALTERNATE RECORD KEY
clause in the SELECT statement.

Page 109 of 163


COBOL

Note:
1. More than one ALTERNATE record key can be used.
2. WITH DUPLICATES means than an ALTERNATE RECORD KEY need not be unique.
Thus, fields like EMP-DEPT can be used as a key even though numerous records
may have the same department no.
3. A record can be accessed by its RECORD KEY or any of its ALTERNATE RECORD
KEYs.

SELECT EMP-FILE ASSIGN TO 'INDEMPL.DAT'


ORGANIZATION IS INDEXED
ACCESS IS SEQUENTIAL
RECORD KEY IS EMP-CODE
ALTERNATE RECORD KEY IS EMP-NAME
ALTERNATE RECORD KEY IS EMP-DEPT WITH DUPLICATES
FILE STATUS IS W01-EMP-STAT.

Example 13.7
Accessing records randomly by alternate record key

The program that accesses the file by key field has the same SELECT clause except
that ACCESS IS RANDOM rather than SEQUENTIAL. In the PROCEDURE DIVISION , we can
access records by either I-EMP-NO , the record key, or I-EMP-DEPT, the alternate key.

The KEY clause is used with the READ statement when an indexed file has ALTERNATE
RECORD KEYs that we want to use to randomly access a record. If the KEY clause is
omitted when accessing a file randomly, the RECORD KEY is assumed to be the KEY
used for finding the record.

Suppose ALTERNATE RECORD KEY WITH DUPLICATES was specified in the


ENVIRONMENT DIVISION and there is more than one record with the same ALTERNATE
RECORD KEY. The first one that was actually placed on the disk will be the one
retrieved by the READ.

IDENTIFICATION DIVISION.
PROGRAM-ID. CH13EX08.
****************************************************************
* This program accepts employee name from the user and *
* displays the employee record. *
****************************************************************

ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
Contd.

Page 110 of 163


COBOL

SELECT EMP-FILE ASSIGN TO 'INDEMPL.DAT'


ORGANIZATION IS INDEXED
ACCESS IS RANDOM
RECORD KEY IS EMP-CODE
ALTERNATE RECORD KEY IS EMP-NAME
ALTERNATE RECORD KEY IS EMP-DEPT WITH DUPLICATES
FILE STATUS IS W01-EMP-STAT.

DATA DIVISION.
FILE SECTION.
COPY EMP02.

WORKING-STORAGE SECTION.
01 W01-EMP-STAT PIC X(02) VALUE SPACES.
01 W02-FOUND PIC X(01) VALUE 'Y'.
88 88-FOUND VALUE 'Y'.

PROCEDURE DIVISION.
0000-MAIN.
PERFORM 1000-INIT THRU 1000-EXIT.
PERFORM 2000-PROCESS THRU 2000-EXIT.
PERFORM 3000-TERM THRU 3000-EXIT.
STOP RUN.

1000-INIT.
OPEN INPUT EMP-FILE.
IF W01-EMP-STAT NOT = '00'
DISPLAY 'ERROR OPENING EMPLOYEE FILE'
STOP RUN.

1000-EXIT.
EXIT.

2000-PROCESS.
DISPLAY 'ENTER EMP FIRST NAME : ' WITH NO ADVANCING.
ACCEPT EMP-FIRST-NAME.
DISPLAY 'ENTER EMP LAST NAME : ' WITH NO ADVANCING.
ACCEPT EMP-LAST-NAME.

READ EMP-FILE
KEY IS EMP-NAME
INVALID KEY
MOVE 'N' TO W02-FOUND
DISPLAY 'EMPLOYEE RECORD DOES NOT EXIST'.

IF 88-FOUND
DISPLAY 'EMP CODE : ' EMP-CODE
DISPLAY 'DESIGNATION : ' EMP-DESIG
DISPLAY 'DEPARTMENT : ' EMP-DEPT
DISPLAY 'SALARY : ' EMP-SALARY.
Contd.

Page 111 of 163


COBOL

2000-EXIT.
EXIT.

3000-TERM.
CLOSE EMP-FILE.

3000-EXIT.
EXIT.

Example 13.8

IDENTIFICATION DIVISION.
PROGRAM-ID. CH13EX09.
****************************************************************
* This program lists all the records in order of the employee *
* code. *
****************************************************************
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT EMP-FILE ASSIGN TO 'INDEMPL.DAT'
ORGANIZATION IS INDEXED
ACCESS IS SEQUENTIAL
RECORD KEY IS EMP-CODE
ALTERNATE RECORD KEY IS EMP-NAME
ALTERNATE RECORD KEY IS EMP-DEPT WITH DUPLICATES
FILE STATUS IS W01-EMP-STAT.

DATA DIVISION.
FILE SECTION.
COPY EMP02.

WORKING-STORAGE SECTION.
01 W01-EMP-STAT PIC X(02) VALUE SPACES.

PROCEDURE DIVISION.
0000-MAIN.
PERFORM 1000-INIT THRU 1000-EXIT.
PERFORM 2000-PROCESS THRU 2000-EXIT
UNTIL W01-EMP-STAT = '10'.
PERFORM 3000-TERM THRU 3000-EXIT.
STOP RUN.
1000-INIT.
OPEN INPUT EMP-FILE.
IF W01-EMP-STAT NOT = '00'
1000-INIT.
OPEN INPUT EMP-FILE.
IF W01-EMP-STAT NOT = '00'
DISPLAY 'ERROR OPENING EMPLOYEE FILE'

Contd.

Page 112 of 163


COBOL

STOP RUN.
READ EMP-FILE.

1000-EXIT.
EXIT.

2000-PROCESS.
DISPLAY 'EMPCODE : ' EMP-CODE.
DISPLAY 'EMPNAME : ' EMP-FIRST-NAME EMP-LAST-NAME.
READ EMP-FILE.
2000-EXIT.
EXIT.
3000-TERM.
CLOSE EMP-FILE.
3000-EXIT.
EXIT.

Example 13.9
The START statement

The START statement enables a program to begin processing an indexed file


sequentially but at a record location other than the first or next physical record in the
file. The access of the file is to be in sequence (ACCESS IS SEQUENTIAL) if we use the
RECORD KEY for finding a record, even though we want to start the access at some
point other than the beginning. The ACCESS IS DYNAMIC clause is used if we want to
begin the processing an indexed file based on the contents of the ALTERNATE RECORD
KEY.

When the record to be accessed has a key equal to the one placed in the RECORD
KEY, the KEY clause in the START statement is not required. The INVALID clause is
executed only if no such record is found.

Note that the START locates the desired record but it does not READ it into storage.
The record must always be brought into storage with a READ statement.

Suppose we wish to begin processing with an I-EMP-NO greater than 006. We must
include a KEY clause with the START because we wish to position the file at allocation
greater than the value of a RECORD KEY. The KEY clause can be omitted only if the
record to be located has a RECORD KEY equal to the one stored.

The READ…NEXT RECORD… AT END Instruction

To process records both randomly and sequentially in a single file, ACCESS IS DYNAMIC
must be specified. To indicate that we wish to read records in sequence by some key
field from a file accessed dynamically, we must use a NEXT RECORD clause. Only the
word NEXT is required with this type of READ. Suppose, after a random update, we
wish to access all records in sequence beginning with the record that has an EMP-NO
of 6.

Page 113 of 163


COBOL

This NEXT RECORD clause is not necessary when ACCESS IS SEQUENTIAL has been
coded and a standard sequential READ… AT END is used throughout the program.
Rather, the READ … NEXT RECORD clause is used for (1) sequentially reading from a
file that has been accessed dynamically or for (2) sequentially reading from a file by
its ALTERNATE RECORD KEY, or, as in the preceding case, for (3) beginning a
sequential read from some point other than the beginning of a file.

IDENTIFICATION DIVISION.
PROGRAM-ID. CH13EX10.
****************************************************************
* Accept an employee code from the user. Display all the *
* records after the specified employee code. *
****************************************************************

ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT EMP-FILE ASSIGN TO 'INDEMPL.DAT'
ORGANIZATION IS INDEXED
ACCESS IS SEQUENTIAL
RECORD KEY IS EMP-CODE
ALTERNATE RECORD KEY IS EMP-NAME
ALTERNATE RECORD KEY IS EMP-DEPT WITH DUPLICATES
FILE STATUS IS W01-EMP-STAT.

DATA DIVISION.
FILE SECTION.
COPY EMP02.

WORKING-STORAGE SECTION.
01 W01-EMP-STAT PIC X(02) VALUE SPACES.

PROCEDURE DIVISION.
0000-MAIN.
PERFORM 1000-INIT THRU 1000-EXIT.
PERFORM 2000-PROCESS THRU 2000-EXIT
UNTIL W01-EMP-STAT NOT = '00'.
PERFORM 3000-TERM THRU 3000-EXIT.
STOP RUN.

1000-INIT.
OPEN INPUT EMP-FILE.
IF W01-EMP-STAT NOT = '00'
DISPLAY 'ERROR OPENING EMPLOYEE FILE'
STOP RUN.

DISPLAY 'ENTER THE EMPLOYEE CODE :' WITH NO ADVANCING.


ACCEPT EMP-CODE.
Contd.

Page 114 of 163


COBOL

START EMP-FILE
KEY > EMP-CODE
INVALID KEY
DISPLAY 'NO RECORDS BEYOND EMP CODE - ' EMP-CODE.

IF W01-EMP-STAT = '00'
READ EMP-FILE NEXT RECORD.

1000-EXIT.
EXIT.

2000-PROCESS.
DISPLAY 'EMPCODE : ' EMP-CODE.
DISPLAY 'EMPNAME : ' EMP-FIRST-NAME EMP-LAST-NAME.
READ EMP-FILE NEXT RECORD.

2000-EXIT.
EXIT.

3000-TERM.
CLOSE EMP-FILE.

3000-EXIT.
EXIT.

Example 13.10

The ACCESS IS DYNAMIC clause

Sometimes we wish to access an indexed file both randomly and sequentially in a


single program. For this, we say that ACCESS IS DYNAMIC.

In addition to using ACCESS IS DYNAMIC for combining sequential and random access
techniques in a single program, we can use this clause to access records by
ALTERNATE RECORD KEY. Also, when records are to be accessed by both RECORD KEY
and ALTERNATE RECORD KEY, use ACCESS IS DYNAMIC.

Rules for using the START statement

1. The file must be accessed with (a) ACCESS IS SEQUENTIAL for reading records in
sequence by the RECORD KEY or (b) ACCESS IS DYNAMIC or SEQUENTIAL for
reading records in sequence by an ALTERNATE RECORD KEY.
2. The file must be opened as either input or I-O.
3. If the KEY phrase is omitted, the relational operator “IS EQUAL TO” is implied
and the primary record key is assumed to be the key of reference.
4. We use KEY =, >, NOT < for accessing records by ALTERNATE RECORD KEY. We
also use KEY >, NOT < for accessing records by a value that is correspondingly
>, NOT < the primary RECORD KEY.

Page 115 of 163


COBOL

IDENTIFICATION DIVISION.
PROGRAM-ID. CH13EX11.
****************************************************************
* Accept the department code from the user. Display the empcode *
* and name of all the employee in the given department. *
****************************************************************

ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT EMP-FILE ASSIGN TO 'INDEMPL.DAT'
ORGANIZATION IS INDEXED
ACCESS IS DYNAMIC
RECORD KEY IS EMP-CODE
ALTERNATE RECORD KEY IS EMP-NAME
ALTERNATE RECORD KEY IS EMP-DEPT WITH DUPLICATES
FILE STATUS IS W01-EMP-STAT.

DATA DIVISION.
FILE SECTION.
COPY EMP02.

WORKING-STORAGE SECTION.
01 W01-EMP-STAT PIC X(02) VALUE SPACES.
01 W02-EMP-DEPT PIC X(08).
01 EOF PIC X(01) VALUE SPACES.
PROCEDURE DIVISION.
0000-MAIN.
PERFORM 1000-INIT THRU 1000-EXIT.
PERFORM 2000-PROCESS THRU 2000-EXIT
UNTIL FLAG = ‘Y’ OR
W02-EMP-DEPT NOT = EMP-DEPT.
PERFORM 3000-TERM THRU 3000-EXIT.
STOP RUN.

1000-INIT.
OPEN INPUT EMP-FILE.
IF W01-EMP-STAT NOT = '00'
DISPLAY 'ERROR OPENING EMPLOYEE FILE'
STOP RUN.
Contd.

Page 116 of 163


COBOL

DISPLAY 'ENTER THE DEPARTMENT NAME :' WITH NO ADVANCING.


ACCEPT W02-EMP-DEPT.

MOVE W02-EMP-DEPT TO EMP-DEPT.

START EMP-FILE
KEY = EMP-DEPT
INVALID KEY
DISPLAY 'NO EMPLOYEES IN DEPARTMENT - ' W02-EMP-DEPT.

IF W01-EMP-STAT = '00'
READ EMP-FILE NEXT RECORD AT END MOVE ‘Y’ TO EOF.

1000-EXIT.
EXIT.

2000-PROCESS.
DISPLAY 'EMPCODE : ' EMP-CODE.
DISPLAY 'EMPNAME : ' EMP-FIRST-NAME EMP-LAST-NAME.
READ EMP-FILE NEXT RECORD AT END MOVE ‘Y’ TO EOF.

2000-EXIT.
EXIT.

3000-TERM.
CLOSE EMP-FILE.

3000-EXIT.
EXIT.

Example 13.11

The READ…NEXT RECORD … Instruction

To process records both randomly and sequentially in a single file, ACCESS IS DYNAMIC
must be specified. To indicate that we wish to read records in sequence by some key
field from a file accessed dynamically, we must use a NEXT RECORD clause. The
READ…NEXT RECORD is also used for sequentially reading from a file by this
ALTERNATE RECORD KEY, or, for beginning a sequential read at some point other than
the beginning of a file.

Page 117 of 163


COBOL

Permissible INPUT-OUTPUT Statements

FILE ACCESS STATEMENT INPUT MODE OUTPUT MODE I-O MODE


MODE
Sequential READ X X
WRITE X
REWRITE X
START X X
DELETE X

Random READ X X
WRITE X X
REWRITE X
START
DELETE X

Dynamic READ X X
WRITE X X
REWRITE X
START X X
DELETE X

Page 118 of 163


COBOL

14. File updation


We will discuss 2 techniques for file updation
- Updating an existing master file
- Creation of a new master

Updating an existing master file

IDENTIFICATION DIVISION.
PROGRAM-ID. CH14EX01.
****************************************************************
* This program updates the existing employee file. *
* The employee's salary is increased by the amount in the *
* transaction file. *
* Note: There need not be transaction records for each master *
* record. *
* Only 1 transaction record will exist for a master *
* record. *
****************************************************************

ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT MASTER-EMP-FILE ASSIGN TO 'EMPL.DAT'
ORGANIZATION IS LINE SEQUENTIAL
FILE STATUS IS W01-EMP-STAT.

SELECT TRANS-FILE ASSIGN TO 'EMPTRAN.DAT'


ORGANIZATION IS LINE SEQUENTIAL
FILE STATUS IS W01-TRANS-STAT.

DATA DIVISION.
FILE SECTION.
FD MASTER-EMP-FILE
LABEL RECORDS STANDARD
BLOCK CONTAINS 0 RECORDS
RECORD CONTAINS 80 CHARACTERS.
01 MASTER-EMP-REC.
05 EMP-CODE PIC 9(04).
05 EMP-NAME.
10 EMP-FIRST-NAME PIC X(10).
10 EMP-LAST-NAME PIC X(15).
05 EMP-DEPT PIC X(08).

Page 119 of 163


COBOL

05 EMP-DESIG PIC X(12).


05 EMP-SALARY PIC 9(05).
05 FILLER PIC X(26).

FD TRANS-FILE
LABEL RECORDS STANDARD
BLOCK CONTAINS 0 RECORDS
RECORD CONTAINS 80 CHARACTERS.
01 TRANS-REC.
05 T-EMP-CODE PIC 9(04).
05 T-INCR-AMT PIC 9(04).
05 FILLER PIC X(72).

WORKING-STORAGE SECTION.
01 W01-FILE-STATUS.
05 W01-EMP-STAT PIC X(02) VALUE SPACES.
88 88-MASTER-EOF VALUE '10'.
05 W01-TRANS-STAT PIC X(02) VALUE SPACES.
88 88-TRANS-EOF VALUE '10'.

PROCEDURE DIVISION.
0000-MAIN.
PERFORM 1000-INIT THRU 1000-EXIT.
PERFORM 2000-PROCESS THRU 2000-EXIT
UNTIL 88-MASTER-EOF OR 88-TRANS-EOF.
PERFORM 3000-TERM THRU 3000-EXIT.
STOP RUN.

1000-INIT.
OPEN I-O MASTER-EMP-FILE.
IF W01-EMP-STAT NOT = '00'
DISPLAY 'UNABLE TO OPEN EMP MASTER FILE'
STOP RUN.

OPEN INPUT TRANS-FILE.


IF W01-TRANS-STAT NOT = '00'
DISPLAY 'UNABLE TO OPEN TRANSACTION FILE'
CLOSE MASTER-EMP-FILE
STOP RUN.

PERFORM 1100-READ-EMP THRU 1100-EXIT.


PERFORM 1200-READ-TRANS THRU 1200-EXIT.

Page 120 of 163


COBOL

1000-EXIT.
EXIT.

1100-READ-EMP.
READ MASTER-EMP-FILE.

1100-EXIT.
EXIT.

1200-READ-TRANS.
READ TRANS-FILE.

1200-EXIT.
EXIT.

2000-PROCESS.
IF EMP-CODE = T-EMP-CODE
PERFORM 2100-NORMAL-UPDATE
ELSE
IF EMP-CODE < T-EMP-CODE
PERFORM 1100-READ-EMP THRU 1100-EXIT
ELSE
PERFORM 1200-READ-TRANS THRU 1200-EXIT.

2000-EXIT.
EXIT.

2100-NORMAL-UPDATE.
ADD T-INCR-AMT TO EMP-SALARY.
REWRITE MASTER-EMP-REC.
PERFORM 1100-READ-EMP THRU 1100-EXIT.
PERFORM 1200-READ-TRANS THRU 1200-EXIT.

2100-EXIT.
EXIT.

3000-TERM.
CLOSE MASTER-EMP-FILE
TRANS-FILE.
3000-EXIT.
EXIT.

Page 121 of 163


COBOL

Example 14.01

Creation of a new master

IDENTIFICATION DIVISION.
PROGRAM-ID. CH14EX02.
****************************************************************
* This program creates a new employee file. *
* The employee's salary is increased by the amount in the *
* transaction file. *
* Note: There need not be transaction records for each master *
* record. *
* 1 or more transaction records will exist for a master *
* record. *
* If a master record does not exist for a given *
* transaction record, create it in the new master. *
****************************************************************

ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT MASTER-EMP-FILE ASSIGN TO 'EMPL.DAT'
ORGANIZATION IS LINE SEQUENTIAL
FILE STATUS IS W01-EMP-STAT.

SELECT TRANS-FILE ASSIGN TO 'EMPTRAN.DAT'


ORGANIZATION IS LINE SEQUENTIAL
FILE STATUS IS W01-TRANS-STAT.

SELECT NEW-EMP-FILE ASSIGN TO 'NEWEMP.DAT'


ORGANIZATION IS LINE SEQUENTIAL
FILE STATUS IS W01-NEW-EMP-STAT.

DATA DIVISION.
FILE SECTION.
FD MASTER-EMP-FILE
LABEL RECORDS STANDARD

Page 122 of 163


COBOL

BLOCK CONTAINS 0 RECORDS


RECORD CONTAINS 80 CHARACTERS.
01 MASTER-EMP-REC.
05 EMP-CODE PIC X(04).
05 EMP-NAME.
10 EMP-FIRST-NAME PIC X(10).
10 EMP-LAST-NAME PIC X(15).
05 EMP-DEPT PIC X(08).
05 EMP-DESIG PIC X(12).
05 EMP-SALARY PIC 9(05).
05 FILLER PIC X(26).

FD TRANS-FILE
LABEL RECORDS STANDARD
BLOCK CONTAINS 0 RECORDS
RECORD CONTAINS 80 CHARACTERS.
01 TRANS-REC.
05 T-EMP-CODE PIC X(04).
05 T-INCR-AMT PIC 9(04).
05 FILLER PIC X(72).

FD NEW-EMP-FILE
LABEL RECORDS STANDARD
BLOCK CONTAINS 0 RECORDS
RECORD CONTAINS 80 CHARACTERS.
01 NEW-EMP-REC.
05 N-EMP-CODE PIC 9(04).
05 N-EMP-NAME.
10 N-EMP-FIRST-NAME PIC X(10).
10 N-EMP-LAST-NAME PIC X(15).
05 N-EMP-DEPT PIC X(08).
05 N-EMP-DESIG PIC X(12).
05 N-EMP-SALARY PIC 9(05).
05 FILLER PIC X(26).

WORKING-STORAGE SECTION.
01 W01-FILE-STATUS.
05 W01-EMP-STAT PIC X(02) VALUE SPACES.
88 88-MASTER-EOF VALUE '10'.
05 W01-TRANS-STAT PIC X(02) VALUE SPACES.
88 88-TRANS-EOF VALUE '10'.
05 W01-NEW-EMP-STAT PIC X(02) VALUE SPACES.
88 88-NEW-EMP-EOF VALUE '10'.

PROCEDURE DIVISION.

Page 123 of 163


COBOL

0000-MAIN.
PERFORM 1000-INIT THRU 1000-EXIT.
PERFORM 2000-PROCESS THRU 2000-EXIT
UNTIL EMP-CODE = HIGH-VALUES AND
T-EMP-CODE = HIGH-VALUES.
PERFORM 3000-TERM THRU 3000-EXIT.
STOP RUN.

1000-INIT.
OPEN INPUT MASTER-EMP-FILE.
IF W01-EMP-STAT NOT = '00'
DISPLAY 'UNABLE TO OPEN EMP MASTER FILE'
STOP RUN.

OPEN INPUT TRANS-FILE.


IF W01-TRANS-STAT NOT = '00'
DISPLAY 'UNABLE TO OPEN TRANSACTION FILE'
CLOSE MASTER-EMP-FILE.

OPEN OUTPUT NEW-EMP-FILE.


IF W01-NEW-EMP-STAT NOT = '00'
DISPLAY 'UNABLE TO CREATE NEW MASTER FILE'
CLOSE MASTER-EMP-FILE
TRANS-FILE.

PERFORM 1100-READ-EMP THRU 1100-EXIT.


PERFORM 1200-READ-TRANS THRU 1200-EXIT.

1000-EXIT.
EXIT.

1100-READ-EMP.
READ MASTER-EMP-FILE
AT END
MOVE HIGH-VALUES TO EMP-CODE.

1100-EXIT.
EXIT.

1200-READ-TRANS.
READ TRANS-FILE
AT END
MOVE HIGH-VALUES TO T-EMP-CODE.

1200-EXIT.

Page 124 of 163


COBOL

EXIT.

2000-PROCESS.
IF EMP-CODE = T-EMP-CODE
MOVE MASTER-EMP-REC TO NEW-EMP-REC
PERFORM 2100-NORMAL-UPDATE THRU 2100-EXIT
UNTIL EMP-CODE NOT = T-EMP-CODE
WRITE NEW-EMP-REC
PERFORM 1100-READ-EMP THRU 1100-EXIT
ELSE
IF EMP-CODE < T-EMP-CODE
PERFORM 2200-TRANSFER-EMP THRU 2200-EXIT
ELSE
PERFORM 2300-NEW-EMP THRU 2300-EXIT.

2000-EXIT.
EXIT.

2100-NORMAL-UPDATE.
ADD T-INCR-AMT TO N-EMP-SALARY.
PERFORM 1200-READ-TRANS THRU 1200-EXIT.

2100-EXIT.
EXIT.

2200-TRANSFER-EMP.
MOVE MASTER-EMP-REC TO NEW-EMP-REC.
WRITE NEW-EMP-REC.
PERFORM 1100-READ-EMP THRU 1100-EXIT.

2200-EXIT.
EXIT.

2300-NEW-EMP.
MOVE T-EMP-CODE TO N-EMP-CODE.
MOVE T-INCR-AMT TO N-EMP-SALARY.
WRITE NEW-EMP-REC.
PERFORM 1200-READ-TRANS THRU 1200-EXIT.

2300-EXIT.
EXIT.

3000-TERM.
CLOSE MASTER-EMP-FILE
TRANS-FILE
NEW-EMP-FILE.

Page 125 of 163


COBOL

3000-EXIT.
EXIT.
Example 14.02

Page 126 of 163


COBOL

15. Call statement


Structured programs should consist of a series of independent modules that are
executed from the main module.

When programs are properly structured :

1. Each module may be written, compiled, and perhaps even tested


independently.
2. The modules may be written in different stages, in atop-down manner.
They may even be coded by different programmers.
3. If a specific module needs to be modified, the entire logical flow should
still function properly without the need for extensive revision to other
parts of the program.

Modules within a program can be viewed as subroutines that are called or executed
from the main module. But a program may also CALL or reference independent
subprograms stored in a library that are entirely separate from the main program
itself. The main program that references or calls a subprogram is referred to as the
calling program. The subprogram that is linked and executed within the main program
is referred to as the called program.

The called program would need to be compiled so that it may be called when needed.

When the CALL is performed, data is passed from the calling to the called program (if
the calling program has assigned values to fields used in the called program). The
entire called program is executed, data is passed from the called program back to the
calling program, and control return to the calling program.

Called Program Requirements

PROGRAM-ID.

The literal used in the CALL statement of the main program to extract a subprogram
or routine from a library and execute it must be identical to the called program’s
PROGRAM-ID. Note that the literal is enclosed in quotation marks when used in the
CALL statement.

LINKAGE SECTION

A LINKAGE SECTION must be defined in the called program for identifying those items
that (1) will be passed to the called program from the calling program and (2) passed
back from the called program to the calling program. The LINKAGE SECTION of the
called program, then, describes all items to be passed between the two programs.

Page 127 of 163


COBOL

The LINKAGE SECTION, if used, is coded after the FILE and WORKING-STORAGE
SECTIONs of the called program. This section is similar to WORKING-STORAGE except
that VALUE clauses from initializing fields are not permitted in the LINKAGE SECTION.

EXIT PROGRAM

The last executed statement in the called program must be the EXIT PROGRAM. It
signals the computer to return control back to the calling program. With COBOL 74,
EXIT PROGRAM must be the only statement in the last paragraph.

Calling Program Requirements

PROCEDURE DIVISION USING

The identifiers specified in the USING clause in the PROCEDURE DIVISION entry include
all fields defined in the LINKAGE SECTION; these identifiers will be passed from one
program to the other. They are passed to and from corresponding identifiers in the
CALL … USING of the main program.

The USING clause of the CALL statement is required if the subprogram performs any
operations in which data is to be passed from one program to another. The CALL …
USING identifies fields in the main or calling program that will be either passed to the
called program before it is executed, or passed back to the calling program after the
called program has been executed.

Sample Program

Calling Program : CH15EX01.CBL

IDENTIFICATION DIVISION.
PROGRAM-ID. CH15EX01.
ENVIRONMENT DIVISION.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 MY-NAME PIC X(20).
PROCEDURE DIVISION.
0000-MAIN.
DISPLAY 'ENTER NAME '.
ACCEPT MY-NAME.
CALL 'CH15EX02' USING MY-NAME.
STOP RUN.

Example 15.1

Called Program : CH15EX02.CBL

IDENTIFICATION DIVISION.

Page 128 of 163


COBOL

PROGRAM-ID. CH15EX02.
ENVIRONMENT DIVISION.
DATA DIVISION.
LINKAGE SECTION.
01 NM PIC X(20).
PROCEDURE DIVISION USING NM.
0000-MAIN.
DISPLAY 'HELLO ' NM.
EXIT PROGRAM.

Example 15.2

Shown below is an example that displays a parameter value passed by the calling
program to called program, and modified in the called program

Calling Program : CH15EX01A.CBL

IDENTIFICATION DIVISION.
PROGRAM-ID. CH15EX01A.
ENVIRONMENT DIVISION.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 MY-NAME PIC X(20).
PROCEDURE DIVISION.
0000-MAIN.
DISPLAY 'ENTER NAME '.
ACCEPT MY-NAME.
CALL 'CH15EX02A' USING MY-NAME.
DISPLAY MY-NAME.
STOP RUN.

Example 15.1 (A)

Page 129 of 163


COBOL

Called Program : CH15EX02A.CBL

IDENTIFICATION DIVISION.
PROGRAM-ID. CH15EX02A.
ENVIRONMENT DIVISION.
DATA DIVISION.
LINKAGE SECTION.
01 NM PIC X(20).
PROCEDURE DIVISION USING NM.
0000-MAIN.
DISPLAY ‘ENTER ANOTHER NAME FOR NM’.
ACCEPT NM.
EXIT PROGRAM.

Example 15.2 (A)


In the above example, the value of the parameter is changed in the called program,
and the calling program shows the changed value of the parameter, indicating that a
call by reference is the default.

An example of a called program, which makes use of the RENAMES clause.

PROGRAM-ID. PROC1.
LINKAGE SECTION.
01 FUNCTION-CODE.
05 A1 PIC X(05).
05 A2 PIC X.
05 A3 PIC X(06).
66 CHAR-5 RENAMES A1.
66 CHAR-6 RENAMES A1 THRU A2.
66 CHAR-12 RENAMES A1 THRU A3.
01 DATA-FIELD PIC X(60).
PROCEDURE DIVISION USING FUNCTION-CODE, DATA-FIELD.
CHECK-PARA.
IF CHAR-5 = ‘CHECK’
PERFORM CHECK-ROUTINE
ELSE
IF CHAR-6 = ‘FORMAT’
PERFORM FORMAT-ROUTINE
ELSE…..

Example 15.2 (B)

Page 130 of 163


COBOL

IDENTIFICATION DIVISION.
PROGRAM-ID. CH15EX03.
ENVIRONMENT DIVISION.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 W01-VARS.
05 W01-MARKS1 PIC 9(03).
05 W01-MARKS2 PIC 9(03).
05 W01-TOTAL PIC 9(03).

01 W02-TEMP PIC X.
PROCEDURE DIVISION.
0000-MAIN.
DISPLAY 'ENTER MARKS 1 '.
ACCEPT W01-MARKS1.
DISPLAY 'ENTER MARKS 2 '.
ACCEPT W01-MARKS2.
CALL 'CH15EX04' USING W01-VARS.
DISPLAY “TOTAL : “ W01-TOTAL.
ACCEPT W02-TEMP.
STOP RUN.

Example 15.3
Called Program : CH15EX04.CBL

IDENTIFICATION DIVISION.
PROGRAM-ID. CH15EX04.
ENVIRONMENT DIVISION.
DATA DIVISION.
LINKAGE SECTION.
01 L01-VARS.
05 L01-MARKS1 PIC 9(03).
05 L01-MARKS2 PIC 9(03).
05 L01-TOTAL PIC 9(03).

PROCEDURE DIVISION USING L01-VARS.


0000-MAIN.
ADD L01-MARKS1 L01-MARKS2 GIVING L01-TOTAL.
EXIT PROGRAM.

Example 15.4

Page 131 of 163


COBOL

16. Table Handling


A table, like a file, is a collection of logically related entries or a set of values stored
in consecutive storage locations and assigned one data-name. For example,
commission rates for different product classes, temperatures in various cities, etc.
Such data is short enough to be placed in central storage. There are specialized
instructions for table definition and manipulation.

Why use Tables ?

Let’s imagine that we want to write a program that totals a company’s sales on a
product-by-product basis. Let us assume the company sells 25 products. The products
have codes (unique) 01 thru 25.

Obviously, we need 25 accumulators to hold the sales totals for each subject.. We
define accumulators in Working-Storage as follows:

01 PRODUCT-TOTALS
05 ACUM01 PIC S9(05).
05 ACUM02 PIC S9(05).
05 ACUM03 PIC S9(05).
: : : :
05 ACUM25 PIC S9(05).

Example 16.1

Let’s assume, we have a transaction file which records sale of each product on a daily
basis. The tran-record is as follows:

01 SALES-REC
05 PRD-CODE PIC 99.
05 NUMB-SOLD PIC 9(3).

Example 16.2

In order to accumulate sales of each product correctly, we could write the following
code, in the Procedure Division:

IF PRD-CODE = 01
ADD NUMB-SOLD TO ACUM01
ELSE
IF PRD-CODE = 02
ADD NUMB-SOLD TO ACUM02
ELSE

Page 132 of 163


COBOL

IF……
ELSE
IF PRD-CODE = 25
ADD NUMB-SOLD TO ACUM25

Example 16.3

Although this approach will solve the problem, it is time consuming, error-prone, and
boring. And what if the company has 2500 products instead of just 25?

To handle problems of this type more easily, we make use of TABLES in COBOL.

In the above example of accumulating product sales, we set up a table of


accumulators as shown below:

01 PRODUCT-TOTALS.
05 ACCUM PIC S9(05) OCCURS 25 TIMES.

Example 16.4

We are reserving space for 25 occurrences of S9(5) fields. The table-name is ACCUM.

Now, there should be some way of adding the NUMB-SOLD to proper accumulator. Since
the PRD-CODE is the key to proper accumulator, it can be used as the ‘subscript’ or
‘pointer’ for ACCUM; that is, it acts as a pointer to particular occurrence of ACCUM that
is to be used. So modify the procedure division entries as:

ADD NUMB-SOLD TO ACCUM (PRD-CODE).

Example 16.5

The subscript can be any data-name as long as it is of numeric-type.

A one-dimensional table may be defined as shown in the example below.

01 TEMP-REC.
05 TEMPERATURE OCCURS 24 TIMES PIC S9(3).

Example 16.6

A DATA DIVISION entry involving an OCCURS clause includes the following:

1. Data name assigned to the table


2. Number of dimensions
3. Number of entries in each dimension

Page 133 of 163


COBOL

4. Field characteristics of the entries

The OCCURS 24 TIMES clause in the above example sets up a table in storage that has
the following conceptual structure.

TEMP-REC table

Temperature 1 Temperature 2 … … Temperature 24

Subscript

A subscript is used in the PROCEDURE DIVISION to indicate which specific item within
the array we wish to access.

The subscript is used along with the identifier that is defined with an OCCURS, to
refer to an item within an array.

For example, in order to move a single field of entry in the table, the subscript is
included in parentheses and separated from the name by a space, as shown below.

MOVE TEMPERATURE (2) TO TEMP-OUT.

Example 16.7

Execution of the PROCEDURE DIVISION statement MOVE TEMP-REC TO. .will result in
the entire table of 24 fields being moved.

INITIALISING A TABLE:

In the earlier example of accumulating product sales into a table of accumulators, we


have to initialize each entry of the table to zero before using it. Unfortunately use of
value clause with a subscripted data-item is not permitted.

For example the following would be illegal:

01 SG-TOTAL-TABLE.
05 SALES-GIRL OCCURS 50 TIMES.
10 SALES-GIRL-TOT PIC 9(7)V99 VALUE 0.

Example 16.8

Page 134 of 163


COBOL

The accumulators, must therefore be initialized in the Procedure Division as follows:

MOVE 1 TO COUNTER.
PERFORM ZERO-TABLE UNTIL COUNTER > 50.
ZERO-TABLE.
MOVE ZERO TO ACCUM (COUNTER).
ADD 1 TO COUNTER,

Example 16.9

The PERFORM verb and TABLES:

PERFORM …. VARYING:

In our earlier example, initialization of accumulators in the table was accomplished


by initializing a subscript (COUNTER) to the value1 thus pointing to first entry in the
table. A PERFORM… UNTIL was then executed and this loop terminated when the end
of the table was reached. The subscript was incremented by 1 in the paragraph
involved by the PERFORM…UNTIL. Viz. ZERO-TABLE.

COBOL offers a variation of the PERFORM…UNTIL which accomplishes the initialization


of subscript, the incrementing of subscript and termination of the loop in a single
statement. This is the PERFORM…VARYING instruction. The syntax is given below:

PERFORM procedure-1 [{THRU } procedure-2]


[{THROUGH} ]
VARYING { id-1 } FROM {id-2 } BY {id-3 }
{lit-1 } {lit-2 }
UNTIL condition-1

Now initializing a table to Zero value entries, can be done as follows:

PERFORM ZERO-TABLE VARYING COUNTER


FROM 1 BY 1 UNTIL COUNTER > 50.
ZERO-TABLE.
MOVE 0 TO ACCUM (COUNTER).

Example 16.10

To print contents of a Table entries in reverse in reverse order :

MOVE 50 TO COUNTER.
PERFORM LISTING UNTIL COUNTER < 1.
LISTING.
MOVE ACCUM (COUNTER) TO OUT-ACCUM.
DISPLAY OUT-ACCUM
SUBSTRACT 1 FROM COUNTER.

Page 135 of 163


COBOL

Example 16.11

Use of OCCURS clause


1. An OCCURS clause is used in COBOL to indicate the repeated occurrence of
fields with the same format.
2. Defining a series of totals in WORKING-STORAGE to which amounts are added;
after all data is accumulated, the total can be printed.
3. Defining a table in WORKING-STORAGE to be accessed by each input record. For
example, using the contents of some input field to “look up” the required data
in the table.

Rules for OCCURS and subscripts


There must be at least one space between the identifier and the left parenthesis that
precedes the subscript. Similarly, the subscript must be enclosed in parentheses with
no spaces within the parentheses.

A subscript may be a numeric literal or a data-name with a numeric PICTURE clause.

An OCCURS clause may be used on levels 02-49 only, because 01 level is used for
defining records not fields.
COBOL 74 permits only up to three levels of OCCURS clauses

The OCCURS clause need not be used alone in a record; other reference entries may
be included as well.

For example:

01 STATE-INCOME-TABLE.
05 AVERAGE-INCOME OCCURS 50 TIMES PIC 9(6)V99.
05 NATIONAL-AVERAGE PIC 9(6)V99.

Example 16.12

The STATE-INCOME-TABLE now refers to more than the table of 50 entries plus the
NATIONAL-AVERAGE field.

Shown below is an example that includes the name of the states along with their
corresponding average temperature figures. Size of the table is 50 * 20 = 1000 bytes.

01 STATE-INCOME-TABLE.
05 NAME-INCOME OCCURS 50 TIMES.
10 NAME PIC X(12).

Page 136 of 163


COBOL

10 INCOME PIC 9(6)V99.

Example 16.13

To access entries in the above table :

1. Use NAME (1) to refer to a field of 12 positions.


2. Use INCOME (1) to refer to an 8-position field.
3. Use NAME-INCOME (1) to refer to a storage field of 20 positions.

Page 137 of 163


COBOL

A sample program that uses a one-dimensional table.

IDENTIFICATION DIVISION.
PROGRAM-ID. CH16EX14.
**************************************************************
* This program accepts 10 numbers from the user and displays *
* the maximum. *
**************************************************************

ENVIRONMENT DIVISION.

DATA DIVISION.
WORKING-STORAGE SECTION.
01 W01-MARKS-TAB.
05 W01-MARKS OCCURS 10 TIMES PIC 9(03).

01 W02-SUB PIC 9(02).


01 W03-MAX PIC 9(03).
01 W04-SIZE PIC 9(02) VALUE 10.
* It is a normal practice to use 2 variables in a program on array handling.
* 1 variable is used for the subscript (W02-SUB) in this example
* the other variable is for the max-size of any array (W04-SIZE) in this example

PROCEDURE DIVISION.
0000-MAIN.
PERFORM 1000-ACPT-MARKS THRU 1000-EXIT
VARYING W02-SUB FROM 1 BY 1
UNTIL W02-SUB > W04-SIZE.

MOVE W01-MARKS(1) TO W03-MAX.

PERFORM 2000-FIND-MAX THRU 2000-EXIT


VARYING W02-SUB FROM 1 BY 1
UNTIL W02-SUB > W04-SIZE.
DISPLAY 'MAXIMUM : ' W03-MAX.
STOP RUN.

1000-ACPT-MARKS.
DISPLAY 'ENTER NUMBER ' W02-SUB ' : ' NO ADVANCING.
ACCEPT W01-MARKS(W02-SUB).

1000-EXIT.
EXIT.

2000-FIND-MAX.
IF W01-MARKS(W02-SUB) > W03-MAX
MOVE W01-MARKS(W02-SUB) TO W03-MAX.
2000-EXIT.
EXIT.

Example 16.14

Page 138 of 163


COBOL

Using OCCURS with VALUE and REDEFINES clauses


Sometimes we want to initialize elements in a table or an array with specific values.

With COBOL 74, we cannot use a VALUE clause with an entry defined by an OCCURS
clause. Instead we can define the field with one value and then redefine that storage
area into separate array elements. As a result, each array element will have a
different value.

IDENTIFICATION DIVISION.
PROGRAM-ID. CH16EX15.
**************************************************************
* This program displays the system date in two formats: *
* a) 10-Jan-01 *
* b) January 10, 01 *
**************************************************************
ENVIRONMENT DIVISION.

DATA DIVISION.
WORKING-STORAGE SECTION.
01 W01-MONTH-1.
05 FILLER PIC X(09) VALUE 'January'.
05 FILLER PIC X(09) VALUE 'February'.
05 FILLER PIC X(09) VALUE 'March'.
05 FILLER PIC X(09) VALUE 'April'.
05 FILLER PIC X(09) VALUE 'May'.
05 FILLER PIC X(09) VALUE 'June'.
05 FILLER PIC X(09) VALUE 'July'.
05 FILLER PIC X(09) VALUE 'August'.
05 FILLER PIC X(09) VALUE 'September'.
05 FILLER PIC X(09) VALUE 'October'.
05 FILLER PIC X(09) VALUE 'November'.
05 FILLER PIC X(09) VALUE 'December'.

01 W02-FULL-MONTH-TAB REDEFINES W01-MONTH-1.


05 W02-MONTH-NAME OCCURS 12 TIMES PIC X(09).

01 W03-MONTH-2.
05 W03-STRING PIC X(36)
VALUE 'JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC'.

05 W03-MTH REDEFINES W03-STRING


Contd.

Page 139 of 163


COBOL

OCCURS 12 TIMES PIC X(03).


01 W04-DATE.
05 W04-YY PIC 9(02).
05 W04-MM PIC 9(02).
05 W04-DD PIC 9(02).
PROCEDURE DIVISION.
0000-MAIN.
PERFORM 1000-ACPT-DATE THRU 1000-EXIT.
PERFORM 2000-DISPLAY-DATE THRU 2000-EXIT.
STOP RUN.
1000-ACPT-DATE.
ACCEPT W04-DATE FROM DATE.
1000-EXIT.
EXIT.
2000-DISPLAY-DATE.
DISPLAY 'A) ' W04-DD '-' W03-MTH(W04-MM) '-' W04-YY.
DISPLAY 'B) ' W02-MONTH-NAME(W04-MM) ' ' W04-DD ', '
W04-YY.
2000-EXIT.
EXIT.

Example 16.15
Constants can also be defined in the following manner :

01 MONTHS.
05 FILLER PIC X(60) VALUE
“JAN31FEB29MAR31APR30MAY31JUN30JUL31AUG31AEP30OCT
“31NOV30DEC31”.
01 MONTH-TABLE REDIFINES MONTHS.
05 MONTH-DAY OCCURS 12 TIMES.
10 MTH PIC X(03).
10 DAYS PIC 9(02).

Example 16.16

16.1.1 Two-Dimensional Tables

If each entry of a table in turn is a table of one dimension, we have a two dimensional
table. Using the OCCURS clause, we can very easily define multi-dimension tables.

Two-dimensional tables require 2 subscripts to locate an individual entry or field.

Example – 1

Assume a particular state has 3 universities. We wish to set up a table that contains
enrollment figures for each university according to class standing viz. 1YR, 2YR, 3YR,
FYR.

Page 140 of 163


COBOL

The DATA DIVISION entries to represent the above in a two-dimensional table is as


follows:

01 ENROLMENT-TABLE.
05 UNIV OCCURS 3 TIMES.
10 YEAR OCCURS 4 TIMES.
15 ENROLLMENT PIC 9(3).

Example 16.17

Compilation of these data division statements results in the following conceptual


storage layout:

ENROLMENT – TABLE
UNIV-1 UNIV-2 UNIV-3
(1) (2) (3) (4) (1) (2) (3) (4) (1) (2) (3) (4)

Refer examples shown below to illustrate the use of two-dimensional tables.

• ENROLLMENT (1, 1)
• UNIV (1) refers to all the 4 years of university 1.
• ENROLLMENT (1,1) refers to the I year enrollment in the first university.
• Similarly we can have,
o ENROLLMENT (1,2)
o ENROLLMENT (1,3)
o ENROLLMENT (1,4)

Consider the following sales girl input record. Let us assume there are 10 departments
(1 to 10) and 5 sales girls in each dept. (1 to 5). The input record is follows:

01 SALE-TRAN.
05 BILL-NO PIC X(4).
05 DEPT-NO PIC 99.
05 SALE-GIRL-NO PIC 99
05 SALE-VALUE PIC 9(5)V99.

Example 16.18

In order to set up required storage location, the following DATA DIVISION entries can
be written:

01 SG-TOTAL-TABLE.
05 DEPT OCCURS 10 TIMES.
10 SA-GIRL OCCURS 5 TIMES.
15 SA-TOTAL PIC 9(7)V99.

Page 141 of 163


COBOL

Example 16.19

DEPARTMENT
SA-GIRL 01 02 03 04 05 06 07 08 09 10
01
02
03
04
05

To initialize the above two dimensional table, we code as follows in the procedure
division:

PROCEDURE DIVISION.
PERFORM INITIALIZE-DEPT VARYING
DEPT-CTR FROM 1 BY 1
UNTIL DEPT-CTR > 10.
INITIALIZE-DEPT.
PERFORM INITIALIZE-TABLE VARYING
SG-CTR FROM 1 BY 1
UNTIL SG-CTR > 5.
INITIALIZE-TABLE.
MOVE ZERO TO SA-TOTAL (DEPT-CTR, SG-CTR).

Example 16.20

Instead of using nested performs, we can use the PERFORM…VARYING….AFTER.


As given below:

PERFORM INITIALIZE-TABLE
VARYING DEPT-CTR FROM 1 BY 1
UNTIL DEPT-CTR > 10
AFTER SG-CTR FROM 1 BY 1
UNTIL SG-CTR > 5.

Example 16.21

(Note : Sequence of subscripts as specified against a data name should be the


same as specified by the OCCURS clauses.)

SEARCHING AN ARRAY
The following program introduces the logic for searching an array. The program
accepts 5 names into an array. It then accepts a name from the user. Search the array
from the beginning to the end. If the name is found, display the position at which it is
found. Otherwise, display a message ‘Not found’.

Page 142 of 163


COBOL

IDENTIFICATION DIVISION.
PROGRAM-ID. SRCHARR.

ENVIRONMENT DIVISION.

DATA DIVISION.
WORKING-STORAGE SECTION.
01 W01-NAME-ARR.
05 W01-NAMES OCCURS 5 TIMES PIC X(10).

01 W02-SUB PIC 9(02).


01 W03-SIZE PIC 9(02) VALUE 5.

01 W04-FOUND PIC X(01) VALUE 'N'.


01 W05-SRCH-NAME PIC X(10).
01 W06-TEMP PIC X(01).

PROCEDURE DIVISION.
0000-MAIN.
PERFORM 1000-ACPT-NAMES THRU 1000-EXIT
VARYING W02-SUB FROM 1 BY 1
UNTIL W02-SUB > W03-SIZE.

MOVE 1 TO W02-SUB.

DISPLAY 'ENTER NAME TO BE SEARCHED '.


ACCEPT W05-SRCH-NAME.

PERFORM 2000-SRCH-ARR THRU 2000-EXIT


UNTIL W02-SUB > W03-SIZE
OR W04-FOUND = 'Y'.

IF W04-FOUND = 'N'
DISPLAY 'NAME NOT FOUND'.

ACCEPT W06-TEMP.
STOP RUN.
1000-ACPT-NAMES.
DISPLAY 'ENTER NAME - ' W02-SUB.
ACCEPT W01-NAMES (W02-SUB).
Contd.

Page 143 of 163


COBOL

1000-EXIT.
EXIT.

2000-SRCH-ARR.
IF W05-SRCH-NAME = W01-NAMES (W02-SUB)
DISPLAY 'NAME FOUND AT POSITION ' W02-SUB
MOVE 'Y' TO W04-FOUND.

ADD 1 TO W02-SUB.

2000-EXIT.
EXIT.

Example 16.22

INDEXED TABLES :

So far we saw the use of sub-script(s) which were separate numeric data items or
fields of an input record for accessing the various entries of the table. The subscript
data items had to be defined in the DATA DIVISION. Alternately, we could use an
INDEX as a subscript. INDEXes need not be defined separately in the DATA DIVISION.
They are naturally associated with a table thru the OCCURS clause as is illustrated by
the following example :

01 SG-TOTAL-TABLE.
05 SALES-GIRL OCCURS 5 TIMES INDEXED BY SG-COUNTER.
10 SALES-GIRL-TOTAL PIC 9(7)V99.

Example 16.23

The data item specifies in the INDEXED BY clause is automatically defined by


the complier and has USAGE INDEX. The INDEX cannot be used for any other
purpose. A two dimensional table using INDEX is given below:

01 SG-TOTAL-TABLE.
05 DEPT OCCURS 10 TIMES INDEXED BY DEPT-CTR.
10 SA-GIRL OCCURS 5 TIMES INDEXED BY SG-CTR.
15 SG-TOTAL PIC 9(7)V99.

Example 16.24

In a multi-dimension table, if INDEXing is done at one level, it must be done for


all levels. In the above example, therefore, it is an error if INDEXED BY clause is
used for DEPT and not for SA-GIRL.

When a table is declared to be INDEXED by an index item, the index item is


expressed in terms of the displacement values from the beginning of the table.
Consider a table T defined as follows :

Page 144 of 163


COBOL

02 T OCCURS 4 TIMES INDEXED BY I.


03 T-ENTRY PIC X(3).

Example 16.25

Following are the corresponding subscript and index item values :

SUBSCRIPT INDEX ITEM (I)


1 0
2 3
3 6
4 9

I indicates position at which the table entry begins with respect to the beginning of
the table. The I value is 6 for a subscript 3 because the third item in the table begins
at the sixth byte from the beginning of the table.

Index manipulations are done through the SET statement. Arithmetic computations
cannot be done on the index items. MOVE statement cannot be used with index items.
Indexes are used in the binary form.

For example, if S represents a subscript and I an index, then if S contains the value 3,
the statement SET I TO S will result in I being SET to a value 6 (refer above table).
Conversely, if I = 6, the statement SET S TO I will result in S being set to the value
3.

SET I UP BY 1 increases I not by 1 but the unit displacement value determined by


the picture clause. If the PIC clause defines a size of 3, then UP BY1 or DOWN BY 1
changes the index item by 3.

Indexes are processed more efficiently than subscripts. INDEX is stored in a register
during a table operation while a subscript is stored in the main memory and has to be
brought into a register each time it is used.

16.2 The SET verb


The SET verb is a variation of MOVE and provides a way of handling index items.
There are two formats of the SET statement and are shown below:

FORMAT 1 :

SET {index-name-1 [index-name-2] …} TO {index-name-3}


{identifier-1 [identifier-2}……..} {identifier-3}
{integer-1)

Page 145 of 163


COBOL

Example 16.26

If we use index-name-1, we can SET it equal to index-name-3, identifier-3 or integar-


1. If identifier-3 is used, it must be defined as an elementary integer item; if integar-
1 is used, it must be appositive integer. If we use identifier-1 and it has not been
defined by a USAGE IS INDEX clause, it can be SET only to index-name-3.

FORMAT 2 :

SET index-name-1 [index-name-2]….. { UP BY }{ident-1}


{ DOWN BY } { intgr-1}

Example 16.27

We can increase or decrease value of index-name-1 either by a positive integer


(intgr-1) or by the value of ident-1 which must be a data item without the USAGE IS
INDEX clause.

SEARCHING TABLES :

The SEARCH verb is used to perform a linear search on a one dimensional table.
Consider the following example :

DATA DIVISION.
01 SG-TOTAL-TABLE
05 SALES-GIRL OCCURS 5 TIMES INDEXED BY SG-COUNTER.
10 SG-NO-TAB PIC X(5).
10 SG-TOTAL PIC 9(7)V99.
PROCEDURE DIVISION. :
PERFORM ACCUM-SG-TOTAL.
ACCUM-SG-TOTAL.
SET SG-COUNTER TO 1.
SEARCH SALES-GIRL AT END PERFORM NO-FIND-PARA
WHEN WS-SG-NO = SG-NO-TAB (SG-COUNTER) ADD WS-SALE
TO SG-TOTAL (SG-COUNTER).

Example 16.28

NOTE : SEARCH verb is used with tables defined with occurs and INDEXED by
clauses. The value of the INDEX is automatically incremented by 1 every time the
SEARCH is performed.

The AT END is true when the end of the table is reached and not true when the
WHEN conditions were found true. After the AT END is invoked, control passes
to the first statement following the period in the SEARCH statement. Any number

Page 146 of 163


COBOL

of WHEN clauses can be used in a single SEARCH statement. However, it should be


kept in mind that there is an implied OR connecting them.

The format of the SEARCH statement for a linear search is given below:

SEARCH identifier-1 [VARYING {index-name-1}]


{[ { identifier-2} ]
[AT END imperative-statement-1]

WHEN CONDITION-1 {imperative-statement-2}


{ NEXT SENTENCE }
[WHEN condition-2 {imperative-statement-3}]
[ {next sentence }]…

EXAMPLE :

01 NAME PIC X(20).


01 SB-ACCOUNT.
05 ACCOUNT –TABLE OCCURS 400 TIMES
INDEXED BY ACCT-INDEX.
10 ACCOUNT-NO PIC 9(6).
10 ACCOUNT-NAME PIC X(20).
10 ACCOUNT-BAL PIC 9(6)V99.
PROCEDURE DIVISION.
SEARCH-PARA.
SET ACCT-INDEX TO 1.
SEARCH ACCOUNT-TABLE
AT END PERFORM NO-FIND-PARA
WHEN NAME = ACCOUNT-NAME (ACCT-INDEX)
PERFORM FOUND-PARA

. Example 16.29

SEARCH with the VARYI NG option :

This is used to SEARCH two tables in tandem in order to locate corresponding


entries in the two tables. Consider the following tables defined in the working
storage:

Page 147 of 163


COBOL

DATA-TABLE.

01 DATA-TABLE.
05 NAME OCCURS 400 TIMES PIC X(16)
INDEXED BY NAME-INDEX.
05 EMPL-NO OCCURS 400 TIMES PIC 9(4)
INDEXED BY NUMB-INDEX.

Example 16.30

We wish to SEARCH the NAME table to locate a particular name and then obtain
corresponding EMPL-No from the EMPL-no table.

To achieve this, we set both the indexes to 1, we then SEARCH the NAME table,
VARYING the index of the EMPL-NO table. The following PROCEDURES DIVISION
statements are self-explanatory.

SET NAME-INDEX, NUMB-INDEX TO 1.


SEARCH NAME VARYING NUMB-INDEX
AT END PERFORM NO-MATCH-PARA
WHEN WS-NAME = NAME (NAME-INDEX)
MOVE EMPL-NO (NUMB-INDEX) TO WS-EMPL-NO.

Example 16.31

NOTE: Both the indexes must be initialized to 1 before beginning the SEARCH

OCCURS . . DEPENDING ON:

Sometimes, the number of entries in a table varies. The number of entries may be
given by a value stored in a data-name. Consider a bank account-file which has
recorded pertaining to savings-account details of it’s customers. Suppose that some
customers have more transactions than others. Hence it seems natural that records
are of variable length depending upon the number of transactions. Consider the
following file description:

We define the above layout as follows in the FILE SECTION :

FD TRN-FILE.
01 TRN-REC.
05 CUST-NO PIC 9(6).
05 NO-OF-TRAN PIC 9(3).
05 TRAN OCCURS 0 TO 100 TIMES
DEPENDING ON NO-OF-TRAN.
05 TRN-CODE PIC 9.
05 TRN-DATE PIC 9(6).
05 TRN-AMT PIC 9(5)V99.

Page 148 of 163


COBOL

Example 16.32

NOTE : NO-OF_TRAN does not automatically contain the number of the transactions.
It is the responsibility of the program logic to store the proper data in the data
name of the DEPENDING ON clause.

SEARCH ALL statements :

The SEARCH ALL statement is used for performing a binary search on a sorted table.
Hence the OCCURS clause associated with the sorted table should specify the key on
which it is sorted and in what order. A sorted table is created from an input file which
is sorted on the required key either in ascending or descending order. The larger the
table, more is the advantage of using the binary search. In COBOL, binary search on
sorted tables is implemented thru the SEARCH ALL statement. To use the SEARCH ALL
statement, we code as follows :

DATA DIVISION.
:
01 SALES-GIRL-TABLE.
05 SALES-GIRL OCCURS 10 TIMES
INDEXED BY SG-COUNTER
ASCENDING KEY IS SA-GIRL-NO.
10 SA-GIRL-NO PIC 9(3).
10 SG-SALES PIC 9(5)V99.
:
;
PROCEDURE DIVISION.
:
:
ACCUM-SG-TOTAL.

SEARCH ALL SALES-GIRL AT END


PERFORM NOT –FOUND-PARA
WHEN
SALES-GIRL-NO = SA-GIRL-NO(SG-COUNTER)
ADD SALE-VALUE TO SG-SALES(SG-COUNTER).

Example 16.33

The following points may be noted with regards to use of SEARCH ALL on indexed
sorted tables:

1. Initial Setting of INDEX is ignored


2. Duplicate INDEX will indicate first entry.
3. Unpredictable results if table is not sorted.
4. The INDEX name used is the first INDEX

The format of SEARCH ALL statement is :

Page 149 of 163


COBOL

SEARCH ALL identifier-1

[AT END imperative-statement-1]

[ WHEN condition-1 {imperative-statement-2}]


[ { NEXT Sentence } ]…

Example :

01 EMP-TABLE.
05 E-NAME-NO OCCURS 40 TIMES
ASCENDING KEY IS E-NAME
INDEXED BY INDX-1.
10 E-NAME PIC X(10).
10 E-NO PIC 9(02).
PROCEDURE DIVISION.
SEARCH ALL E-NAME-NO AT END
PERFORM NO-FIND-PARA.
WHEN EMPL-NAME = E- NAME (INDX-1) MOVE E-NO (INDX-1) TO EMPL-NO.

Example 16.34

Sample Program

The program reads the students’ marks from a file, whose input records are as shown
below. The marks of the students are output in the output format as shown below.

Note : Tables are used to represent the record structure in the file, and also for
displaying the data in a 2 dimensional output format.

INPUT DATA

STUDENT-1 09051000082306000900089909770777
STUDENT-2 02000732066605920812085503000600

OUTPUT DATA

EXAM PART
STUDENT NAME 1 2 3 4 5 6 7 8
STUDENT-1 90.5 100.0 82.3 60.0 90.0 89.9 87.7 77.7
STUDENT-2 20.0 73.2 66.6 59.2 81.2 85.5 30.0 60.0

Page 150 of 163


COBOL

IDENTIFICATION DIVISION.
PROGRAM-ID GRADES.

ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
SOURCE-COMPUTER.
OBJECT-COMPUTER

INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT INFILE ASSIGN TO ‘EXAM-DAT’
ORGANIZATION IS SEQUENTIAL.

SELECT OUTFILE ASIGN TO ‘SCORES-DAT’


ORGANIZATION IS SEQUENTIAL.

DATA DIVISION.
FILE SECTION.
FD INFILE
01 INREC.
02 STUD-NAME PIC X(10).
02 STUD-MARKS.
03 MARKS-IN OCCURS 8 TIMES PIC 9(3)V9.
FD OUTFILE
01 OUTREC PIC X(75).
WORKING-STORAGE SECTION.
01 EOF-SWITCH PIC X(3) VALUE ‘NO’ .
88 END-OF-FILE VALUE ‘YES’.
01 M USAGE IS INDEX.
01 EXAM-TABLE.
02 STUD-DATA OCCURS 50 TIMES INDEXED BY S.
03 STUD-NAME-W PIC X(10).
03 EXAM-SCORES.
04 SCORE OCCURS 8 TIMES PIC 9(03)V9 INDEXED BY Q.
01 HEADING-1.
02 FILLER PIC X(40) VALUE SPACES.
02 FILLER PIC X(09) VALUE ‘EXAM PART’.
01 HEADING – 2.
02 FILLER PIC X(03) VALUE SPACES.
02 FILLER PIC X(12) VALUE ‘STUDENT NAME’.
02 FILLER PIC X(06) VALUE SPACES.
02 FILLER PIC X(50) VALUE
‘1….2….3….4….5….6….7….8’.

Page 151 of 163


COBOL

01 REPORT-LINE.
02 FILLER PIC X(02) VALUE SPACES.
02 STUD-NAME-R PIC X(10).
02 FILLER PIC X(02) VALUE SPACES.
02 SCORES-R OCCURS 8 TIMES PIC ZZZ99.9
INDEXED BY R.

PROCEDURE DIVISION.
PROG-SUMMARY.
OPEN INPUT INFILE
OUTPUT OUTFILE.
PERFORM READ-EXAM-REC.
PERFORM STORE-RECORD
VARYING S FROM 1 BY 1
UNTIL S > 50
OR END-OF-FILE.
SET S DOWN BY 1.
SET M TO S.

WRITE OUTREC FROM HEADING-1.


WRITE OUTREC FROM HEADING-2 .

PERFORM CHECK-SCORES-AND-PRINT
VARYING S FROM 1 BY 1
UNTIL S > M.
CLOSE INFILE OUTFILE.
STOP RUN.

READ-EXAM-REC
READ INFILE AT END MOVE ‘YES’ TO EOF-SWITCH.

STORE-RECORD.
MOVE STUD-NAME TO STUD-NAME-W (S).
MOVE STUD-MARKS TO EXAM-SCORES (S).
PERFORM READ-EXAM-REC.

CHECK-SCORES-AUD-PRINT.
PERFORM MOVE-SCORES
VARYING Q FROM 1 BY 1 UNTIL Q > 8.
MOVE STUD-NAME-W(S) TO STUD-NAME-R.
WRITE OUTREC FROM REPORT-LINE.
MOVE-SCORES.
SET R TO Q.
MOVE SCORE (S,Q) TO SCORE (R).

Example 16.35

Page 152 of 163


COBOL

17. String Handling


The STRING Statement

A STRING statement may be used to combine several fields to form once concise field.
This process is called concatenation.

Example :

Suppose we want to print a report that lists a company name in columns 5-20, a city
name starting with column 26, 1 blank space, and then the zip code. The source of
data is VENDOR-RECORD.

01 VENDOR-RECORD.
05 COMPANY-NAME PIC X(15).
05 STREET PIC X(40).
05 CITY-STATE PIC X(20).
05 ZIP PIC 9(5).

The data in CITY-STATE are recorded so that the city - name is followed by a comma,
a space and then the state code, i.e., LOS ANGELES, CA.

01 OUTPUT-REC PIC X(132).

We use the STRING verb as follows :

MOVE SPACES TO OUTPUT-REC.


MOVE 5 TO STARTING-PLACE.
STRING COMPANY-NAME DELIMITED BY SIZE
‘ ‘ DELIMITED BY SIZE
CITY-STATE DELIMITED BY ‘,’
SPACE, ZIP DELIMITED BY SIZE
INTO OUTPUT-REC
WITH POINTER STARTING-PLACE.

The first MOVE statement clears the output record buffer.


The second MOVE sets STARTING-PLACE to a value of 5. Thus, the beginning of data
transfer into OUTPUT-REC will begin in column 5 (WITH POINTER STARTING-PLACE).
STARTING-PLACE must be an integer field.

The STRING statement specifies that, in effect, five fields will be transferred:
COMPANY-NAME, the 5-byte nonnumeric literal ’ ‘, CITY-STATE, the
figurative constant SPACE, and ZIP.

Page 153 of 163


COBOL

Thus, starting with column 5 of OUTPUT-REC, COMPANY-NAME is transferred character


by character (DELIMITED BY SIZE) followed by ‘ ‘
CITY-STATE is transferred until a comma is encountered (DELIMITED BY ‘,’). One blank
follows (SPACE) and then the ZIP code.

Note : Use of figurative constants, such as SPACE, ZEROS, or the like, always means
one occurrence of the implied character.

IDENTIFICATION DIVISION.
PROGRAM-ID. CH17EX01.

ENVIRONMENT DIVISION.

DATA DIVISION.
WORKING-STORAGE SECTION.
01 W01-NAME.
05 W01-FNAME PIC X(10).
05 W01-MNAME PIC X(10).
05 W01-LNAME PIC X(10).

01 W02-PRT-NAME PIC X(33).

PROCEDURE DIVISION.
0000-MAIN.
PERFORM 1000-ACPT-NAME THRU 1000-EXIT.
PERFORM 2000-DISP-NAME THRU 2000-EXIT.
STOP RUN.

1000-ACPT-NAME.
DISPLAY 'ENTER YOUR FIRST NAME : '
WITH NO ADVANCING.
ACCEPT W01-FNAME.
DISPLAY 'ENTER YOUR MIDDLE NAME : '
WITH NO ADVANCING.
ACCEPT W01-MNAME.
DISPLAY 'ENTER YOUR LAST NAME : '
WITH NO ADVANCING.
ACCEPT W01-LNAME.

1000-EXIT.
EXIT.

Page 154 of 163


COBOL

2000-DISP-NAME.
STRING W01-FNAME DELIMITED BY SPACE
' ' DELIMITED BY SIZE
W01-MNAME DELIMITED BY SPACE
' ' DELIMITED BY SIZE
W01-LNAME DELIMITED BY SPACE
INTO W02-PRT-NAME.

DISPLAY W02-PRT-NAME.
2000-EXIT.
EXIT.

Example 17.1

If the following contents are entered :


W01-FNAME = THOMAS
W01-MNAME = ALVA
W01-LNAME = EDISON

The contents of W02-PRT-NAME will be THOMAS ALVA EDISON

OVERFLOW Option

The OVERFLOW option specifies the operation(s) to be performed if the receiving field
is not large enough to accommodate the result.

POINTER Option

We may count the number of characters actually moved to the receiving field if it is
initialized at 1.
IDENTIFICATION DIVISION.
PROGRAM-ID. CH17EX02.

ENVIRONMENT DIVISION.

DATA DIVISION.
WORKING-STORAGE SECTION.
01 W01-NAME PIC X(10).
01 W02-PRT-NAME PIC X(15).
01 W03-COUNT PIC 9(01) VALUE 1.

PROCEDURE DIVISION.
0000-MAIN.
PERFORM 1000-ACPT-NAME THRU 1000-EXIT.
PERFORM 2000-DISP-NAME THRU 2000-EXIT.

STOP RUN.
1000-ACPT-NAME.
DISPLAY 'ENTER YOUR NAME : '
WITH NO ADVANCING.
ACCEPT W01-NAME.

Page 155 of 163


COBOL

1000-EXIT.
EXIT.
2000-DISP-NAME.
STRING W01-NAME DELIMITED BY SPACE
INTO W02-PRT-NAME
WITH POINTER W03-COUNT.

DISPLAY 'COUNT : ' W03-COUNT.

2000-EXIT.
EXIT.

Example 17.2

If the contents of W01-NAME is ABC. The contents of W03-COUNT will be 4.

Rules for using the STRING statement

1. The DELIMITED BY clause is required. It can indicate :


SIZE : The entire sending field is transmitted.
Literal : The transfer of data is terminated when the specified literal is
encountered; the literal itself is not moved.
Identifier : The transfer of data is terminated when the contents of the
identifier is encountered.
2. The receiving field must be an elementary data item with no editing
symbols or JUSTIFIED RIGHT clause.
3. All literals must be described as non-numeric.
4. The identifier specified with the POINTER clause must be an elementary
numeric item.
5. The STRING statement moves data from left to right just like
alphanumeric fields are moved, but a STRING does not pad data from
left to right just like alphanumeric fields are moved, but a STRING does
not pad with low-order blanks, unlike an alphanumeric MOVE.

The UNSTRING statement


The UNSTRING statement may be used to convert keyed data to a more compact form
for storing it on disk. For example, we can instruct the computer to separate the
W02-PRT-NAME into its components and store them without the commas.

Page 156 of 163


COBOL

IDENTIFICATION DIVISION.
PROGRAM-ID. CH17EX03.

ENVIRONMENT DIVISION.

DATA DIVISION.
WORKING-STORAGE SECTION.
01 W01-NAME.
05 W01-FNAME PIC X(10).
05 W01-MNAME PIC X(10).
05 W01-LNAME PIC X(10).

01 W02-PRT-NAME PIC X(33).

PROCEDURE DIVISION.
0000-MAIN.
MOVE 'THOMAS,ALVA,EDISON' TO W02-PRT-NAME.
UNSTRING W02-PRT-NAME
DELIMITED BY ','
INTO W01-FNAME
W01-MNAME
W01-LNAME.

PERFORM 1000-DISP-NAME THRU 1000-EXIT.


STOP RUN.

1000-DISP-NAME.
DISPLAY 'FIRST NAME : ' W01-FNAME.
DISPLAY 'MIDDLE NAME : ' W01-MNAME.
DISPLAY 'LAST NAME : ' W01-LNAME.

1000-EXIT.
EXIT.

Example 17.3
Output

FIRST NAME : THOMAS


MIDDLE NAME : ALVA
LAST NAME : EDISON

Rules for using the UNSTRING statement


1. The sending field must be non-numeric. The receiving fields may be
numeric or non-numeric.
2. Each literal must be non-numeric.
3. The [WITH POINTER identifier] and [ON OVERFLOW imperative-
statement] clauses may be used in the same way as with the STRING.

The UNSTRING verb, as its name implies, acts in the reverse direction of the STRING
verb.

Page 157 of 163


COBOL

Here are further two examples to illustrate use of this verb.

Suppose the data are recorded in free form (without predefined fields) as follows:

TED S BROWN,4,15,3.52
TINA LORI CHRISTIANSON,1,12,2,50

As we can see, name fields are separated by 1 or more blank spaces; then commas
separate the remaining three fields. We would like to move these data fields to a
fixed-format record, as shown below:

01 STUDENT-RECORD.
02 FIRST-NAME PIC X(15).
02 MIDDLE-NAME PIC X(15).
02 LAST-NAME PIC X(20).
02 CLASSIFICATION PIC 9.
02 CREDIT-LOAD PIC 99.
02 GPA PIC XXXX.

Assuming that the source data are in

01 FREE-FORM-RECORD PIC X(57).

we can write:

UNSTRING FREE-FORM-RECORD
DELIMITED BY ALL SPACES OR ‘,’
INTO FIRST-NAME
MIDDLE-NAME
LAST-NAME
CLASSIFICATION
CREDIT-LOAD
GPA.

The DELIMITED clause specifies that fields in the source record are separated by 1 or
more blank spaces (ALL SPACES), or single commas (OR ‘,’). When a blank or a comma
appears, it is assumed that a new field begins. The delimiters in this case are blanks
or commas, and they are not included in the data transfer, although the UNSTRING
statement does include an option allowing the transfer of delimiters themselves.

Page 158 of 163


COBOL

The INSPECT statement


The INSPECT statement may be used for replacing a specific character in a field with
another character. It can also be used for counting the number of occurrences of a
given character.

IDENTIFICATION DIVISION.
PROGRAM-ID. CH17EX04.

ENVIRONMENT DIVISION.

DATA DIVISION.
WORKING-STORAGE SECTION.
01 W01-CTR1 PIC 9(01) VALUE ZERO.
01 W02-NAME PIC X(10).

PROCEDURE DIVISION.
0000-MAIN.
PERFORM 1000-ACPT-NAME THRU 1000-EXIT.
PERFORM 2000-CNT-NAME THRU 2000-EXIT.
STOP RUN.

1000-ACPT-NAME.
DISPLAY 'ENTER YOUR NAME : '
WITH NO ADVANCING.
ACCEPT W02-NAME.

1000-EXIT.
EXIT.

2000-CNT-NAME.
INSPECT W02-NAME
TALLYING W01-CTR1 FOR LEADING SPACES.

DISPLAY 'COUNT : ' W01-CTR1.

2000-EXIT.
EXIT.

Example 17.4

This code will check for the number of leading spaces in the field W01-NAME and store
the value in the field W01-CTR1.

Applications of the INSPECT statement


1. To count the number of occurrences of a given character in a field.
2. To replace specific occurrences of a given character with another
character.

Page 159 of 163


COBOL

Examples of the Inspect statement.

1. To replace all blanks by zeros in a field called TEST :

INSPECT TEST REPLACING ALL ‘ ‘ BY ‘0’.

2. To replace the first zero by a +:

INSPECT TEST REPLACING FIRST ‘0‘ BY ‘+’.

3. To find how many dollars are in test :

INSPECT TEST TALLYING COUNT-A FOR ALL ‘$‘ .

After this instruction is executed, the numeric field COUNT-A will contain a value
equal to the number of $ in TEST. Assume COUNT-A has been defined in DATA
DIVISION.

4. To find how many zero characters are there to the left of the decimal point
and how many zeros are there to the right of the decimal point:

INSPECT TEST TALLYING COUNT-A FOR ALL ‘0‘ BEFORE INITIAL ‘.’ COUNT-B FOR ALL ‘0’
AFTER ‘.’.

COUNT-A will contain the number of zeros before the decimal point and COUNT-B will
contain the number of zeros after the decimal point.

5. To count the number of dollar signs in TEST and replace all dollar signs after
the first one by asterisks

INSPECT TEST TALLYING COUNT-A FOR ALL ‘$’ REPLACING ALL ‘$’ BY ‘*’ AFTER INITIAL ‘$’.

6. To find out the actual number of characters in TEST before space is


encountered.

INSPECT TEST TALLYING COUNT-A FOR


CHARACTERS BEFORE INITIAL ‘ ‘.

7. Use the REPLACING option as follows :

INSPECT TEST REPLACING ALL ‘/’ BY ‘0’


‘U’ BY ‘1’
‘I’ BY ‘2’
‘.’ BY ‘9’.

Page 160 of 163


COBOL

8. An integer field ABC of six positions may have leading blanks and a sign. We
want to move the correct numeric value represented in ABC to S-ABC whose PIC
is S9(6). We could write:

MOVE ZERO TO PLUS-SIGN, MINUS-SIGN


INSPECT ABC
TALLYING
PLUS-SIGN FOR ALL ‘+’
MINUS-SIGN FOR ALL ‘—‘
REPLACING
LEADING SPACES BY ZERO
FIRST ‘+’ BY ZERO
FIRST ‘—‘ BY ZERO
IF ABC IS NOT NUMERIC
PERFORM INCORRECT-DATA
ELSE
MOVE ABC TO S-ABC
IF MINUS-SIGN NOT = ZERO
MULTIPLY –1 BY S-ABC.

Two counters, PLUS-SIGN and MINUS-SIGN, are initialized to zero and we use them for
TALLYING the occurrence of + and -, respectively.
We are also REPLACING … FIRST.
If there us more than one sign present, the statement IF ABC IS NOT NUMERIC would
sense the presence of the unconverted extra sign(s).
If the field is unsigned or positive, MOVE ABC to S=ABC is sufficient.
If the field is negative, however, then MINUS-SIGN would have a nonzero value and we
multiply S-ABC by –1 to represent the negative.

9. Suppose that we want to convert all uppercase letters to lowercase. We can


write:

INSPECT TEST REPLACING ‘A’ by ‘a’


‘B’ by ‘b’
.
.
.
‘Z’ by ‘z’.

10. Alternately, we can use the CONVERTING option to achieve the same result
more easily:

INSPECT TEST CONVERTING ‘ABCDEFGHIJKLMNOPQRSTUVWXYZ’ TO


‘abcdefghijklmnopqrstuvwxyz’.

Page 161 of 163


COBOL

18. Appendix –A (Standards)


For the COBOL standards refer to PKMS

QMS

QMS-Manual

Standards

COBOL Standards

Page 162 of 163


COBOL

19. Appendix –B (Bibliography/References)

1. M. K. Roy and D Ghosh Dastidar, COBOL Programming including MS-COBOL and


COBOL-85 – 2nd edition
2. Andreas S. Philippakis and Leonard J. Kazmier, Information Systems through
COBOL – 2nd edition
3. Nancy Stern and Robert A. Stern, Structured COBOL Programming - 7th edition

Page 163 of 163


COBOL

20. Appendix –C (File Status codes)


Successful Completion

* 00 Successful completion - no error occurred


Duplicate alternate record key (when WITH DUPLICATES) is not
* 02 specified

04 Successful read, but length of record does not conform to FD entry


Unsuccessful Completion

* 10 Sequential read attempted, but there are no more input records


* 21 Keys are not in correct sequence
* 22 Attempt to write a record, which will create a duplicate primary
record key
* 23 Required record not found during a READ
* 24 Attempt to write beyond the pre-established boundaries of an
indexed file
* 30 Permanent data error has occurred (hardware problem)
34 Boundary error for a sequential file
37 Permanent error has occurred because an OPEN statement has been
attempted on a file that will not support the mode specified in the
OPEN statement.
39 Error during OPEN execution, due to inconsistency between the file
description and the actual file
41 An OPEN statement has been attempted on a file that is already open.
42 A CLOSE statement has been attempted on a file that has not been
opened
* 43 An attempt has been made to DELETE or REWRITE a record after an
unsuccessful READ
44 A boundary violation due to attempt to WRITE or REWRITE a record of
improper length
46 Attempt to read the next nonexistent record
47 Attempt to READ from a file not open in INPUT or I-O mode
48 Attempt to WRITE from a file not open in OUTPUT or EXTEND mode
49 Attempt to REWRITE on a file not open in I-O mode

* apply specifically to indexed files.

Page 164 of 163


COBOL

21. Appendix – D (Syntax)


RULES FOR INTERPRETING INSTRUCTION FORMATS

Uppercase words are COBOL reserved words that have special meaning to the
compiler.
Underlined words are required in the paragraph.
Lowercase words represent user-defined entries.
Braces { } denote that one of the enclosed items is required.
Brackets [ ] mean the clause or paragraph is optional.
If punctuation is specified in the format, it is required.
The use of dots or ellipses (...) means that additional entries of the same type may be
included if desired.

IDENTIFICATION DIVISION.
PROGRAM-ID. Program-name.
[AUTHOR. [Comment-entry]....].
[INSTALLATION. [Comment-entry]....].
[DATE-WRITTEN. [Comment-entry]....].
[DATE-COMPILED. [Comment-entry]....].
[ SECURITY. [Comment-entry]....].

ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
SOURCE-COMPUTER. computer-name.
OBJECT-COMPUTER. computer-name.

INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT file-name-1
ASSIGN TO implementor-name-1
[ ORGANIZATION IS ] SEQUENTIAL
INDEXED
ACCESS MODE IS SEQUENTIAL
RANDOM
DYNAMIC

RECORD KEY IS data-name-1


[ ALTERNATE RECORD KEY IS data-name-2
[ WITH DUPLICATES ] ] ...
[ FILE STATUS IS data-name ] .

Page 165 of 163


COBOL

DATA DIVISION.
FILE SECTION.
FD file-name-1
LABEL RECORD IS OMITTED
RECORD ARE STANDARD

RECORD CONTAINS integer-1 CHARACTERS


BLOCK CONTAINS integer-1 RECORDS .

01 record-name-1.

WORKING-STORAGE SECTION.
(level-number 02-49) identifier-1 OCCURS integer-1 TIMES

ASCENDING KEY IS data-name-2


DESCENDING

INDEXED BY index-name-1

LINKAGE SECTION.

PROCEDURE DIVISION.

OPEN INPUT
OUTPUT file-name-1 ...
I-O
EXTEND

READ file-name-1
[ AT END statement-1...] .

READ file-name-1 NEXT RECORD


[ AT END statement-1...] .

READ file-name-1
[ INVALID KEY statement-1...] .

READ file-name-1
KEY IS alternate-record-keyname
[ INVALID KEY statement-1...] .

WRITE record-name-1 [ FROM identifier-1 ]


AFTER ADVANCING PAGE LINE
BEFORE integer-1 LINES
identifier-2

WRITE record-name-1 [ FROM identifier-1 ]


[ INVALID KEY imperative-statement-1] .

REWRITE record-name-1 [ FROM identifier-1 ]


[ INVALID KEY imperative-statement-1 ] .

Page 166 of 163


COBOL

DELETE indexed-file-name-1 RECORD


[ INVALID KEY imperative-statement-1 ] .

START file-name-1 KEY IS EQUAL TO data-name-1


IS =
IS GREATER THAN
IS >
IS NOT LESS THAN
IS NOT <
[ INVALID KEY imperative-statement-1 ]

CLOSE file-name-1... .

DISPLAY identifier …
literal-1
[ WITH NO ADVANCING ]

ACCEPT identifier-1
[ FROM mnemonic-name-1]

GO TO paragraph-name-1.

PERFORM procedure-name-1 .

PERFORM procedure-name-1
UNTIL condition-1.

PERFORM paragraph-name-1 THROUGH paragraph-name-2


THRU

PERFORM paragraph-name-1 THROUGH paragraph-name-2


THRU
UNTIL condition-1.

PERFORM paragraph-name-1 THROUGH paragraph-name-2


THRU
integer-1 TIMES .
identifier-1

PERFORM paragraph-name-1 THROUGH paragraph-name-2


THRU
VARYING identifier-2 FROM identifier-3 BY identifier-4
index-name-1 literal-1 literal-2
index-name-2
UNTIL condition-1

AFTER identifier-5 FROM identifier-6 BY identifier-7


index-name-3 literal-3 literal-4
index-name-4
UNTIL condition-2

STOP RUN.

Page 167 of 163


COBOL

MOVE identifier-1 TO identifier-2


literal-1

MOVE CORRESPONDING group-item-1 TO group-item-2


CORR

ADD identifier-1 ... TO identifier-2 ...


literal-1

ADD identifier-1 ... GIVING identifier-2 ..


literal-1

SUBTRACT identifier-1 ... FROM identifier-2 ...


literal-1

SUBTRACT identifier-1 ... FROM identifier-2


literal-1 literal-2
GIVING identifier-3 ...

MULTIPLY identifier-1 BY identifier-2 ...


literal-1

MULTIPLY identifier-1 BY identifier-2


literal-1 literal-2
GIVING identifier-3 ...

DIVIDE identifier-1 INTO identifier-2 ...


literal-1

DIVIDE identifier-1 INTO identifier-2


literal-1 literal-2
GIVING identifier-3 ...
[ REMAINDER identifier-4 ]

DIVIDE identifier-1 BY identifier-2


literal-1 literal-2
GIVING identifier-3 ...
[ REMAINDER identifier-4 ]

COMPUTE identifier-1 [ ROUNDED ] ... = arithmetic expression-1


literal-1
identifier-2
[ ON SIZE ERROR imperative statement ]

IF condition
statement-1...
[ ELSE
statement-2 ... ] .

Class Test NUMERIC


ALPHABETIC

Page 168 of 163


COBOL

Sign Test POSITIVE


NEGATIVE
ZERO

SEARCH identifier-1 VARYING identifier-2


index-name-1
[ AT END imperative-statement-1 ]
WHEN condition-1 imperative-statement-2 ...
NEXT SENTENCE

SET index-name-1 TO integer-1


UP BY
DOWN BY

SEARCH ALL identifier-1


[ AT END imperative-statement-1 ]
WHEN data-name-1 IS EQUAL TO identifier-2
IS = literal-1
arithmetic-expression-1
condition-name-1
AND data-name-2 IS EQUAL TO identifier-3
IS = literal-2
arithmetic-expression-2 …
condition-name-2

imperative-statement-2
NEXT SENTENCE

COPY text-name OF library-name-1


IN

==pseudo-text-1== ==pseudo-text-2==
identifier-1 identifier-2
REPLACING literal-1 BY literal-2 ...
word-1 word-2

CALL literal-1 [ USING identifier-1 ... ]

EXIT PROGRAM.

INSPECT identifier-1 TALLYING


identifier-2 FOR ALL identifier-3
LEADING literal-1
CHARACTERS

BEFORE INITIAL identifier-4 ...


AFTER literal-2

Page 169 of 163


COBOL

INSPECT identifier-1 REPLACING

CHARACTERS
ALL identifier-2
LEADING literal-1
FIRST

BY identifier-3 BEFORE INITIAL identifier-4 ...


literal-2 AFTER literal-3

SORT file-name-1
ON DESCENDING KEY data-name-1 ...
ASCENDING
USING file-name-2
INPUT PROCEDURE IS procedure-name-1 THRU procedure-name-2
THROUGH

GIVING file-name-3
OUTPUT PROCEDURE IS procedure-name-1 THRU procedure-name-2
THROUGH

RELEASE sort-record-name-1
[ FROM identifier-1 ]

RETURN sort-file-name-1
AT END imperative-statement-1

STRING identifier-1 DELIMITED BY identifier-2


literal-1 literal-2 ...
SIZE
INTO identifier-3

[ WITH POINTER identifier-3 ]

UNSTRING identifier-1 DELIMITED BY [ALL] identifier-2


literal-1
OR [ALL] identifier-3
literal-2 ...

INTO identifier-4

[ WITH POINTER identifier-3 ]

Page 170 of 163

Вам также может понравиться