Sei sulla pagina 1di 272

Table of Contents

UNIT 1. Introduction to Language Features COMMON BUSINESS ORIENTED LANGUAGE


COBOL PROGRAM ORGANIZATION
COBOL LANGUAGE STRUCTURE
STRUCTURE OF
COBOL PROGRAM
CHARACTER SET OF COBOL
SAMPLE COBOL PROGRAM
CODING
FORMAT
USER-DEFINED WORDS
UNIT 2. The Organization of a COBOL Program
IDENTIFICATION DIVISION
ENVIRONMENT DIVISION DATA DIVISION
DATA-ITEMS
LEVEL NUMBERS
LEVEL NUMBERSW-S DECLARATIONS FILLER
PICTURE CLAUSE
USAGE CLAUSE
CLAUSE
REDEFINES CLAUSE DULPICATE DATA NAMES
RENAMES CLAUSE
FIGURATIVE CONSTANTS EDITED FIELDS
MORE EDITING CHARACTER
EXAMPLES

SPECIAL
VALUE

UNIT 3. PROCEDURE DIVISION


PROCEDURE DIVISION
COBOL VERBS
PARAGRAPHS
TERMINATOR STATEMENTS
SCOPE TERMINATORS
DISPLAY VERB
ACCEPT VERB
MOVE VERB
ELEMENTARY
& GROUP MOVES CORRESPONDING PHASE
REFERENCE MODIFICATION
ADD VERBADD
CORRESPONDING STATEMENT
ON SIZE ERROR PHRASE
NUMERIC DATA
SUBTRACT
VERB SUBTRACT CORRESPONDING STATEMENT MULTIPLY VERB
DIVIDE VERB
COMPUTE
STATEMENT
PERFORM STATEMENT
PERFORM THROUGH PERFORM N TIMES PERFORM
VARYING
IN-LINE PERFORM
RELATIONAL EXPRESSIONS
IF STATEMENT
COMPOUND
CONDITIONALS CLASS CONDITION CONTINUE & NEXT STATEMENT EVALUATE STATEMENT
SET TO TRUE
INITIALIZE

UNIT 4. FILE HANDLING IN COBOL


FILES
FIXED VS VARIABLE LENGTH RECORDS
FILE-CONTROL-SEQUENTIAL
ACCESS MODE
FILE STATUS CLAUSE
I-O CONTROL PARAGRAPH
FILE SECTION
FILE OPERATIONS
OPEN MODES
READ-SEQUENTIAL ACCESS
END OF FILE PROCESSING
READ RANDOM ACCESS
READ DYNAMIC ACCESS
START STATEMENT
WRITE STATEMENT
WRITEFROM
READINTO
REWRITE & DELETE
APPENDING TO SEQUENTIAL FILES
FILE COMPARISON
CLOSE STATEMENT
SEQUENTIAL FILES
INDEXED FILES
INVALID KEY
ACCESS MODE: SEQUENTIAL & RANDOM
ACCESS MODE: DYNAMIC
RELATIVE FILES

UNIT 5. TABLE HANDLING


INTRODUCTION: TABLE HANDLING
OCCURS CLAUSE
SUBSCRIPT
INDEXING
ONE DIMENSIONAL TABLE
TWO DIMENSIONAL TABLE
MULTIDIMENTIONAL TABLE
TABLE-SORTING
SET
SEARCH
BINARY SEARCH

UNIT 6. Library Services


COPY STATEMENT
NESTED COPY
COPY REPLACING
COPY PSEUDO-TEST
REPLACE PSEUDO-TEST

UNIT 7. CHARACTER HANDLING


STRING
UNSTRING STATEMENT
INSPECT TALLYING STATEMENT
INSPECT REPLACING STATEMENT
EXAMINE STATEMENT

UNIT 8. SORT / MERGE


SORT/MERGE
SORT STATEMENT
MERGE STATEMENT
SORT PROCEDURES
RELEASE STATEMENT
RETURN STATEMENT

UNIT 9. CALL and LINKAGE


CALL STATEMENT
CALL BY CONTENT/REFERENCE
LINKAGE SECTION

UNIT 1

Introduction To Language Features

Common Business Oriented Language


1959 New Language is named
COBOL
1960 Codasyl established
COBOL maintenance committee
1961 1st version of complier
made available. Users started
writing programs

1968 2nd version of cobol was


approved and standardized by
ANSI
1974 Revised and released as
COBOL-74
1985- Revised and released as
COBOL-85

To meet the increasing demands for a high level language suitable for business data processing, the
United States Department of Defense Convened a Conference on 28th and 29th of May 1958.
Three committee were formed for the actual design of the language.
In September 1959 the short term committee submitted a report to the Defense Directorate thus
COBOL came into existence.
COBOL is known as a structured programming language because it allows programmers to
segregate the modules and put them into different paragraphs in a more efficient way.
Some of the features of COBOL are
It is English-like and more easily readable
Efficient file handling capabilities.
More than 70% of business applications are running on COBOL
Reduces the efforts required for documentation of the program.

The following features are available with VS COBOL II:


- MVS/XA and MVS/ESA support
- The compiler and the object programs it produces can be run in either 24- or 31-bit
addressing mode
COBOL PROGRAM ORGANIZATION

IDENTIFICATION DIVISION
ENVIRONMENT DIVISION
DATA DIVISION
PROCEDURE DIVISION

Notes:
The four divisions of the COBOL source program are :

IDENTIFICATION DIVISION

This divisions primary purpose is to name the program

ENVIRONMENT DIVISION

This division is primarily used to tell the computer about the input and output devices such
as files or printers.

DATA DIVISION
This division describes the data the program will be using and carves out sections
of memory to map the data. Here you would distinguish between data, which
will be used for a scratch pad area called WORKING-STORAGE and the
holding area for data that will be used by the files.

PROCEDURE DIVISION
The PROCEDURE DIVISION is the section of our program where the logic or
commands reside. This is the logic or rules we will use to manipulate the data
defined in the DATA DIVISION to solve a business problem.

Cobol Language Structure


.

Characters
Character String
COBOL Words
User-Defined Words
Reserved Words
Figurative Words
Special Registers
IBM Extensions
Non-numeric and numeric Literals

Structure of a Cobol Program


Examples

Divisions

Sections or Paragraphs
Statements

Sentences

DATA DIVISION
PROGRAM-ID
FILE SECTION, 100-PARA
MOVE A TO B
IF A>B MOVE A TO B ELSE
ADD C TO D

Notes:
All COBOL programs should follow the structure. Rules of coding varies, depending
on the compiler versions but the structure remains same. A period (.) is a must at the end of
each sentence and indicates the end of the sentence.

Character Set of COBOL

COBOL supports the following characters


Numbers

0-9

Alphabets

a-z, A-Z

Arithmetic operators

ex: **, *, +, -, /

Special characters

ex: - \ / , ;

Spaces or blanks

Notes:
The COBOL dictionary words used for coding are called COBOL reserved words and
they should not be used as user-defined words. Lower case alphabets can be used for coding
depending on the compiler version.comma (,) or space is used as separators for user-defined
words.

Sample COBOL Program


Columns
1
6 7 8 11 12
* This is a sample program

72 73

80

IDENTIFICATION DIVISION.
PROGRAM-ID. SAMPLE.
ENVIRONMENT DIVISION.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 A PIC 9(2) VALUE 20.
01 B PIC 9(2) VALUE 3O.
01 C PIC 9(3) VALUE ZEROS.
PROCEDURE DIVISION.
DISPLAY THE SUM IS.
ADD A ,B GIVING C.
DISPLAY C.
STOP RUN.
Notes:
1-6 -------------- Sequence numbers
7
-------------- Indicator/Comment/Continuation
8-11 -------------- Area A
12-72 -------------- Area B
73-80 -------------- Descriptor
This foil shows a sample COBOL program to ADD two numbers and DISPLAY the sum.
SAMPLE is the program name.
SAMPLE, A, B AND C are called user-defined words.
A, B,C are called variables or data-items.

Coding Format

Columns

Name
01-06

Purpose
Sequence

07
Indicator
08-11
Area A
12-72
Area B
73-80
Description

Sequence numbers are


generated by Cobol Compiler
for each line.
To mark an asterisk (*) or a
slash (/) for comment line, or a
hyphen (-) for continuation of
a statement.
All division headings, section
and paragraph headings and
01 level entries should begin
from this area.
All Cobol statements and
sentences should lie within
this area
Any thing written in this area
is ignored.

Notes:
COBOL coding should follow the standard format.
The Screen is divided into different areas for the purposes explained above.
All statements indicating action are called COBOL verbs and should begin from 12 th column or after.
-E.g
MOVE, ADD, DIVIDE, STOP RUN

User-defined Words

Valid

Invalid

TOTAL-OF-FIGURES
34B100-PARA1
GROSS-PAY

DATA
-48B
GROSS PAY

Reason
Cobol reserved word
Hyphen in beginning
space in b/w 2 words

Literals

Examples

Numeric constants
Alphanumeric constants

35, -345.67
Leo talstoy
ka01-h215

Paragraph names, Identifiers, File names can be defined by users.


The terms identifiers, data-names, variables, data-items are often used
interchangeably indicates memory.

Notes:

All user-defined words should conform to following rules

Length should not exceed 30 characters.


At least one character must be an alphabet.
Spaces and special characters are not allowed.
Word can contain hyphens (-) but not in the beginning or at the end
Cannot be a COBOL reserved word

UNIT 2

THE ORGANIZATION OF A COBOL PROGRAM

IDENTIFICATION DIVISION
IDENTIFICATION DIVISION.
PROGRAM-ID. <Pgm-name>
AUTHOR.
<Pgmr-name>
DATE WRITTEN. <Entry>
DATE-COMPILED. <Entry>
SECURITY. <Entry>

Required
Required
Optional
Optional
Optional
Optional

At least one space required after the period

Notes:
The Identification Division must be the first division in every COBOL source program.
It must be coded as IDENTIFICATION DIVISION or ID DIVISION followed by a
separator period.

ENVIRONMENT DIVISION
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
SOURCE-COMPUTER. <Entry>.
OBJECT-COMPUTER. <Entry>.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
------------------------------------------------------I-O-CONTROL.
--------------------------------------------------------Notes:
The Environment Division is divided into two sections:

The CONFIGURATION SECTION


The Configuration Section is an optional section for programs which describe
the computer environment on which the program is compiled and executed.
The Configuration Section can be specified only in the ENVIRONMENT DIVISION
of the outermost program of a COBOL source program.

The INPUT-OUTPUT SECTION


The Input-Output Section of the Environment Division contains two paragraphs:
FILE-CONTROL paragraph
I-O-CONTROL paragraph

FILE-CONTROL paragraph

The keyword FILE-CONTROL can appear only once, at the beginning of the FILE-CONTROL
paragraph. It must begin in Area A, and be followed by a separator period.
The FILE-CONTROL paragraph is optional.
The FILE-CONTROL paragraph associates each file in the COBOL program with an
external dataset, and specifies file organization, access mode, and other information.
There are three formats for the FILE-CONTROL paragraph:
QSAM, SAM, and VSAM sequential file entries
VSAM indexed file entries VSAM relative file entries.
The FILE-CONTROL paragraph begins with the word "FILE-CONTROL", followed by a
separator period. It must contain one and only one entry for each file described in an FD or SD
entry in the Data Division. Within each entry, the SELECT clause must appear first, followed
by the ASSIGN clause. The other clauses can appear in any order.

I-O-CONTROL paragraph
Specifies information needed for efficient transmission of data between
the external data set and the COBOL program. The series of entries must
end with a separator period
The keyword I-O-CONTROL can appear only once, at the beginning of the
paragraph. The word I-O-CONTROL must begin in Area A, and must
be followed by a separator period.
Each clause within the paragraph can be separated from the next by
a separator comma or a separator semicolon. The order in which
I-O-CONTROL paragraph clauses are written is not significant

DATA DIVISION
Data division is the third and most frequently used division in all programs. Every variable
required by the program should be declared in appropriate section of the data division,
before using in procedure division
The Data Division is divided into three sections:
.

File Section
Defines the structure of data files (including sort-merge files).

Working-Storage Section
Describes records and subordinate data items that are not part of data
files but are required by the program.

. Linkage Section
Describes data made available by another program. It usually appears in the called
program and describes data items that are referred to by the calling and
the called programs.
Each section has a specific logical function within a COBOL source program, and each
can be omitted from the source program when that logical function is not needed.
If included, the sections must be written in the order shown.

DATA DIVISION.
FILE SECTION.
FD .

---------------------------------------------

WORKING-STORAGE SECTION.
01 VAR-1
01 ID-1
01 DATA-NAME

Level number

PIC
PIC
PIC

picture
Clause

LINKAGE SECTION.
record-description-entry
data-item-description-entry

DATA TYPES
A(5).
-Alphabetic
X(10)
-Alphanumeric
9(5)
-Numeric

data type (length)

DATA-ITEMS

Explicitly identifies the data being described


The data-item must be the first word following the level-number.
The data-item values can be changed during program execution.
A data-item name cannot be the same as a section-name or a paragraph

Notes:
Data item is a user-defined word which is associated with Level number.
COBOL Reserved words should not be Data items .

Level Numbers

Range of level numbers available are 01 to 49 and


66 level specified for RENAMING CLAUSE
77 levels specified exclusively for elementary item
88 levels specified for CONDITION NAMES.

.
.

An elementary item can be declared with level numbers


01 and 77 01 and 77 level entries must begin from area A and other level entries can begin
from any where in area A or area B
Notes:
Level represents the nature of a data item.
The level-number specifies the hierarchy of data within a record, and identifies special-purpose data entries. A
level- number begins a data description entry, a renamed or redefined item, or a condition-name entry. A levelnumber has a value taken from the set of integers between 01 and 49, or from one of the special level-numbers,
66, 77, or 88.

Level-number 01 and 77 must begin in Area A and must be followed either by a separator period;
or by a space, followed by its associated data-name, FILLER, or appropriate data description clause.
Level numbers 02 through 49 can begin in Areas A or B and must be followed by a space or
a separator period.
Level number 66 and 88 can begin in Areas A or B and must be followed by a space.
Single-digit level-numbers 1 through 9 can be substituted for level-numbers
01 through 09.
Successive data description entries can start in the same column as the first or they can be indented according to the levelnumber. Indentation does not affect the magnitude of a level-number.
When level-numbers are indented, each new level-number can begin any number of spaces to
the right of Area A. The extend of indentation to the right is limited only by the width of Area B.
Higher numbered level(s) represent subordinate definition(s).
Level numbers need not be consecutive(but should be in ascending order)

Special Level Numbers


LEVEL-66 contains a RENAMES clause. It regroups previously defined names
LEVEL-77 defines ELEMENTARY items with no subdivision and are unique
LEVEL-88 establishes condition-name entries, associated with a VALUE clause
66 data-name-1 renames-clause.
88 condition-name-1 value-clause.
Notes:
LEVEL-66 regroups previously defined items.
A level-66 entry cannot rename another level-66 entry, nor can it rename a level-01,
level-77, or level-88 entry.
All level-66 entries associated with one record must immediately follow the last
data description entry in that record.
LEVEL-77 items are ELEMENATARY items with no subdivision. LEVEL-77 names
are unique because they can not bequalified.
LEVEL-88 describes condition-names.
LEVEL-88 can be used to describe both elementary and group items .

Picture Clause
Describes the characteristics of the data

CODE
A
B
G or N
9
X
P
V
S

Meaning
Alphabetic or space
Blanks or spaces
Graphical data
Indicates a Numeric
Indicates an Alpha Numeric
Indicates the position of the assumed
Decimal point when the point lies
Outside the data item.
Indicates the position of assumed
Decimal point of numeric field.
Indicates whether the data item signed.

Notes:
Picture clause specifies the data type of an identifier.
Identifier with PIC clause 9 implies that it is numeric data type, which can take art in arithmetic
computations. V and S clauses are allowed with numeric data types only.
X clause represents an alphanumeric data type which can hold any character including numbers also.
A clause indicates an alphabetic data type.
Group items are always considered as alphanumeric only. Therefore GROSS-PAY, DEDUCTIONS can
not be used for computations

W-S Declarations
WOKING-STORAGE SECTION.
01 PAY.
05 GROSS-PAY.Alternatively
10 BASIC PIC 9(4)V99.
10 DA
PIC 9(4)V99.9(4)V9(2)
10 HRA
PIC 9(4)V999999V99
05 DEDUCTIONS.
07 PF-DED PIC
07 IT-DED PIC
05 NET-PAY
PIC
05 NAME
PIC
05 E-CODE
PIC

9(3)V99.
9(3)V99.
9(4)V99.
A(5).AAAAA
X(6).XXXXXX

Notes:
Pay, gross-pay, deductions are called group items and they dont have PICTURE clause. Other elements with
picture clause are called elementary items, which cannot be broken further.
Pay is a Group item is divided into Gross-pay, Deductions, net-pay, name, e-code further Gross-pay sub-divided
into Basic, DA, HRA and DEDUCTIONS sub-divided into PF-DED and IT-DED.

FILLER
FILLER is a COBOL Reserved Word used to describe data fields that will not
be referenced in the PROCEDURE DIVISION.
If the data-name of FILLER clause is omitted, the data item being described is treated as
though it was FILLER
01 EMPLOYEE-RECORD.
05 EMPLOYEE-TYPE
05 EMPLOYEE-SERIAL
05 EMPLOYEE-NAME
05
05 EMPLOYEE-ADDRESS
05 FILLER

PIC X.
PIC X(6).
PIC X(30).
PIC X(2).
PIC X(60).
PIC X(34).

Notes:
FILLER is a data item that is not explicitly referred to in a program. The key word FILLER is optional.
If specified, FILLER must be the first word following the level-number.
IF data-name or FILLER clause is omitted, the data item being described is treated as though FILLER had been
specified.
The VALUE clause may be used on FILLER items, e.g. to assure BLANKS in header lines between fields.
In a MOVE CORRESPONDING statement ,or in an ADD CORRESPONDING or SUBTRACT
CORRESPONDING statement ,FILLER items are ignored.
In an INITIALIZE statement, elementary FILLER items are ignored.

USAGE Clause
<level number> data-name [PIC
X(n)] [USAGE]
COMP
COMP-1
COMP-2
COMP-3
COMP Binary Representation
Size:
Half/Full/Double word
COMP-1 Hexa Decimal Representation Size:
Full word for Float
COMP-2 COMP-3 Where n is number of digits.
Notes:

Hexa Decimal Representation Size:


for float
Packed Decimal Representation Size:

Double word for Float


round(n/2)+1

The USAGE clause can be specified for a data description entry with a level-number other than 66 or 88.
However, if it is specified at the group level, it applies to each Elementary item in the group. The usage
of an elementary item must not contradict the usage of a group to which the elementary item belongs.
The USAGE clause specifies the format in which data is represented in storage. The format can be restricted
if certain Procedure Division statements

When the USAGE clause is not specified at either the group or elementary level, it assumed
that the usage is DISPLAY

Computational ( COMP) Usage


When usage is specified as COMP, the numeric data item is represented in pure binary. The item
must be an integer( no assumed decimal point is allowed). Such that data items are often used
as subscripts.The PICTURE of a COMP item should not contain any character other than 9, S.

COMPUTATIONAL-1 (COMP-1) Usage


If the usage of a numeric data item is specified as COMP-1, it will be represented in one word
in the floating point form. The number is actually represented in Hexa decimal (base 16).
Such representation is suitable for arithmetic operations. The PICTURE clause cannot be specified
for COMP-1 items.

COMPUTATIONAL-2(COMP-2)Usage
This usage is same as COMP-1, except that the data is represented internally in two words.
The advantages is that this increases the precision of the data which means that more significant
digits can be available for the item. The PICTURE clause cannot be specified for COMP-2 items.

COMPUTATIONAL-3(COMP-3)Usage
In this form of internal representation the numeric data is the decimal form, but one digit
takes half-a-byte. The sign is stored separately as the right most half a-byte regardless of whether
S is specified in the PICTURE or not. The hexa decimal number C or F denotes a positive sign
and the Hexa decimal number D denotes a negative sign. Inorder that data fields can start and end
on byte boundaries, numbers with an even number of digits are stored with an extra half-byte of
zeroes on the left hand side.

PICTURE

S9(5)V9(3)

USAGE IS COMP-3

Will require 5 bytes to be stored internally. Only the characters 9,S, V and P can be used in the
PICTURE of a COMP-3 item.

Value Clause

Value Clause defines the initial value of a data item


Must not be used for items declared in FILE SECTION.
Can also specify FIGURATIVE CONSTANTS.
If defined at the group level can be used for array declaration also

EXAMPLES.
01 NUM-1
PIC 9(3)
VALUE 245.
01 E-CODE
PIC X(6)
VALUE E10K3.
At group level

contents

01 GROUP-ITEM
VALUE IS ER34155
05 E-ITEM-1
PIC X(2).
ER
05 E-ITEM-2
PIC XXX
341
05 E-ITEM-3
PIC X(3)

55

Group item is considered as alphanumeric.

Notes:
Assigning values to identifiers is called initialization. If variables are not initialized, then they
may contain any value, which was stored at the time of last execution of program. It is advised to always
working-storage variables.

initialize

REDEFINES Clause
Two or more data items can share the same working storage area by
REDEFINING a storage area.
Level number data name-1 REDEFINES data-name-2

Level numbers of data-name-1 and data-name-2 must be identical


The redefines clause must immediately follow data-name-I
must not be used for level number 66 or 88 items.
Data-name-1 should not contain VALUE clause
Multiple redefinition is allowed

Notes:

Two or more storage areas defined in the data sometimes may not be used simultaneously, in such
cases, only one storage area can serve the purpose of two or more areas if the area is defined.
The REDEFINES clause used allows the said area to be referred to by more than one data name
with different sizes and pictures.

ILLUSTRATES REDEFINES CLAUSE


DATA DIVISION.
WORKING-STORAGE SECTION.
01
X1
02
Y
PIC
99.
02
Y1
REDEFINES Y
PIC
01
X3
02
Z
PIC X
VALUE M.
02
ZZ
PIC X (25) VALUE ALL *.
02
ZZZ
PIC X (45) VALUE ALL - .
01
X4
REDEFINES X3.
02
FILL1
PIC X.
02
FILL2
PIC X (70).
01
X5
REDEFINES X4.
02
BUFFER PIC X (71).
PROCEDURE DIVISION
PARA 1.
MOVE 20 TO Y.
DISPLAY X1.
MOVE A1 TO Y1.
DISPLAY X1
DISPLAY X3.
DISPLAY X4.

DISPLAY X5.
STOP RUN.

XX.

Duplicate Data Names


Are allowed, provided they belong to a group item
01 Pay-Rec.
02 Id-numbers

02 Name
02 Dept
01 Print-Rec.
02 Filler
02 Id-numbers
02 Filler
02 Name
02 Dept

PIC 9(5).

PIC X (25).
PIC X (20).
PIC X (5).
PIC X (5)
PIC X (5).
PIC X (25).
PIC X (920).

MOVE Id-Numbers (OF | IN) Pay-Rec TO Id-Numbers (OF | IN)Print-Rec.


* OF and IN are called Qualifiers.
To move the data stored in the four fields of Pay-Rec. the four MOVE statements serve the purpose.
Using the MOVE CORRESPONDING statement the same can be accomplished.

RENAMES Clause
Syntax:
66 data-name-1 RENAMES data-name-2 THRU data-name-3
E.g. :
01

66
66

PAY REC.
02 FIXED-PAY.
05 BASIC
PIC
9(6) V99.
05 DA
PIC
9(6) V99.
02 ADDITIONAL-PAY.
05 HRD
PIC
9(4) V99.
05 INCENT
PIC
9(3) V99.
02 DEDUCTIONS.
05 PF
PIC
9(3) V99.
05 IT
PIC
9(4) V99.
05 OTHER
PIC
9(3) V99.
PAY-OTHER-THAN-BASIC RENAMES DA THRU INCENT.
IT-AND-PF-DEDUCTIONS RENAMES PF THRU IT.

ILLUSTRATES RENAMES CLAUSE


DATE DIVISION.
WORKING-STORAGE SECTION.
01
PAY
02
FIXED-PAY
10
E-BASIC
PIC 9(6). 99
10
E-DA
PIC 9(6). 99.
05
ADDL-PAY.
10 HRA
PIC 9(4). 99.
10 INCENTIVE
PIC 9(3). 99.
05
DEDUCTIONS.
10
E-PF
PIC 9(3). 99.
10
E-IT
PIC 9(4). 99.
10
OTHERS
PIC 9(3). 99.
66
PAY-LESS-BASIC RENAMES E-DA THRU INCENTIVE.
66
IT-AND-PF RENAMES E-PF THRU E-IT.

PROCEDURE DIVISION.
MAIN-PARA
MOVE-123456.78 TO E-BASIC.
MOVE 234567.89 TO E-DA.
MOVE 1234.56 TO HRA.
MOVE 123.45 TO INCENTIVE.
MOVE 123.45 TO E-PF.
MOVE 1234.56 TO E-IT.
MOVE 123.45 TO OTHERS.
DISPLAY PAY.
DISPLAY FIXED-PAY.
DISPLAY ADDL-PAY.
DISPLAY DEDUCTIONS.
DISPLAY PAY-LESS-BASIC.
DISPLAY IT-AND-PF.
STOP RUN.

Figurative Constants

Constants frequently used by most programs


Figurative Constants

Meaning

HIGH-VALUE(S)

Represents the highest and lowest

LOW-VALUES (S)

value in the collating sequence.

ZERO, ZEROS, ZEROES

One or more Zeroes

SPACE (S)

Example

One or more blanks

01 ID-1 PIC X(3) VALUE SPACES.

Collating sequence is the order in which the characters are compared


by the system.
Notes:
Figurative constants are reserved words that name and refer to specific constant values.

Edited Fields

Move 345.46 to a field of picture 9(3)v99 & display or print


You may see different number in result

Characters must be edited before report is taken to suppress leading


zeros, to include currency signs or to include date separators.

Editing Codes
Z
*
$

Effect
Leading Zeros if any will be suppressed
Leading Zeros are replaced by asterisks(*)
Currency sign appears in the left most of the

field.
-

Appears at left or right of the field as specified in


the picture clause if value is negative

Appears if value is positive, else minus sign


appears
Editing Codes are specified in the picture clause for
variables intended for report purpose.
These variables cannot be used for arithmetic calculations.

More Editing Characters

EDIT CODES

MEANING

CR or DB

To be specified in the right most position of


the pic clause. Appears only if the value is
negative ,if value is positive it replaced by
two characters.

Stands for decimal point. Cannot be


specified with V clause

Inserted in the position where specified


Blank is appeared

Zero is appeared. To be specified left most


position of pic clause.

-(hyphen) / (slash)

Used as date separators. Appears where


specified.

BLANK WHEN ZERO

Sets all null values to blanks

EXAMPLES
DATA
02346

PIC CLAUSE
UNEDITED
9(5)

PIC CLAUSE
EDITED
ZZ999

EDITED
VALUE
2346

0005

9(4)

ZZ99

05

03.42

99V99

Z999

003

0.007

9V999

ZV999

007

05634

9(5)

**999

*5634

00143

9(5)

$9(5)

$00143

453

9(3)

$**999

$**453

-0453

s9(4)

-ZZ9(2)

- b453

-0453

s9(4)

9999-

0453-

453

9(3)

999-

453

-453

s9(3)

999+

453-

70.46

99V99

99.99-

70.46

156758

9(6)

99/99/99

15/67/58

00

99V9

0.00

8654

9(4)

99.9 Blank when


zero
99b9b9

86b5b4

24

99

9900

2400

Notes:
The above table shows contents of unedited fields in the first column. Contents of edited fields
after moving the data-1 shown in last column.
Edited fields (Fields with editing codes) cannot take part in arithmetic computations. Moving of numeric
edited fields to unedited fields is illegal.

UNIT 3
PROCEDURE DIVISION

PROCEDURE DIVISION
PROCEDURE DIVISION[USING <DATA-ITEM1>, <DATA-ITEM2>.
MAIN-PARA.
DISPLAY ENTER VALUE OF A:.
ACCEPT A.
DISPLAY ENTER VALUE OF B:.
ACCEPT A.
MOVE A TO B.
ADD A TO B.
DISPLAY A VALUE : A.
DISPLAY B VALUE : B.
----------------------------------------------------------------

STOP RUN.

Notes :

Procedure Division can consists of


Sections (Optional)
Paragraphs(Optional)
Statements.
While coding, we must follow the following Hierarchy:
SECTION------- PARAGRAPHS ------ STATEMENTS
Or
PARAGRAPH------- STATEMENTS
Or
STATEMENTS

COBOL VERBS

All instructions are coded in Procedure division.

BASIC COBOL VERBS

MOVE
ACCEPT
DISPLAY
PERFORM
GOTO
STOP RUN
CALL
COPY

SORT
MERGE
FILE OPERATIONS
CHARACTER
HANDLING
TABLE HANDLING
CONDITIONS
ARITHMETIC VERBS

Notes:
Arithmetic Verbs

: ADD, SUBTRACT, MULTIPLY, DIVIDE, COMPUTE

Conditions

: IF.ELSE, EVALUATE

File handling

: READ, WRITE, REWRITE, DELETE

Character handling

: INSPECT, STRING, UNSTRING

Table handling

: SET, SEARCH

Paragraphs
Paragraphs are building blocks of the PROCEDURE DIVISION
PROCEDURE DIVISION.
MAIN-PARA.
STATEMENT1.
STATEMENT2.
-------------------------------------------------------------PARA-100.
-----------------------------------------------

Notes:
A paragraph-name must begin in Area A and must be followed by a separator period.
A paragraph-name need not be unique because it can qualified by a SECTION name.
Paragraph-names need NOT contain any alphabetic character (i.e. can be all numeric).
A paragraph ends at:

The next paragraph-name or section header

The end of the PROCEDURE DIVISION

The Scope terminator END-PARAGRAPH

Terminator statements

EXIT PROGRAM.

The EXIT PROGRAM statement specifies the end of a called program and returns
control to the calling program
STOP RUN.
The STOP RUN statements halts the execution of the object program, and returns
control to the system
GOBACK.
The GOBACK statement functions like the EXIT PROGRAM statement
When it is coded as part of a called program and like the STOP RUN when coded in a
main program
Notes:
If these statements are not the last statements in a sequence, statements following them will not
be executed.

Scope Terminators
Explicit scope terminators mark the end of certain PROCEDURE DIVISION statements.
Explicit scope terminators are COBOL Reserved Words.
END-ADD
END-SEARCH
END-MULTIPLY
END-START
END-PERFORM
END-STRING
END-READ
END-DIVIDE
END-EVALUATE
END-REWRITE
END-IF

END-CALL
END-COMPUTE
END-DELETE
END-UNSTRING
END-WRITE

An explicit Scope Terminator is paired with the unpaired occurrence of the verb.
An implicit Scope Terminator is a separator period.

Notes:
Example:
PERFORM PARA-1 UNTIL A > 10
STATEMENT1
STATEMENT2
-------------------------------------------------------END-PERFORM.
Period(.) should not encounter in between PERFORM and END-PERFORM. Since it indicates end of
the PERFORM statement, then compiler error will raise.

Display verb
The function of the DISPLAY statement is to display low-volume results on the
operators console or some other hardware device.
Syntax :
>>____DISPLAY_____ __identifier-1___ __ |
_____________________________________________>
| _ literal-1______|
e.g:
PROCEDURE DIVISION.
DISP-PARA.
DISPLAY SRCH-ARG NOT IN TABLE..
---------------------------------------------------------------DISPLAY HELLO HOW ARE YOU.

Notes:
The DISPLAY statement transfers the contents of each operand to the output device. The contents are
displayed on the output device in the order, left to right, in which the operands are listed.
WITH NO ADVANCING When specified, the positioning of the output device will not be changed in
any way following the display of the last operand.

ACCEPT Verb
Format 1 transfers data from an input/output device into identifier-1.
When the FROM phrase is omitted, the system input device is assumed.
Format 1 is useful for exceptional situations in a program when
operator intervention (to supply a given message, code, or exception indicator)
is required.
Format 1 :
>>__ACCEPT______identifier-1___ __________________________________________><
| _ FROM__ _mnemonic-name-1___ _|
| _ environment-name _ |
77 SEARCH-VALUE
PIC X(10).
.
ACCEPT SEARCH-VALUE FROM SYSIN.

Notes:
The ACCEPT statement transfers data into the specified identifier. There is no editing or error checking
of the incoming data.
If the source of the ACCEPT statement is a file and identifier-1 is filled without using the full record
delimited by the record terminator, the remainder of the input record is used in the next ACCEPT
statement for the file. The record delimiter characters are removed from the input data before the input
records are moved into the ACCEPT receiving area.
If the source of the ACCEPT statement is a terminal, the data entered at the terminal, followed by the
enter key, is treated as the input data. If the input data is shorter than identifier-1, the area is padded with
spaces.

MOVE Verb
MOVE verb is used to copy the contents of an identifier into another identifier.
MOVE <identifier-1>
Or
<literal-1>

TO <identifier-2>[<identifier-3>,.].

E.g.:
MOVE A TO B,C,D
MOVE dataname-1 to dataname-2
MOVE 345 to num-1
MOVE 345 TO K
MOVE XYZ TO data-name-1
If the length of the receiving field is less than the length of sending field then truncation
occurs.

Notes:
The MOVE statement transfers data from one area of storage to one or more other areas.
An index data item cannot be specified in a MOVE statement.
If the sending field(identifier-1) is reference-modified, subscripted, or is an alphanumeric or
alphabetic function-identifier, the reference-modifier, subscript, or function is evaluated only
once, immediately before data is moved to the first of the receiving operands.

Elementary & Group Moves


The receiving or sending field of a MOVE statement can be either an
elementary item or a group item.When both the fields are elementary items the
data movement is known as an elementary move. When at least one of the
fields is a group item, it is called group move.
01 MSG-FLD
PIC X(10).
01 DATA-FLD
PIC X(10).
01 OLD-ADDR.
05 NO
PIC X(5).
05 NAME
PIC X(15).
------------------------------------------------------------01 NEW-ADDR.
05 N-NO
PIC X(5).
05 N-NAME
PIC X(15).
------------------------------------------------------------MOVE OUT OF SEQUENCE TO MSG-FIELD
MOVE SPACES TO OLD-ADDR, NEW-ADDR
MOVE DATA-FLD TO MSG-FIELD.
MOVE NEW-ADDR TO OLD-ADDR

Notes:
Elementary move
-

Both sending and receiving data items are elementary items


Data conversion may take place, as well as editing or de-editing
On alphabetic moves, all necessary space-fill or truncation will occur

Group Move
-

Both sending and receiving data items are group items


No data conversion takes place

CORRESPONDING Phrase
01 STRUCT-1.
03 FIELD-A
03 FIELD-B
03 FIELD-C
03 FIELD-D
01 STRUCT-2.
10 FIELD-C
10 FILLER
10 FIELD-B
10 FILLER
10 FIELD-A
10 FILLER

PIC
PIC
PIC
PIC

9(9) VALUE 123456789.


X(5) VALUE abcde.
9(4)V99 VALUE 1234.56.
9(4)V99 VALUE 123456789.

PIC
PIC
PIC
PIC
PIC
PIC

Z(4).99.
XXX.
X(5).
XXX.
Z(9)
XXX.

MOVE CORRESPONDING STRUCT-1 TO STRUCT-2


Statement moves 3 fields but gives warning.
Given the data definitions in the visual, the MOVE CORRESPONDING statements in the
visual move three fields ( FIELD-S, FIELS-B and FIELD-C) but gives a warning message
similar to the one below

ILLUSTRATES MOVE CORRESPONDING


DATA DIVISION
WORKING STORAGE SECTION.
01
DATA-1
05
E-ID
PIC 9(5)
VALUE 2345.
05
E-NAME PIC X (25)
VALUE ALL N.
05
E-DEPT PIC X (20)
VALUE ALL D
05
E-BASIC PIC 9(4) V99
VALUE 1234.67.
01
DATA-2.
05
FILLER
PIC X(5)
05
E-ID
PIC 9(5)
05
FILLER
PIC X(5)
05
E-NAME
PIC X (25).
05
FILLER
PIC X(5).
05
E-DEPT
PIC X(20)
05
FILLER
PIC X(5)
05
E-BASIC
PIC 9(4). 99

PROCEDURE DIVISION.
PARA 1.
MOVE E-ID OF DATA-1 TO E-ID OF DATA-2
MOVE E-NAME OF DATA-1 TO E-NAME OF DATA-2.
MOVE E-DEPT OF DATA-1 TO E-BASIC OF DATA-2.
DISPLAY DATA-1
DISPLAY DATA-2
MOVE SPACES TO DATA-2.
MOVE CORRESPONDING DATA-1 TO DATA-2.
DISPLAY DATA-1
DISPLAY DATA-2.
STOP RUN.

Reference Modification

Reference Modification defines a data item by specifying its leftmost character and
optionally, a length
MOVE data-name1(begin : [length]) TO data-name2

If Length is omitted, the data item continues to rightmost character of data-name1


(the colon is required).

The data name must have usage DISPLAY. It may be qualified or subscripted. When
qualified or subscripted, the reference modification is specified last.

WORKING-STORAGE SECTION.
01
01
01
01

CAT-TYPE PIC X(15) VALUE 'CALICO'.


DOG-TYPE PIC X(15) VALUE 'SCHNAUZER'.
CAT-ABBREV PIC X(5).
DOG-END PIC X(10). PROCEDURE DIVISION.

*Reference Modification Example Number 1: (From position 1:For 5 positions.)


MOVE CAT-TYPE(1:5) TO CAT-ABBREV.
*This will move "CALIC" to CAT-ABBREV. (The letters from position 1 of CAT-TYPE
for 5 positions.)
DISPLAY CAT-ABBREV.

*Reference Modification Example Number 2: (From position 2:For 4 Bytes.)


MOVE CAT-TYPE(2:4) TO CAT-ABBREV.
*This will move "ALIC" to CAT-ABBREV2. (The letters from position 2 of CAT-TYPE
for 4 positions.)
DISPLAY CAT-ABBREV.
*Reference Modification Example Number 3: (From position number 5 to the end of the field.)
MOVE DOG-TYPE(5:) TO DOG-END.
*This will move "AUZER" to DOG-END. (The letters from position 5 of DOG-TYPE to
the end of DOG-TYPE.)
DISPLAY DOG-END.

ADD Verb
All identifiers (or literals) preceding the word TO are added together, and then this
sum is added to, and replaces, each identifier-2. The action is repeated in order left-to- right for each
identifier-2.
Identifiers must be elementary numeric items.
Format 1 :
>>___ADD_______ identifier-1_ _|__ To _____identifier-2__ _ ______ _______|____>
|_literal-1___|
|_ROUNDED _|
>___ _______________________________________ ___________________________>
|_ ____ __SIZE ERROR imperative-statement-1______|
>___ ________________________________________ ___________________________>
|_ NOT___ ______ ___SIZE ERROR__imperative statement_2_|
>___ _______ ___________________________________________________________>
|_ END-ADD_|

In Format 1, all identifiers or literals preceding the key word TO are added together, and this
sum is stored in a temporary data item. This| temporary data item is then added to each
successive occurrence of identifier-2, in the left-to-right order in which identifier-2 is specified.
Identifier must name an elementary numeric item.
Literal must be a numeric.
The ADD statement sums two or more numeric operands and stores the result.
Example :
ADD A TO B.
ADD 112 TO B.
ADD A TO B ON SIZE ERROR GO TO ERR-PARA.

ADD Verb(Continue)

The operands preceding the GIVING are added together and the sum
replaces the value of each identifier-3.

Identifiers must be elementary numeric items, except when following


GIVING then they may also be numeric edited.
Format 2 :
>>___ADD_______ identifier-1_ _|__ _ _ __ _ identifier2____________________>
|_literal-1___|
|_TO_|
|_literal-2______|
>___ GIVING ___________identifier-3__ ______________ _| ________________ >
|_ ROUNDED__|
>___ _____________________________________________________ __________ >
|_
_________ ___SIZE ERROR__imperative statement_1_|
>___ ____________________________ _________________________________ >
|_ NOT___ ______ _SIZE ERROR__imperative statement_2_|
|_ ON_|
>___ _______ _______________________________________________________ >
|_ END-ADD_|

In Format 2, the values of the operands preceding the word GIVING are added together,
and the sum is stored as the new value of each data item referenced by identifier-3.
Identifier must name an elementary numeric item, except when following the word
GIVING. Each identifier following the word GIVING must name an elementary
numeric or numeric-edited item
Literal must be a numeric.
Example :
ADD A TO B GIVING C

ADD CORRESPONDING Statement


Elementary data items within identifer-1 are added to, and stored in the corresponding elementary data
items with identifer-2..
ADD CORRESPONDING identifiers must be group items
Format :
>>___ADD_______ CORRESPONDING_ ___identifier-1___ TO___ identifier-2____________>
|_CORR___________|
>___ ______________ __ ______________________________________ ________________ >
|_ ROUNDED__| | _ ___ __SIZE ERROR____ imperative-statement-1_|
|_ ON_ |
>___ _____________________________________________ ___________________________ >
|_NOT___ ______ __SIZE ERROR__imperative statement_1_|
|_ON___|
>___ _____________________________________________ ___________________________ >
|_ NOT___ ______ _SIZE ERROR__imperative statement_2_|
|_ ON_|
>___ _______ __________________________________________________________________ >
|_ END-ADD_|

ON SIZE ERROR Phrase

If the value of an arithmetic evaluation exceeds the largest value that can be contained
in a result, then a size error condition exists.

The SIZE ERROR condition applies to final results, not intermediate calculations

If ON SIZE ERROR phrase is not specified, then truncation of the results will occur.

If ON SIZE ERROR phrase is specified, the imperative statement (in ON SIZE


ERROR) is taken, following which control is transferred to the end of the arithmetic
statement.

For ADD CORRESPONDING or SUBTRACT CORRESPONDING, the ON SIZE


ERROR imperative is not taken until all individual additions or subtractions have been
completed.

A size error condition can occur in three different ways

When the absolute value of the result of an arithmetic evaluation, after decimal point alignment,
exceeds the largest value that can be contained in the result field

.
.

When division by zero occurs


In an exponential expression, as indicated in the following table
Size error

Action taken when a


size error clause is
present

Action taken when a


size error clause is
not present

Zero raised to zero


power

The size error


imperative is executed

The value returned is


1, and message is
issued

Zero raised to a
negative power

The size error


imperative is executed

Program is terminated
abnormally

A negative number
raised to a fractional
power

The size error


imperative is executed

The absolute value of


the base is used, and a
message is issued.

The size error condition applies only to final results, not to any intermediate results

NUMERIC Data
Types of numeric items are:
Binary
Packed decimal. (internal decimal)
Floating point representation.
The PICTURE character-string can contain only the symbols 9, P, S, and V
The number of digit positions must range from 1 through 18, inclusive
If unsigned, the contents of the item in standard data format must contain a
combination of the Arabic numerals 0-9. If signed, it may also contain a +, -, or
other representation of the operation sign

Notes:
A VALUE clause can specify a figurative constant ZERO

SUBTRACT Verb
Format 1 :
>>___SUBTRACT_______ identifier-1_ _|__ FROM____________________________>
|_literal-1___|
> ______identifier-2__ ___ _|________________________________________________>
| _ ROUNDED ____|
>___ ________________________________________ ___________________________>
|_ ____ __SIZE ERROR imperative-statement-1______|
|_ON _|
>___ ________________________________________ ___________________________>
|_ NOT___ ______ ___SIZE ERROR__imperative statement_2_|
>___ _______ _________________________________________________>
|_ END-SUBTRACT_|
All identifiers or literals preceding the key word FROM are added together and this sum
is subtracted from and stored immediately in identifier-2. This process is repeated for each
successive occurrence of identifier-2, in the left-to-right order in which identifier-2 is specified .

SUBTRACT Verb(Continue.)
Format 2 :
>>___SUBTRACT_______ identifier-1_ _|__ FROM ___ _ identifier-2__ _______________>
|_literal-1___|
|_literal-2______|
>___ GIVING ___________identifier-3__ ______________ _| _________________________ >
|_ ROUNDED__|
>___ ____________________________________________ ____________________________ >
|_
_______ ___SIZE ERROR__imperative statement_1_|
|_ ON _|
>___ ____________________________________________ ____________________________ >
|_ NOT___ ______ _SIZE ERROR__imperative statement_2_|
|_ ON_|
>___ _______ __________________________________________________________________ >
|_ END-SUBTRACT_|

All identifier or literals preceding the key word FROM are added together and this sum is
subtracted from identifier-2 or literals-2. The result of the subtraction is stored as the new value of
each data item referenced by identifier-3.
Notes:
Example:
1. SUBTRACT A FROM B.
The value of A subtttracted from the value of B and then the resultant value will be stored in B.
2. SUBTRACT 9 FROM C.
3. SUBTRACT C FROM 9. Is not valid because 9 is a Literal.

SUBTRACT CORRESPONDING Statement


Format :
>>___SUBTRACT____ CORRESPONDING_ ___identifier-1__ FROM_________________>
|_CORR__________|
>___ identfier-2____ __ ___________ _________________________________________ >
|_ ROUNDED__|
>___ _________________________________________ ____________________________ >
|____ ______ __SIZE ERROR__imperative statement_1_|
|_ON___|
>___ ________________________________________ ____________________________ >
|_ NOT___ ______ _SIZE ERROR__imperative statement_2_|
|_ ON__|
>___ _______ ______________________________________________________________ >
|_ END-SUBTRACT_|

Elementary data items within identifier-1 are subtracted from, and the results are stored in, the
corresponding elementary data items within identifier-2.

MULTIPLY Verb
Format 1 :
>>___MULTIPLY_______ identifier-1___ ___BY____identifier-2___ ______________| __________>
|_ literal-1________|

>___ _______________________________________________________________________________ >


|____ ______ __SIZE ERROR__imperative statement_1_|
|_ON___|
>___ _________________________________________________ ____________________________ >
|_ NOT___ ______ _SIZE ERROR__imperative statement_2_|
|_ ON__|
>___ _______ ________________________________________________________________________ >
|_ END-MULTIPLY_|
In Format 1, the value of identifier-1 or literal-1 is multiplied by the value of identifier-2; the
product is then placed in identifier-2. For each successive occurrence of identifier-2, the
multiplication takes place in the left-to-right order in which identifier-2 is specified.

MULTIPLY Verb(Continue..)
Format 2 :
>>___MULTIPLY_______ identifier-1_ _|__ BY_______ _ identifier-2__ ______________>
|_literal-1___|
|_literal-2______|
>___ GIVING ___________identifier-3__ ______________ _| _______________________ >
|_ ROUNDED__|
>___ _____________________________________________________ ________________ >
|_
_______ ___SIZE ERROR__imperative statement_1_|
|_ ON _|
>___ _____________________________________________________ ________________>
|_ NOT___ ______ _SIZE ERROR__imperative statement_2_|
|_ ON_|
>___ _______ ______________________________________________________________ >
|_ END-MULTIPLY_|
In Format 2, the value of identifier-1 or literal-1 is multiplied by the value of identifier-2
or literal-2.The product is then stored in the data item(s) referenced by identifier-3.

DIVIDE Verb
Format 1 :
>>___DIVIDE_____ _____ identifier-1_ _|__ INTO__________identifier-2____ _____
|_literal-1___|
|_ROUNDED

__ |____>
_|

>___ ________________________________________________ ____________________________>


|_ ____ __SIZE ERROR imperative-statement-1____________|
|_ON _|
>___ _________________________________________________
____________________________>
|_ NOT___ ______ ___SIZE ERROR__imperative statement_2_|
|_ON __|
>___ _______
______________________________________________________________________>
|_ END-DIVIDE_|
In Format 1, the value of identifier-1 or literal is divided into the value of identifier-2, and the quotient is
then stored in identifier-2. For each successive occurrence of identifier-2, the division takes place in the
left-to-right order in which identifier-2 is specified.

DIVIDE Verb(Continue)
Format 2 :
>>___DIVIDE_______ identifier-1_ _|__ INTO_______ _ identifier-2__ ___________________________>
|_literal-1___|
|_literal-2______|

>___ GIVING ___________identifier-3__ ______________ _| ___________________________________ >


|_ ROUNDED__|
>___ _____________________________________________________ ____________________________ >
|_
_______ ___SIZE ERROR__imperative statement_1_|
|_ ON _|
>___ _____________________________________________________ ____________________________>
|_ NOT___ ______ _SIZE ERROR__imperative statement_2_|
|_ ON_|
>___ _______ _________________________________________________ >
|_ END-DIVIDE_|

In Format 2, the value of identifier-1 or literal-1 is divided into or by the value of identifier-2 or literal-2.
The value of the result is stored in each data item referenced by identifier-3.

COMPUTE Verb
Format :
>>___COMPUTE_______ identifier-1_ ____________ _|____ _ =______ __________________________>
|_ ROUNDED _|
|_ EQUAL_|
>___ arithmetic expression________________________________________________________________ >
>___ _____________________________________________________ ____________________________ >
|_
_______ ___SIZE ERROR__imperative statement_1_|
|_ ON _|
>___ _____________________________________________________ ____________________________ >
|_ NOT___ ______ _SIZE ERROR__imperative statement_2_|
|_ ON_|
>___ _______ __________________________________________________ >
|_ END-COMPUTE_|

The arithmetic expression is calculated and replaces the value for each identifier-1 item. Valid operators
allowed in the expression are:
+ addition
- subtraction
* multiplication
/ division
** exponentiation

Notes:
The COMPUTE statement assigns the value of an arithmetic expression to one or more data items.
With the COMPUTE statement, arithmetic operations can be combined without the restrictions on receiving
data items imposed by the rules for the ADD, SUBTRACT, MULTIPLY, and DIVIDE statements.

Must name elementary numeric item(s) or elementary numeric-edited item(s).


Can name an elementary floating-point data item.
The word EQUAL can be used in place of =.
An arithmetic expression ca consist of any of the following:
1. An identifier described as a numeric elementary item
2. A numeric literal
3. The figurative constant ZERO
4. Identifiers are literals, as defined in terms 1,2, and 3, separated by arithmetic operators
5. Two arithmetic expressions, as defined in items 1,2,3, and/or 4, separated by an arithmetic operator
6. An arithmetic expression, as defined in items 1,2,3,4 and/or 5, enclosed in parentheses.

When the COMPUTE statement is executed, the value of the arithmetic expression is calculated, and this
value is stored as the new value of each data item referenced by identifier-1.

PERFORM Statement
PERFORM Paragraph-name/Section-header
Transfer the control to the specified paragraph or section and expects the control back after
executing the paragraph.

PERFORM Para-name-1 [ THROUGH (or) THRU Para-name-n]


Notes:
PERFORM types

PERFORM para-name
PERFORM para-name N TIMES
PERFORM para-name VARYING K FROM M BY N
UNTIL CONDITION K>20

PERFORM para-name VARYING K FROM M BY N UNTIL CONDITION K>20 AFTER

VARYING.

PERFORM THROUGH
PROCEDURE DIVISION.
100-MAIN-PARA.
PERFORM 200-PARA THRU 500-PARA.
STOP RUN.
200-PARA.
* Statements.
400-PARA.
* Statements
500-PARA.
* Statements
300-PARA.
* Statement - Not executed
All the paragraphs between 200-PARA and 500-PARA are executed.

PERFORMN times

PERFORM PARA-NAME-1[THROUGH (or) THRU PARA-NAME-N]


N TIMES.
EX:
PERFORM PARA-1000 15 TIMES.
PERFORM PARA-1000 THRU PARA-4000 15 TIMES.
PARA-1000.
ADD A TO B.
-----------------------------------------------PARA-2000.
SUBTRACT A FROM B.
-------------------------------------------------------------PARA-4000.
MULTIPLY A BY B.
----------------------------

PERFORMVARYING
PERFORM PARA-NAME-1 [THRU (or) THROUGH PARA-NAME-N]
VARYING { identifier- 1 }
{identifier-2 }
{Index-name-1} FROM
{index-name-2}
{ Literal-1
}
BY
{identifier-3 }
UNTIL
Condition
{Literal-2 }
EX:
1. PERFORM PARA-2000 THRU PARA-5000 VARYING A FROM M BY N
UNTIL A > Y
2. PERFORM para-1 Varying K FROM 10 BY 5
UNTIL K>100
Notes:
Example 2 says :
Sets the value of K to 10 initially
Execute para-1
Check the condition K>100
If condition is true, transfer the control to next line
If condition is false, increment K by 5
Execute para-1 again
Check the condition K > 100
Repeat steps from 2 through 7 until Condition K > 100 becomes true

Flow Chart for PERFORM .. VARYING

Enter

Set identifier 1
to initial value

Exit
Conditi
on
False
Execute range

Add increment to identifier.

PERFORM with the VARYING-AFTER Option


PERFORM PARA-NAME-1 [THRU (or) THROUGH PARA-NAME-N]
VARYING { identifier- 1 }
{identifier-2 }
{Index-name-1} FROM
{index-name-2}
{ Literal-1
}
BY
{identifier-3 }
UNTIL
Condition-1
{Literal-2 }
AFTER

{ identifier- 4 }
{Index-name-3}

BY
{identifier-6 }
{Literal-4 }
AFTER

BY

{ identifier- 7 }
{Index-name-5}

FROM

UNTIL

FROM

{identifier-5 }
{index-name-4}
{ Literal-3
}
Condition-2

{identifier-8 }
{index-name-6}
{ Literal-5
}

{identifier-9 }
UNTIL
Condition-3
{Literal-6 }
This form is used when a nested repetition of the range is required while varying more than one
identifier.

For example
PERFORM RANGE-TO-BE-EXECUTED
VARYING I FROM 1 BY 1 UNTIL I > 50
AFTER
J FROM 1 BY 1 UNTIL J > 10.
The range RANGE-TO-BE-EXECUTED will be performed 500 times,.

In-Line PERFORM
The in-line PERFORM will be coded using END-PERFORM.
Named Paragraph
PERFORM MOVEIT
VARYING X FROM 1 BY 1 UNTIL X = 5.
...
MOVEIT.
MOVE DATA-FLD (X) TO PRINT (X).
In-line PERFORM
PERFORM VARYING X FROM 1 BY 1 UNTIL X = 5.
MOVE DATA-FLD (X) TO PRINT (X).
END-PERFORM.
Notes:
An In-line PERFORM requires the END-PERFORM terminator. Conversely the
END-PERFORM phrase must not be specified when the statement is PERFORM procedure name.

IN-LINE PERFORM Considerations

DO not use for procedures executed from several places/

Use for procedures referenced only once.

Consider not using if readability is affected , such as multiple-page PERFORM,

No periods may appear within the in-line PERFORM.

Delimited by END-PERFORM.

END-PERFORM cannot be used at end of an out-of-line PERFORM.

The OPTIMIZE compile option may move the PERFORM in-line in the object code at
the compile time.

IF .. ELSE Statement

The IF statement evaluates a condition and provides for alternative actions in the object
program, depending on the evaluation.
Format :
>>_______IF_____Condition-1____ __________ _____ ___statement-1___|__ ________>
|_THEN_____|
|_NEXT SENTENCE _|
>___ ______________ ____ ________________ ______________________________>
|
<____________
|
|
(1) |
| _ ELSE__ ___statement-2_|_____ |
|___END-IF________|
Note :
(1) END-IF can be specified with NEXT SENTENCE as an IBM extension.

Notes:
The IF statement evaluates a condition and provides for different sets of statements to execute, depending
on the evaluation of the IF.
Condition can be any simple or complex condition.

Statement-1, statement-2 Can be any one of the following:


An imperative statement
An conditional statement
An imperative statement followed by a conditional statement

NEXT SENTENCE
If the NEXT SENTENCE phrase is specified, and then the END-IF phrase must not be specified.
NEXT SENTENCE passes control to the statement after the closest following period. However, if
the NEXT SENTENCE phrase is executed, control will not pass to the statement after the closest
following period.

Compound Conditionals

Conditional expressions can be compound using the AND and OR logical operators
Conditional conditions can also use parentheses to group conditions.
IF
ITEM-1
=
DOMESTIC-ITEM-NO
AND ITEM-2
=
OVERSEAS-ITEM-NO
OR
ITEM-1
=
OVERSEAS-ITEM-NO
AND ITEM-2
=
DOMESTIC-ITEM-NO
SET MIXED-SHIPMENT-FLAG TO TRUE
END-IF
.
SEARCH TABLEPAIR VARYING NDX
WHEN ITEM-1(NDX) = FROM-CITY AND ITEM-2(NDX) = TO-CITY
MOVE
WHEN ITEM-2(NDX) = FROM-CITY AND ITEM-1(NDX) = TO-CITY
MOVE ..
END-SEARCH

Relational Expressions

Relational tests (comparisons) can be express as:

IS LESS THAN
IS NOT LESS THAN
GREATER THAN
IS NOT GREATER THAN
IS EQUAL TO
IS NOT EQUAL TO
IS GREATER THAN OR EQUAL TO
IS LESS THAN OR EQUAL TO

IS <
IS NOT <
IS >
IS NOT >
IS =
IS NOT =
IS >=
IS <=

CONTINUE & NEXT SENTENCE Statement


Example 1 - NEXT SENTENCE
IF A = B
IF C = D
NEXT SENTENCE
ELSE
MOVE MESSAGE-1 TO RPT-MESSAGE-1
END-IF
ADD C TO TOTAL
DISPLAY TOTAL
IF E = F
MOVE MESSAGE-4 TO RPT-MESSAGE-2
END-IF
END-IF.

Example 2 CONTINUE
IF A=B
IF C=D
CONTINUE
ELSE
MOVE MESSAGE-1 TO RPT-MESSAGE-1
END-IF
ADD C TO TOTAL
DISPLAY TOTAL
IF E=F
MOVE MESSAGE-4 TO RPT-MESSAGE-2
END-IF
END-IF.

EVALUATE Statement

EVALUATE is a great way to implement the case programming


construct
EVALUATE dataname
WHEN value-1 .
WHEN value-2 {THROUGH | THRU} value-3 .
WHEN NOT value-4

WHEN OTHER
END-EVALUATE

Basic EVALUATE Example:


EVALUATE dataname
WHEN A
WHEN D
WHEN U
WHEN W
WHEN OTHER
END-EVALUATE

Perform add-trans
Perform delete-trans
Perform update-trans
Perform bad-trans

The scope of a WHEN clause is all statements UNTIL the next WHEN clause,
the END-EVALUATE, or a period

Notes:
The EVALUATE statement provides a shorthand notation for a series of nested IF statements. It
can evaluate multiple conditions. That is, the IF Statements can be made up of compound
conditions.
Examples:
Working-Storage for all Examples:
01 PLANET.
05 PLANET-NUMBER PIC 9.
05 PLANET-NAME PIC X(7).

Evaluate Example Number 1: (Evaluate a PIC 9 field)


EVALUATE PLANET-NUMBER
WHEN 1 MOVE "Mercury" TO PLANET-NAME
WHEN 2 MOVE "Venus "
TO PLANET-NAME
WHEN 3 MOVE "Earth "
TO PLANET-NAME
WHEN 4 MOVE "Mars "
TO PLANET-NAME
WHEN 5 MOVE "Jupiter"
TO PLANET-NAME
WHEN 6 MOVE "Saturn "
TO PLANET-NAME
WHEN 7 MOVE "Uranus " TO PLANET-NAME
WHEN 8 MOVE "Neptune" TO PLANET-NAME
WHEN 9 MOVE "Pluto "
TO PLANET-NAME
WHEN OTHER MOVE "
" TO PLANET-NAME
END-EVALUATE.

Evaluate Example Number 2: (Evaluate a PIC X field)


EVALUATE PLANET-NAME
WHEN "Mercury" MOVE 1
WHEN "Venus " MOVE 2
WHEN "Earth " MOVE 3
WHEN "Mars " MOVE 4
WHEN "Jupiter" MOVE 5
WHEN "Saturn " MOVE 6
WHEN "Uranus " MOVE 7
WHEN "Neptune" MOVE 8
WHEN "Pluto " MOVE 9
WHEN OTHER MOVE 0
END-EVALUATE.

TO
TO
TO
TO
TO
TO
TO
TO
TO
TO

PLANET-NUMBER
PLANET-NUMBER
PLANET-NUMBER
PLANET-NUMBER
PLANET-NUMBER
PLANET-NUMBER
PLANET-NUMBER
PLANET-NUMBER
PLANET-NUMBER
PLANET-NUMBER

Evaluate Example Number 3:


Let each of MONTH and NO-OF-Days be two-digited numeric integer fields. The values 1,2,3,
etc. for
MONTH denote respectively, January, February, March etc. depending on the value of
MONTH , we wish to
ove 30,31 or 28 to NO-OF-DAYS. For example , if the value of MONTH is
1, we shall move 31; if it is 2, we
shall move 28 and so on. The EVALUATE statement for the
purpose is as follows:
EVALUATE TRUE
WHEN MONTH = 4 OR 6 OR 9 OR 11
MOVE 30 TO NO-OF-DAYS
WHEN MONTH = 2
MOVE 28 TO NO-OF- DAYS
WHEN OTHER MOVE 31 TO NO-OF-DAYS
END EVALUATE.

Evaluate Example Number 4:


Suppose MARKS contains the marks obtained by a student. GRADE is an onecharacter alphanumeric field. We wish to calculate GRADE according to the
following rules
MARKS
GRADE
80 100
A
60 - 79
B
45 - 59
C
30 - 44
D
0 - 29
E
The EVALUATE statement for the purpose is shown below.
EVALUATE MARKS
WHEN 80
THRU
100
MOVE A TO GRADE
WHEN 60
THRU
79
MOVE B TO GRADE
WHEN 45
THRU
59
MOVE C TO GRADE
WHEN 30 THRU
44
MOVE D TO GRADE
WHEN ZERO THRU 29 MOVE E TO GRADE
WHEN OTHER MOVE W TO GRADE
END-EVALUATE.
The literal W is moved to GRADE in the case of wrong marks.

ILLUSTRATES CONDITION NAMES


DATA DIVISION.
WORKING-STORAGE SECTION.
77
MARTIAL-STATUS PIC 9.
88
SINGLE VALUE 0.
88
MARRIED
VALUE 1.
88
WIDOWED
VALUE 2.
88
DIVORCED
VALUE 3.
88
ONCE-MARRIED VALUES ARE 1, 2, 3.
88
VALID-STATUS
VALUES ARE 0 THRU 3.
77
AMOUNT
PIC 9 (4) VALUE 1000.
PROCEDURE DIVISION.
MAIN-PARA.
DISPLAY Martial Status:
DISPLAY 0- Single / 1- Married / 2- Widowed / 3- Divorced.
ACCEPT MARTIAL-STATUS.
IF NOT VALI-STATUS DISPLAY Error in Entry.
IF SINGLE SUBTRACT 100 TO AMOUNT.
IF MARRIED ADD 100 TO AMOUNT.
IF WIDOWED ADD 200 TO AMOUNT.
IF DIVORCED SUBTRACT 200 FROM AMOUNT.
IF ONCE-MARRIED ADD 250 TO AMOUNT
DISPLAY AMOUNT.
STOP RUN.

INITIALIZE Statement

The INITIALIZE statement sets selected categories of data fields to predetermined values. It
is functionally equivalent to one or more MOVE statements.
When the REPLACING phrase is not used:
SPACE is the implied sending field for alphabetic alphanumeric, alphanumeric-edited, and
DBCS items.
ZERO is the implied sending field for numeric and numeric-edited items.
>>___INITIALIZE____identifier- 1 ________________________________________>
>___ ___________________________ _________________
_______><
|
< ____________________________________________ __________________
|_REPLACING____ _ALPHABETIC_______ __ _______ __BY____ identifier-2 _ _ | _ |
|_ALPHANUMER____| |_DATA_|
|_LITERAL-1__|
|_NUMERIC __________|
|_ALPHANUMERIC-EDITED_|
|_NUMERIC-EDITED__|
|_ DBCS _____________|
|_ EGCS _____________|

Notes:
The INITIALIZE statement sets selected categories of data fields to predetermined values. It is functionally equivalent to
one or more MOVE statements.
A subscripted item can be specified for identifier-1. A complete table can be initialized only by specifying
a group that contains the complete table.

identifier-1 as

The data description entry for identifier-1 must not contain a RENAMES clause. An index data item cannot be
an operand of INITIALIZE.
Special registers can be specified for identifier-1 and identifier-2 only if they are valid receiving fields or
fields, respectively, for the implied MOVE statement(s).

sending

When the REPLACING phrase is used:


The category of identifier-2 or literal-1 must be compatible with the category indicated in the corresponding
REPLACING phrase, according to the rules for the NUMERIC category.
The same category cannot be repeated in a REPLACING phrase.
The Key word following the word REPLACING corresponds to a category of data shown Classes of Data
visual.

SET TO TRUE Statement

When this form of the SET statement is executed, the value associated with a
condition-name is placed in its conditional variable according to the rules of the
VALUE clause.
>>__SET____condition-name-1_|_ TO TRUE_________________________><
condition-name-1: Must be associated with a conditional variable.
If more than one literal is specified in the VALUE clause of condition-name-1, its
associated conditional variable is set equal to the first literal.
01 CUST-TYPE

PIC 99.
88 INACTIVE
VALUE 9.
88 SPEC-ACCTS VALUE 20, 11, 40, 44.

SET INACTIVE TO TRUE


SET SPEC-ACCTS TO TRUE

Class Condition
NUMERIC
The item entirely contains characters 0 through 9 (with or without a sign determined by its
clause). It may be USAGE DISPLAY or PACKED DECIMAL.
ALPHABETIC
The entire item contains only A through Z, a through z, or spaces
ALPHABETIC-UPPER
The entire item contains only A through Z (exclusively upper-case) or spaces.
ALPHABETIC-LOWER
The entire item contains only a through z (exclusively lower-case) or spaces.

Notes:
Ex:
1. IF A IS NUMERIC
-------------------------------------------2.

IF C IS ALPHABETIC
---------------------------------------------Where A and C are Data items.

PICTURE

UNIT 4

FILE HANDLING IN COBOL

FILES

A record is a group of logically or functionally related fields.

A File is a group of Records.

A group of records, which can be created, copied, modified, retrieved and


deleted.

E.g.:

Details of an employee
-Name, Adds, Phone no., Dept no etc Forms a record

Details of all employees


-Group of such record forms a file.

Notes:
Files can be broadly categorized into Program files and Data files. In COBOL the term Files is used to
indicate data files. Data files are normally created on a tape or disk and subsequently
program can refer
them.

Fixed vs Variables Length Records


Fixed length records.
Corresponding fields of all the records have same length.
Variable length records.
Field lengths may vary from record to record.
Figure 4-2 Fixed vs. Variable Length Records
Notes:
The size of a record is the cumulative size of all the fields in it.
If all the records of a file have the same structure then they are called Fixed length-records.
For convenience,records of different lengths can be placed together in one file.
Then they are known as variable-length-records.

FILE-CONTROL Paragraph
Format:
SELECT [OPTIONAL] File-name-1 ASSIGN TO Assignment-name-1
[ RESERVE <INTEGER> AREA ]
SEQUENTIAL
[ ORGANIZATION IS
INDEXED
RELATIVE

[ACCESS MODE IS

SEQUENTIAL
RANDOM
DYNAMIC

[FILE STATUS IS Data-name-1]


Figure 4-3 FILE-CONTROL - SEQUENTIAL
Notes:
The FILE-CONTROL paragraph associates each file with an external data-set. FILE_CONTROL
paragraph
is in INPUT-OUTPUT Section of ENVIRONMENT Division.Not all options are
available on all platforms.

SELECT OPTIONAL may be specified only for files opened in the input, I-O, or extended mode.
You must specify SELECT OPTIONAL for such input files that are not necessarily present each
time the program is executed.
The file-name-1 must be identified by an FD or SD entry in the DATA DIVISION.
The ASSIGN clause associates the programs name for a file with the external name for the
actual data file.
The RESERVE clause allows you to specify the number of input/output buffers to be allocated at
run time for the file.
The ORGANIZATION clause identifies the logical structure of the file.

ORGANIZATION IS SEQUENTIAL
The Records are stored in contiguous allocation. To access the record in Sequential mode only
(I.e. to read the last record, it reads all the records until last record found.)Deletion of record
is not possible.Updating is possible but record length should not changed.

ORGANIZATION IS INDEXED
Each record in the file has one or more embedded keys; each key is associated with an index.
An index provides a logical path to the data records, according to the contents of the
associated embedded record key data items. Indexed files must be direct-access storage
files.
Records can be fixed-length or variable-length.
Each record in an indexed file must have an embedded prime key data item. When records
are inserted, updated, or deleted, they are identified solely by the values of their prime keys.
Thus, the value in each prime key data item must be unique and must not be changed when the
record is updated.

In addition, each record in an indexed file can contain one or more embedded alternated key data
items. Each alternated key provides another means of identifying which record to retrieve.
The RECORD KEY clause specifies the data item within the record that is the prime
RECORD KEY for an indexed file. The values contained in the prime RECORD KEY data
item
must be unique among records in the file.
The ALTERNATRE RECORD KEY clause specifies a data item within the record that provides
an alternated path to the data in an indexed file. Used like the RECORD KEY but for an alternate
index.

ORGANIZATION IS RELATIVE
The INPUT-OUTPUT FILE-CONTROL for Relative record files is very similar to that of
indexed files except you use the RELATIVE KEY clause of the ACCESS MODE phrase and each
record identified by the Relative Record Number instead of Recoed Key.

ACCESS Mode
Modes

Meaning

SEQUENTIAL

Records of the file can be


accessed sequentially, starting
from first record till the required
record is reached.

RANDOM

Any record can be accessed


directly without beginning from
the first record.

DYNAMIC

Records can be accessed both


randomly and/or sequentially

Notes:

The record of a file stored on a magnetic tape can be accessed in sequential mode only. But the records of file stored
on magnetic disk can be accessed in all the modes.

FILE STATUS Clause


A two-digit number indicates the status of the file.

Value
00
10
30
34

Status
Successful Completion
At end condition
Permanent error
Boundary violation

Notes:
Input-Output operations may not be successful thus resulting in termination of the program.
The data-name specified in the file-status clause contains the status code and can be referred by the programmer.
Depending on the code programmer can take specific actions by transferring the control to error-routine paragraphs.
The data name should be declared in working-storage section with alphanumeric data type of two characters.

I-O-CONTROL Paragraph

The Optional I-O-CONTROL paragraph of the Input-Output Section specifies


when checkpoints are to be taken and the storage areas to be shared by different files.

Specifies information needed for efficient transmission of data between the external data
set and the COBOL program.

Notes:
The I-O-CONTROL paragraph is optional.
The key word I-O-CONTROL can appear only once, at the beginning of the paragraph. The word
CONTROL must begin in Area A, and must be followed by a separator period.
Each clause within the paragraph can be separated from the next by a separator comma or a separator
semicolon. The order in which I-O-CONTROL paragraph clauses are written is not significant. The I-OCONTROL paragraph ends with a separator method.

I-O-

FILE SECTION
FILE SECTION.
FD File-Name
BLOCK CONTAINS m RECORDS
RECORD CONTAINS n CHRACTERS
LABEL RECORDS ARE STANDARD/ OMMITED
01
File-record-structure.
Notes:
Each file used in the program should have an FD entry (File Description) in
FILE SECTION.

BLOCK CONTAINS clause specifies number of records in the block.

RECORD CONTAINS clause specifies total number of characters in each record.

LABEL RECORDS clause indicates

Disk files if STANDARD option is specified


Print files if OMITTED option is specified

Value clause specifies the name of the physical file and the path

01 level entry should follow immediately after FD paragraph.


Blocking
Input-Output operations are slower compared to CPU processing speed. To reduce the CPU waiting time, block of
records from the disk can be moved to the memory space called buffer thus reducing number of I-O operations.
The Programmer can specify the number of records contained in a block. Suitable block size is to be selected by the
programmer.

File Operations
Cobol Verbs

Meaning

WRITE

Writes the records into file.


Required while creating a new
file and while Adding new
records to an existing file.

REWRITE

Rewrites on one or more existing


fields of a file.
Required while updating a file.

READ

Reads the records of a file and


make them available to program

DELETE

Deletes the record from a file.

Notes:
This foil lists the possible operations that can be performed over files.
Before doing any operation, files should be opened and they must be closed before exiting the program
OPEN and CLOSE verbs are provided by COBOL.

OPEN MODES
Mode

Meaning

INPUT

Stands for input mode.


Only reading of records possible.

OUTPUT

Stands for output mode.


Only writing new records possible.

I-O

Stands for Input ---Output mode.


All operations possible

EXTEND

Stands for extend mode.


Only for appending the records in
sequential mode.

Notes:
SYNTAX
OPEN Mode File-name1, File-name2.
CLOSE File-name1, File-name2
While opening the file the mode must be specified depending on the operation to perform.
More than one file can be opened and closed. Further, files can be opened and closed more than once in a program.

READ Sequential Access

When the READ statement is executed the file must already be open in INPUT
or I-O mode

The AT END clause must be before the NOT AT END
Format 1: sequential retrieval
>>____READ__file-name-1___ _________________ __ __________ ___________________>
|_ NEXT __________| |_RECORD__|
|_
(1)|
|_ PREVIOUS______|
>_____ _______________________ ______________________________________________>
|____ INTO___identifier-1____|
>_____ ___________________________________ __________________________________>
|_ ____ __END_imperative statement-1_|
|_ AT _|
>_____ ____________________________________________ ____ __________ _______><
|_ NOT___ ______ ___END_imperative-statement-2_|
|_END-READ_|
Notes:
For sequential access, the READ statement makes the next logical record from a file available to the object program.
For random access, the READ statement makes a specified record from a direct-access file available to the object
program.
When the READ statement is executed, the associated file must be open in INPUT or I-O mode.
NEXT RECORD Reads the next record in the logical sequence of records. NEXT is optional when ACCESS MODE
IS SEQUENTIAL;
PREVIOUS RECORD Reads the previous record in the logical sequence of records.

END OF FILE Processing

When the AT END condition occurs during sequential processing, the READ statement
execution is unsuccessful. The contents of the record area are undefined

The following actions take place when AT END occurs:


The status indicator is posted.
Control is transferred to the AT END phrase, if it is specified
If AT END is not specified, then USE AFTER STANDARD ERROR
could be specified and that procedure is executed. Then control is
returned to the
statement following the READ.

READ Random Access


Format 2 : Random Retrieval
>>_____READ______file-name-1____ __________ ___ _______________ _____________>
>____ _____________________________ ________________________________________>
|_KEY_____ ___ __data-name-1__|
|_TO_|
>_____ _______________________________________________ ______________________>
|_INVALID_____ ______ ____imperative-statement-3__|
|_KEY __|
>____ ___________________________________________ ___ ____________ _______><
|_NOT INVALID___ ___ __imperative-statement-4_|
|_END-READ__|
|_KEY_|
For VSAM INDEXED files, the KEY field contains a data value that will be matched
against the key filed in the file records until the first record having an equal value is found.
For VSAM RELATIVE files, the KEY phrase must not be specified.
Notes:
Format 2 must be specified for indexed and relative files in random access mode, and also for files in the dynamic
access mode when record retrieval is random.
Execution of the READ statement depends on the file organization.

Indexed Files
Execution of a Format 2 READ statement causes the value of the key of reference to be compared
with the value of the
corresponding key data item in the file records, until the first record having
an equal value is found. The file position
indicator is positioned to this record, which is then made
available. If no record can be so identified, an INVALID KEY condition exists, and READ
statement execution is unsuccessful.
If the KEY phrase is not specified, the prime RECORD KEY becomes the key of reference for this request. When dynamic access is
specified, the prime RECORD KEY is also used as the key
of reference for subsequent executions of sequential READ statements,
until a different key of
reference is established.

Relative Files
Execution of a Format 2 READ statement sets the file position indicator pointer to the record
contained in the RELATIVE KEY data item, and makes that record available.
The KEY phrase must not be specified for relative files.

whose relative record number is

READ Dynamic Access

For dynamic access, either sequential or random access possible, depending upon
the format of the Read statement

Dynamic access is allowed only for VSAM indexed or VSAM relative


organizations.

Dynamic access is established by ACCESS IS DYNAMIC in FILE-CONTROL


SELECT statement

The NEXT phrase must be specified for sequential access with dynamic mode.
In order to READ NEXT, position must have been established in the file by a
successful OPEN, START or READ statement

START Statement
Format :
>>___START___file-name-1___________________________________________________________>
>__ _____________________________________________________________________ ________>
|_KEY___ ______ ____ __EQUAL___ ___ ________________ _data-name-1____|
|__TO _|
|
|_ TO_|
|
|_ = ______________________________|
|_LESS__ _______ ________________|
|
|_THAN_|
|
|_ < ______________________________|
|_GREATER__ ____
_____________|
|
|_THAN_|
|
|_> _______________________________|
|_NOT LESS___ _______ ___________|
|
|_THAN _|
|
|_NOT < ___________________________|
|_NOT GREATER__ _______ ________|
|
|_THAN_|
|
|_NOT > ___________________________|
|_LESS_ ____ _ OR EQUAL_ __ _____|
|
|THAN|
|_TO_|
|
|_ < = _____________________________|
|_GREATER__ ____ _OR EQUAL_ __ _|
|
|_THAN_|
\ TO|
|_>+_______________________________|
>__ _______________________________________ _____________________________________>
|_INVALID___ _____ _imperative-statement-1_|
|_KEY_|
>__ _______________________________________ ___________ ____________ _____________>
|_NOT INVALID___ _____ imperative-statement-1_|
|_END-START_|
|_KEY_|

Notes: The START statement provides a means of positioning within an indexed or relative file for
subsequent sequential record retrieval.

When the START statement is executed, the associated indexed or relative file must be open
in either INPUT or I-O mode.
file-name-1
Must name a file with sequential or dynamic access. File-name-1 must be defined in an
FD entry in the Data Division, and must not name a sort file.

END-START Phrase
This explicit scope terminator delimits the scope of the START statement. END-START converts a
conditional START statement to an imperative statement so that it can be nested in another
conditional statement. END-START can also be used with an imperative START statement.

WRITE Statement

The WRITE statement releases a logical record for an output or input/output file.

When the WRITE statement is executed:


The associated sequential file must be open in OUTPUT or EXTEND mode.
The associated indexed or relative file must be open in OUTPUT, I-O, or EXTEND
mode.

Record-name must be defined in a Data Division FD entry. Record-name can be qualified.


It must not be associated with a sort or merge file.

WRITE.FROM

PROCEDURE DIVISION.
WRITE File-rec FROM Identifier.
File-rec is record-name declared in FILE-SECTION.
Identifier is a working-storage section variable
The length of the identifier should be equal to the length of the record.

Notes:
To Create a file, program can accept the data from the terminal into file record and write it.
If the data need to be processed, it can be accepted in a W-S identifier. After processing the data the above
WRITE..FROM statement can be issued.
Each WRITE statement writes one record at a time.

READ.INTO

PROCEDURE DIVISION.
READ FILE-name (INTO W-S-Rec) | (AT END Statement)
File name is defined in SELECT clause.
W-S-Rec is working-Storage section identifier.
INTO clause moves the file record to W-S-rec.
AT END clause if used, indicates the next action after the last record is read.
OPEN INPUT Mode

Notes:
READ statement on sequential files reads one record at a time and makes it available to program.
Reading begins from first record and if the READ statement is put in a loop
That is executing the statement repeatedly, then it is possible to read consecutive records.
Loop can be terminated before AT END condition is reached if required so by the program.
If the file is left open next time when the read statement executes, reading continuous from where it was stopped
before the termination of loop.

If the file is closed then it is to be opened again before reading it.

REWRITE & DELETE


REWRITE record-name (FROM identifier)
Updates an existing record from W-S identifier.
OPEN I-O File-name
DELETE record-name ----------------- not allowed
Deleting of a record in sequential files not allowed.

Notes:
It is often required to change the existing data and the process is called UPDATING.
COBOL provides REWRITES verb to modify an existing record.

For example, changing the address field of an employee requires reading of employee number. Every record to
be updated needs to be read first. To search the record of an employee, whose employee number is known, the
process is as follows
Store the employee number in a variable
Open the file
Read first record
Compare the variable with Emp-No field of the file
If it matches update his address by REWRITE
Else read next record his address by REWRITE

Repeat the process until the require record is read.

Appending to sequential files


Adding new records to the existing file.
OPEN EXTEND Mode
WRITE records.

When new records to be added to file open the file in EXTEND mode
EXTEND mode causes the pointer to move to the end of the file.

CLOSE Statement
Format :
CLOSE File-name-1, [File-name-2 .]

CLOSE Statement Releases the Resourcces which are assigned to that file.
Cannot Close the file which is not opened.
After performing the operations on the file (I,e no longer used in a program) needs to be closed but
not necessary.
If the FILE STATUS clause is specified in the FILE-CONTROL entry, the associated status key is
updated when the CLOSE statement is executed.
If the file is in an open status and the execution of a CLOSE statement is unsuccessful, the
EXCEPTION/ERROR procedure (if specified) for this file is executed.

Sequential Files

ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL
SELECT file-name ASSIGN TO DEVICE-NAME
ORGANIZATION IS SEQUENTIAL.
ACCESS MODE IS SEQUENTIAL.
FILE STATUS IS data-name.

Area
B

Notes:
All the files used in the program should have an entry in FILE CONTROL paragraph.
For each file used, there should be one SELECT..ASSIGN clause.
The file-name is select clause is user defined word and can be used throughout the program wherever required.
ASSIGN clause specifies the device on which file stored.

EXAMPLE: SEQUENTIAL FILE


ID DIVISION.
PROGRAM-ID. SEQ1.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT INFILE ASSIGN TO DDNAME1
ORGANIZATION IS SEQUENTIAL.
SELECT OUTFILE ASSIGN TO DDNAME2
ORGANIZATION IS SEQUENTIAL.
DATA DIVISION.
FILE SECTION.
FD INFILE.
01 INREC.
02 ENO PIC X(5).
02 ENAME PIC X(10).
02 EADDRESS PIC X(15).
02 FILLER PIC X(50).
FD OUTFILE.
01 OUTREC PIC X(80).
WORKING-STORAGE SECTION.
01 EOF PIC X.
PROCEDURE DIVISION.
OPEN INPUT INFILE
OUTPUT OUTFILE.
READ INFILE INTO OUTREC AT END MOVE 'Y' TO EOF.
PERFORM WRITE-PARA UNTIL EOF = 'Y'.
CLOSE INFILE
OUTFILE.
STOP RUN.
READ-PARA.
WRITE OUTREC.
READ INFILE INTO OUTREC AT END MOVE 'Y' TO EOF.

Indexed Files
Index component consists of a index structure with a record key values and addresses of corresponding
records.
RECORD KEY is one or more fields of the records.
Suitable record key is to be chosen by the programmer depending on the functionality of the fields.
E.g :
Employee-code, Job-number.
ALTERNATE RECORD KEY can also be chosen.
E.g :
Employee-name, Job-name.
Indexed files facilitate faster accessing of records compared to that of sequential files.
Notes:
When an indexed file is created

An index component is also created containing some index tables based on record keys.
data component is created containing the actual records.
Record keys identify every record in the file.

The process of accessing a record involves searching for the record key with matching index value. Then locate the
record from the corresponding address.
This is done by the system itself.

INVALID KEY
(READ | WRITE | REWRITE | DELETE) File-name
(INVALID KEY Statement)
(AT END Statement).
Records and indexes of an indexed file are stored in key sequence order to facilitate faster access.
Invalid key clause checks whether any input-output operation is violating the
Uniqueness of primary keys
E.g. add a record with duplicate value.
Sequence of the records.
E.g. add a record with key value out of range.
Proper read
E.g. try to read a non-exist record
Reading of a record in indexed files required the key value to be provided by the program

ACCESS MODE: SEQUENTIAL & RANDOM


ACCESS MODE SEQUENTIAL

READ File-name NEXT RECORD to read sequentially.

DELETE statement should not contain invalid key

AT END clause is required.

ACCESS MODE RANDOM

READ File-name INVALID KEY statement

AT END clause not required.

Notes:
When READ NEXT statement is to be executed each time the records are read consecutively.
IF the access mode is RANDOM a record is read from corresponding key value.

ACCESS MODE: DYNAMIC


START file-name key
(NOT | LESS THAN | GREATER THAN| LESS THAN ) identifier
INVALID KEY statement
READ file-name NEXT RECORD AT END statement.
Notes:

In a situation demanding the access of more than one consecutive records from the middle of the file then
dynamic access is used.
The START verb places the read pointer to the record whose key value is compared with an identifier. Record is
accessed randomly.
READNEXT can be put into loop for sequential reading.
For the Rewrite/ Delete operations the records must be read at first .

EXAMPLE: INDEXED FILE


IDENTIFICATION DIVISION.
PROGRAM-ID. SEQFILE.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT IND-FILE ASSIGN TO DD1
ORGANIZATION IS INDEXED
ACCESS MODE IS RANDOM
RECORD KEY IS NUM.
SELECT OUT-FILE ASSIGN TO DD2
ORGANIZATION IS INDEXED
ACCESS MODE IS DYNAMIC
RECORD KEY IS NUM1.
DATA DIVISION.
FILE SECTION.
FD IND-FILE.
01 IND-REC.
02 NUM PIC X(3).
02 NAME PIC X(15).
02 ADDR PIC X(10).
02 FILLER PIC X(52).
FD OUT-FILE.
01 OUT-REC.
02 NUM1 PIC X(3).
02 NAME1 PIC X(15).
02 ADDR1 PIC X(10).
02 FILLER PIC X(52).
WORKING-STORAGE SECTION.
PROCEDURE DIVISION.
MAIN-PARA.
OPEN INPUT IND-FILE
I-O OUT-FILE.
MOVE '222' TO NUM.
READ IND-FILE RECORD INTO OUT-REC KEY IS NUM INVALID KEY
GO TO ERR-PARA.
WRITE OUT-REC.
PERFORM EXIT-PARA.
ERR-PARA.
DISPLAY 'KEY NOT FOUND'.
PERFORM EXIT-PARA.
EXIT-PARA.
CLOSE IND-FILE OUT-FILE.
STOP RUN.

Relative Files
FILE CONTROL
SELECT file-name ASSIGN TO Disk
ORGANIZATION IS RELATIVE
RELATIVE KEY data-name-1
RRN indicates the offset of a record from the first record of the file.

Notes:
In relative file Relative Record Number identifies the records of the file. Select clause should specify RELATIVE
KEY.
Value of data-name-1 indicates RRN.
Usage of READ/WRITE/ REWRITE/ DELETE statements, ACCESS modes, OPEN modes and START verb, are
exactly similar to that for sequential files.

Open modes
File Organization
Sequential

A
C
C
E
S
S

M
O
D
E

S
E
Q
U
E
N
TI
A
L

R
A
N
D
O
M

D
Y
N
A
M
IC

OPERATI
ONS
READ
WRITE
REWRITE
START

Relative
I

O
X

I-O

Indexed
E

X
X

O
X

X
X

X
X

X
X

X
X

X
X

X
X
X

REWRITE

X
X
X
X

X
X
X

X
X

X
X

I-O
X

START
DELETE

START
DELETE

X
X
X

WRITE
REWRITE

READ
WRITE

DELETE
READ

I-O

X
X
X

X
X

Unit 5
TABLE HANDLING

Introduction : Table Handling


Consider a situation of accepting 100 numbers from the user , display all
The numbers in sorted order.
Types of tables

One dimensional table

Two dimensional table

Multidimensional table
Table is a list of logically similar items.
Notes:
Obviously declaring 100 data items in W-S section and sorting them becomes
practically impossible.
Tables or Arrays provide the solution to handle situations discussed above.
If volume of data to be processed is large and if they are not stored in files,
then tables are used.

OCCURS Clause
Specifies number of occurrences or elements of the table.
WORKING-STORAGE SECTION
01 Marks.
02 Mark Table1
OCCURS 10 TIMES PIC 9(2).

Valid

02 Mark Table2

PIC 9(2) OCCURS 10 TIMES

02 Mark Table3

PIC 9(2) OCCURS 10TIMES VALUE 10 valid

Notes:
OCCURS clause causes setting up of area for holding the table elements.
Following rules must be followed with the usage of OCCURS clause.
1. The Integer must be positive.
2. Clause cannot be specified for an item whose level is 01, 66, 77, 88.
3. Value clause should not be specified with occurs clause.
4. OCCURS clause can be specified for file-section entries for both group
items as well as elementary items.

Valid

Subscript
Indicates the position of an element in the table.
PROCEDURE DIVISION
Marks Table (Subscript)

Parentheses required

Marks Table (I)


Marks Table (5)
Marks Table (12)

Valid provided I declared in data division.


Valid.
Invalid.

Notes:

Subscript can be a COBOL variable or a literal. Value of subscript must not exceed the range of
no. of occurrences specified by OCCURS clause.

If OCCURS clause is specified for a group items subscript should be specified for all elementary
items of that group.

Subscript should be specified for only data items defined with OCCURS clause, whenever used in
procedure division.

INDEXING

An index-name is an identifier that becomes associated with a particular table. The value in an
index is the displacement from the beginning of the table based upon the length of the
table
element.

An index-name may appear on an OCCURS clause, e.g.


01 TABLE-OF-MONTHS.
02 MONTHS OCCURS 12 TIMES.
PIC X(10) INDEXED BY NDX.

The index-name is created by the compiler; it does not have to be defined


elsewhere in the program.

The contents of an index may be changed by the SET TO statement

An index may not be used in a MOVE statement or an INITIALIZE statement.

Notes:
Indexing allows such operations as table searching and manipulating specific items.
To use indexing you associate one or more index-names with an item whose data
description entry contains an OCCURS clause. An index associated with an index-name
acts as a subscript, and its value corresponds to an occurrence number for the item to
which the index-name is associated.
The INDEXED BY phrase, by which the index-name is identified and associated
with its table, is an optional part of the OCCURS clause. There is no separate
entry to describe the index associated with index-name. At run time, the contents of the
index corresponds to an occurrence number for that specific dimension of the table
with which the index is associated.

One Dimensional Tables


Specified by one subscript or index
Example:
01 ABC.
02 XYZ PIC X(10) OCCURS 10 TIMES.

XYZ(1)

WHERE 1 Specifies the first element of XYZ.

Two Dimensional Tables


Specified by two subscripts or indexes.
Student (3 5)
Marks (3 5)

=5th Subject of 3rd Student.


=5th Marks of 3rd Student.

If it requires storing the Marks of N subject for M students then we require two
OCCURS clauses.
Notes:
Two dimension tables are used most frequently in applications. Consider for examples, 10 Students of a class
appeared for 8 subjects in their annual exams and you need to code a program to store and retrieve the data.
Data includes names of all the students, marks and names of corresponding subjects.
To store the marks of n subjects of one student, one dimension table serves the purpose. If number of students
is more than one than for each student there OCCURS n subjects and marks. Next foil shows the W-S
declarations for this example.

Multidimensional Table
Each OCCURS clause adds a dimension in nested occurs.
Ex:
01

Multidimensional.
02
First-dim
OCCURS 10 TIMES
02
Second-dim
OCCURS 5 TIMES.
05Second
PIC
05Third-dim OCCURS 10 TIMES
10Third
PIC

Notes:
COBOL supports multidimensional tables up to 7 levels .

PIC
A.
5.

X.

Table-Sorting

Use Sorting techniques to sort a table.


e.g Bubble sort
PERFORM VARYING I FROM 1 BY 1 UNTIL I = N
PERFORM J FROM I BY 1 UNTIL J > N
IF A[I] > A[J]
MOVE A[I] TO TEMP
MOVE A[J] TO A[I]
MOVE TEMP TO A[J]
END-IF
END-PERFORM
END-PERFORM.
I and J are used as subscripts for comparing elements of the table.
Notes:
Sorting is the process of arranging the elements of table in order. Searching for a particular element of the
sorted table, requires less time when compared to searching from an unsorted table.
SORT verb available in COBOL is limited to File sorting.

SET Verb
SET verb initializes and / or changes the value of index.
E.g. :
SET K To 1

K is initialized to 1

SET K UP BY 2

Value increment by step of 2.

SET K DOWN BY 2

Decrements by step of 2

MOVE verb cannot be used for index.


E.g. : SET data-name-1, data-name-2 TO K

SET verb moves of value of K to data-name-1 and data-name-2.


Notes:
Even though indexes assume the displacement values for table elements internally, programmer sets the value of
index by specifying the position of an element.

This means an index indicates the position of an element in the table similar to subscript, but internally it is processed
a different manner, but more efficient

SEARCH Verb
Searches for a particular value in the table, which has an index.
SEARCH Table name AT END statement
WHEN condition statement
Ex : SET K TO 1
SEARCH table-name AT END DISPLAY not found.
WHEN field-1 = element (K) DISPLAY element (K).
Notes:
In the above example, field-1 contains the required value to be searched for in the table,
More than one condition can be checked, with more than one WHEN clause.
All valid arithmetic operators can be used.
This form of search statement is called serial search.

Binary Search
Searches the table previously sorted, by splitting the table.
Faster than serial search
Only one WHEN clause is allowed.
SEARCH ALL Table-Name
.
WHEN.

other clauses
remain same.

Notes:
Before applying SEARCH ALL clause the table must be sorted.
SEARCH ALL causes the table to split into two halves. Then it determines which half of the table contains
the required value by comparing it to the last element of the first half and first element of the second half.
Again the selected half-table splits and continues and so on until the value is located .

ILLUSTRATES ONE-DIMENSIONAL ARRAYS


DATA DIVISION.
WORKING STORAGE SECTION.
77
CT
PIC
99
VALUE 0.
01
TAX-RATE.
05
RATE
PIC
999
OCCURS 5 TIMES.
* There should be a space before and after the braces.
01
MONTH-TABLE.
02
FILLER PIC
X(9)
VALUE January.
02
FILLER PIC
X(9)
VALUE February.
02
FILLER PIC
X(9)
VALUE March:
02
FILLER PIC
X(9)
VALUE April.
02
FILLER PIC
X(9)
VALUE May.
02
FILLER PIC
X(9)
VALUE June.
02
FILLER PIC
X(9)
VALUE July.
02
FILLER PIC
X(9)
VALUE August.
02
FILLER PIC
X(9)
VALUE September.
02
FILLER PIC
X(9)
VALUE October.
02
FILLER PIC
X(9)
VALUE November.
02
FILLER PIC
X(9)
VALUE December.
01
MONTH-NAME REDEFINES MONTH-TABLE.
02
MONTH PIC
X(9) OCCURS 12 TIMES.

PROCEDURE DIVISION.
100-MAIN-PARA.
PERFORM 200-FILL-PARA VARYING CT FROM 1 BY 1.
UNTIL CT>5.
PERFORM 300-DISP-PARA VARYING CT FROM 1 BY 1.
UNTIL CT>5.
PERFORM 400-MNTH-PARA.
STOP RUN.
200-FILL-PARA.
COMPUTE RATE ( CT ) = CT*100.
300-DISP-PARA.
DISPLAY RATE ( CT ).
400-MNTH-PARA.
DISPLAY Month as a number ?
ACCEPT CT.
IF CT< 1 OR > 12 DISPLAY Error in number
ELSE DISPLAY MONTH ( CT ).

ILLUSTRATES SEARCH VERB


DATA DIVISION.
01
MONTH-TABLE.
02
FILLER PIC
X(9)
VALUE January.
02
FILLER PIC
X(9)
VALUE February.
02
FILLER PIC
X(9)
VALUE March:
02
FILLER PIC
X(9)
VALUE April.
02
FILLER PIC
X(9)
VALUE May.
02
FILLER PIC
X(9)
VALUE June.
02
FILLER PIC
X(9)
VALUE July.
02
FILLER PIC
X(9)
VALUE August.
02
FILLER PIC
X(9)
VALUE September.
02
FILLER PIC
X(9)
VALUE October.
02
FILLER PIC
X(9)
VALUE November.
02
FILLER PIC
X(9)
VALUE December.
01
MONTH-NAME REDEFINES MONTH-TABLE.
02
MONTH OCCURS 12 TIMES INDEXED BY CT.
05
FIRST-THREE PIC X (3).
05
BALANCE-REST PIC X (6).
77
M-NAME PIC X (9) VALUE SPACES.

PROCEDURE DIVISION.
MAIN PARA.
DISPLAY Months Name please.
ACCEPT M-NAME.
SET CT TO 1.
SEARCH MONTH AT END DISPLAY Not Found.
WHEN M-NAME = MONTH ( CT ).
DISPLAY FIRST-THREE ( CT ).
STOP RUN.

ILLUSTRATE TWO-DIMENSIONAL ARRAYS


DATA DIVISION
WORKING-STORAGE SECTION.
01
WORK-AREA
05
MORE DATA
PIC A VALUE Y.
88
NO-MORE-DATA VALUE N.
01
TEMPERATURE-ARRAY.
05
DAY-IN-THE-WEEK OCCURS 24 TIMES.
10
HOURS-IN-THE-DAY OCCURS
24 TIMES.
15 DEGREE-TEMP PIC
S9(3).
77
DAY-OF-THE-WEEK
PIC 9.
77
TIME-OF-THE-DAY PIC 99.
77
HOUR-COUNT
PIC 99.
77
DAY-COUNT
PIC 9.
77
TOT-TEMP
PIC S999.
77

AVERAGE-TEMP

PIC S999.

PROCEDURE DIVISION.
100-MAIN-PARA.
PERFORM 200-DATA-ACCP-RTN UNTIL NO-MORE-DATA.
PERFORM 300-DATA-DISP-RTN.
STOP RUN.

200-DATA-ACCP-RTN.
DISPLAY Day of the Week : 1-Sunday.7-Saturday :
ACCEPT DAY-OF-THE-WEEK.
DISPLAY Time of the Day during Data Collection :
ACCEPT TIME-OF-THE- WEEK.
DISPLAY Temperature
ACCEPT DEGREE-TEMP (DAY-OF-THE-WEEK, TIME-OF-THE-DAY).
DISPLAY Anymore (Y/N):
ACCEPT MORE-DATA.
300-DATA-DISP-RTN.
PERFORM VARYING
DAY-COUNT FROM 1 BY 1
UNTIL DAY-COUNT > 7.
PERFORM VARYING
DAY-COUNT FROM 1 BY 1
UNTIL HOUR-COUNT > 24.
DISPLAY DAY : , DAY-COUNT, HOUR: ,
HOUR-COUNT, TEMP : ,
DEGREE-TEMP ( DAY-COUNT, HOUR-COUNT )
ADD DEGREE-TEMP ( DAY-COUNT, HOUR-COUNT )
TO TOT-TEMP.
COMPUTE AVERAGE-TEMP = TOT-TEMP / 168.
DISPLAY Weeks Average Temperature Is : ,
AVERAGE-TEMP.

ILLUSTRATES MULTIPLE INDEXES AND 3D ARRAYS


DATA DIVISION.
WORKING-STORAGE SECTION.
01
ENROLL-TABLE.
02 FACULTY OCCURS 3 TIMES INDEXED BY F1, F2.
03 DEPARTMENT OCCURS 6 TIMES INDEXED BY D1, D2.
04 YEAR OCCURS 5 TIMES INDEXED BY Y1, Y2.
05 FAC
PIC X (15).
05 DEPT
PIC X (10).
05 YY
PIC 9 (4).
77
ANYMORE PIC A VALUE Y.
PROCEDURE DIVISION.
100-MAIN-PARA.
SET F1, D1, F2, D2, Y2 TO 1.
PERFORM 200-ACC-PARA UNTIL SNYMORE = N.
DISPLAY THE CONTENTS OF 3 DIMENSIONSAL ARRAY ARE :
PERFORM VARYING R2 FROM 1 BY 1 UNTIL F2 > F1
AFTER
D2 FROM 1 BY 1 UNTIL D2 > D1.
AFTER
Y2 FROM 1 BY 1 UNTIL Y2 > Y1
DISPLAY RAC (F2, D2, Y2)
DISPLAY DEPT (F2, D2, Y2)
DISPLAY YY (F2, D2, Y2).
STOP RUN.

200-ACC-PARA.
DISPLAY ENTER FACULTY NAME.
ACCEPT FAC (F1, D1, Y1).
DISPLAY ENTER DEPARTMENT NAME:.
ACCEPT DEPT (F1, D1, Y1).
DISPLAY ENTER YEAR.
ACCEPT YY (F1, D1, Y1).
IF Y1 = 5
IF D1 = 6
IF F1 = 3
MOVE N TO ANYMORE
ELSE
SET F1 UP BY 1
END-IF
ELSE
SET D1 UP BY 1
END-IF
ELSE
SET Y1 UP BY 1.
DISPLAY ANYMORE.
ACCEPT ANYMORE

UNIT 6

Library Services

COPY Statement
The COPY statement is a library statement that places prewritten text in
a COBOL program
Each COPY must be terminated by a period
If library-name is omitted, then SYSLIB is assumed
Format:
>>____COPY____ _____text-name___ _____ _____________________________________>
|_
literal __|
|_ _OF _ ____ library-name_ ___|
|_IN_| |_ literal 2_______|
>____ ____________ _____ _________________________________________ ___ ______><
|_SUPPRESS__|

|
<______________________________ _|
|__REPLACING_______operand-1___BY__operand-2___|_|

Notes:
SUPRRESS means that the imbedded text will not be printed in the source program listing
COPY requires the LIB compiler option to be in effect
The COPY statement is a library statement that places prewritten text in a COBOL program.
Prewritten source program entries can be included in a source program at compile time. Thus, an installation
can use standard file descriptions, record descriptions, or procedures without recording them. These entries
and procedures can then be saved in user-created libraries; they can then be included in the source program
by means of the COPY statement.
Compilation of the source program containing COPY statements is logically equivalent to processing
all COPY statements before processing the resulting source program.
The effect of processing a COPY statement is that the library text associated with text-name is copied into
the source program, logically replacing the entire COPY statement, beginning with the word COPY and
ending with the period, inclusive. When the REPLACING phrase is not specified, the library text is copied
unchanged

Each COPY statement must be preceded by a space and ended with a separator period.
Debugging lines are permitted within library text and pseudo-text.
Comment lines or blank lines can occur in library text. Comment lines or blank lines appearing in library text
are copied into the resultant source program unchanged with the following exception: a command line or blank
line in library text is not copied if that comment line or blank line appears within the sequence of text
words that match operand-1

A COPY statement can appear in the source program anywhere a character string or a separator can appear;
however, a COPY statement must not be specified within a COPY statement. The resulting copied text
must not contain a COPY statement.

Nested COPY

COPY FILEA.
FILEA contains:
01 FILEA.
05 NAME PIC X(40).
COPY ADDRESS.
05 DATA PIC X(100).
Compile produces:
01 FILEA.
05
NAME
05 STREET
05
CITY
05
STATE
05
ZIP
05
DATA

PIC X(40).
PIC X(40).
PIC X(20).
PIC X(02).
PIC X(09).
PIC X(100).

ADDRESS contains:
05 STREET PIC X(40).
05 CITY
PIC X(20).
05 STATE PIC X(02).
05 ZIP
PIC X(09).

Notes:
COBOL allows nested COPY statements.
Nested COPY statements cannot contain the REPLACING phrase.
A COPY statement can appear in the source program anywhere a character string or a separator can appear.
As an IBM extension, COPY statements can be nested. However, nested COPY statements cannot
contain the REPLACING phrase, and a COPY statement with the REPLACING phrase cannot contain
nested COPY statements.
A COPY statement cannot cause recursion. That is, a COPY member can be named only once
in a set of nested COPY statements until the end-of-file for that COPY member is reached.

COPY REPLACING
To change some, or all, of the names in the library (COPYed) text, the programmer
can use the REPLACING option.
The text in the library is unchanged.
COPY PAYLIB REPLACING
FLDA BY PAY-RECORD
FLDA BY HRLY-RATE
FLDA BY HRS-WORKD.
LIBRARY TEXT
01 FLDA.
02 FLDB PIC 999V99.
02 FLDC PIC 999V99.

SOURCE PROGRAM
01 PAY-RECORD.
02 HRLY-RATE PIC 999V99.
02 HRS-WORKD PIC 999V99.

In the discussion that follows, each operand can consist of one of the following:

Pseudo-text

An identifier

A literal

A COBOL word

Function identifier

COPY Pseudo-Text

To change only part of the data-name(s) in the library text, the programmer can
use the REPLACING option with the standard pseudo-text delimiters (==)
COPY PAYLIB REPLACING
= = : PFFX: = =
BY = = PAY = =.
LIBRAR TEXT

SOURCE PROGRAM

01 :PFFX:.
02 :PFFX:-RTE
PIC 999V99.
02 :PFFX: - HRS
PIC 999V99.

01 PAY.
02 PAY-RTE
PIC 999V99.
02 PAY-HRS
PIC 999V99.

Notes :
Pseudo-text A sequence of character-strings and/or separators bounded by, but not including, pseudo-text-1
delimiters (= =). Both characters of each pseudo-text-1 delimiter must appear on one line; however,
character-strings within pseudo-text-1 can be continued.
Any individual character-string within pseudo-text-1 can be up to 322 characters long.
Pseudo-text-1 cannot be null, nor can it consist solely of the space character, separator comma, separator
semicolon, and/or of comment lines. Beginning and ending blanks are not included in the text
comparison process. Embedded blanks are used in the text comparison process to indicate multiple text words.
Pseudo-text must not contain the word COPY.

REPLACE Pseudo-test

Replace can be applied to the entire program, including text introduced through
COPY members

Replace action starts at a the REPLACE statement and continues until:


- Another REPLACE statement
- REPLACE OFF statement
- End of source program

REPLACE statements are processed by the compiler after any COPY statements
are processed

UNIT 7

CHARACTER HANDLING

STRING

Two or more fields can be concatenated or string in to single-field.

STRING
DELIMITED BY
DELIMITED BY
INTO id 7

(id- 1 | literal ), (id-2 | literal )


(id- 3 | literal | size |space),..
(id- 4 | literal )
(id- 4 | literal ), (id 5 | literal )
(with pointer id- 6 ).
(ON OVERFLOW statement)

Notes:
Delimited by clause specifies how the fields are concatenated, Its usage is described in
following foils.
With pointer option if used gives the total no. of characters in the concatenated field (id-7)
If the length of id-7 is not enough to hold the transferred characters, the statement after on
overflow option is executed.
One STRING statement can be written instead of a series of MOVE statements.
The following rules should be followed when this verb is used.
(i). This statement is used to concatenate one or more strings into one by placing them
side by side.
(ii). Sending strings may be alphanumeric literals, figurative constants or identifiers
with usage DISPLAY.
(iii). The receiving string, i.e., identifier- 7 must also be with usage DISPLAY.

STRING example :
DATA DIVISION.
WORKING-STORAGE SECTION.
77 ID-1 PIC X(7) VALUE 'CON,CON'.
77 ID-2 PIC X(7) VALUE 'CAT,CAT'.
77 ID-3 PIC X(6) VALUE 'ENATED'.
77 ID-4 PIC X(12).
77 COUNTER PIC 9(3) VALUE ZEROS.
PROCEDURE DIVISION.
STRING ID-1, ID-2, ID-3
DELIMITED BY ',' INTO ID-4
RESULT
Content if id-4: CONCATENATED.

The following example shows usage of size option.


77 F 1
PIC
X(7) VALUE HIGHTEC
77 F 2
PIC
X(7)
VALUE SPACES.
STRING MAIN DELIMITED BY SIZE F 1 INTO F 2.

ILLUSTRATES STRING VERB


DATA DIVISION.
WORKING STORAGE-SECTION.
01
FULL-NAME
PIC
01
FIRST-NAME
PIC
01
MIDDLE-NAME
PIC
01
LAST-NAME
PIC

X(30).
X(10)
X (10)
X (10)

VALUE SPACES.
VALUE SPACES.
VALUE SPACES.

PROCEDURE DIVISION.
100-MAIN-PARA.
MOVE RAJA TO FIRST-NAME.
MOVE ROMOHAN TO MIDDLE-NAME.
MOVE ROY TO LAST-NAME.
STRING FIRST-NAME,MIDDLE-NAME,LAST-NAME DELIMITTED BY
SPACE INTO FULL-NAME.

UNSTRING Statement
The UNSTRING statement is used to split a single data item into several data items
Format:

>>__UNSTRING___identifier-1__________________________________________________________>
>__ _____________________________________________________________________________ ___>
|_DELIMITED___ _____ ___ _____ ___ __identifier-2__ ____ __________________________|
|_BY_|
|_ALL_| |_literal-1______|
| <_____________________ |
|__OR_ ___ __ identifier-3_ _| |
|_ALL_| |_literal-2__|
>___INTO____________________________________________________________________________>
>____identifier-4__ _____________________________ ____ ___________________________ __| __>
|_DELIMITER__ ___ identifier-5 _|
|_COUNT__ ____ identifier-6___|
|_IN_|
|_IN__|
>___ ___________________________ ____ _______________________________ ______________>
|_ ____ _POINTER__identifier-7_|
|_TALLYING___ ____ __identifier-8_|
|_WITH_|
|_IN_|
>__ _____________________________________________ _________________________________>
|_ _____ ___OVERFLOW__imperative-statement-1___|
|_WITH_|
>___ __________________________________________________ ___ _________________ _______>
|_ NOT__ _____ __OVERFLOW__imperative-statement_2_|
|_END-UNSTRING_|
|_ON_|

Notes:

The UNSTRING statement causes contiguous data in a sending field to be separated and placed into multiple
receiving fields.
One UNSTRING statement can take the place of a series of MOVE statements, except that evaluation or
calculation of certain elements is performed only once, at the beginning of the execution of the UNSTRING
statement.
When the TALLYING phrase is specified, the field-count field contains a value equal to the initial value,
plus the number of data receiving areas acted upon.

ILLUSTRATES UNSTRING VERB


DATA DIVISION.
WORKING STORAGE-SECTION.
01
FULL-NAME
PIC
01
FIRST-NAME
PIC
01
MIDDLE-NAME
PIC
01
LAST-NAME
PIC

X(30).
X(10)
X (10)
X (10)

VALUE SPACES.
VALUE SPACES.
VALUE SPACES.

PROCEDURE DIVISION.
100-MAIN-PARA.
MOVE RAJA ROMOHAN ROY TO FULL-NAME.
UNSTRING FULL-NAME DELIMITTED BY SPACE INTO FIRST-NAME,
MIDDLE-NAME,LAST-NAME.

EXAMINE Statement

EXAMINE Identifier TALLYINY

EXAMINE Identifier REPLACING

EXAMINE Identifier TALLYINY

ALL
LEADING
UNTIL FIRST

ALL
LEADING
UNTIL FIRST

ALL
LEADING
UNTIL FIRST

REPLACING BY Literal - 5

Literal - 1

Literal - 2 BY Literal - 3

Literal - 4

Notes:
This verb is used to scan a string to find the number of occurrences of a given character in it.
In addition, the Verb can also be use to replace some or all occurrences of the said character
by another character.

Eg :
Let us consider the following DATA DIVISION entry
77 A PIC X(5) VALUE IS PPRIP.
Now the statement
EXAMINE A TALLYING ALL P.
Will store 3 in the TALLY register as there are altogether three Ps in the string.
However the statement
EXAMINE A TALLYING LEADING P
Will store 2 in the TALLY , Since there are only Two leading Ps.

The statement
EXAMINE A TALLYING UNTIL FIRST I.
Will store 3 in the TALLY as there are only Three characters before the character I.
It may be noted here that if a particular character is not found, TALLY is set to
Zero, When the ALL or LEADING phrase is used. For e.g.. In the statement

EXAMINE A TALLYING LEADING R


Will set TALLY to zero, Since the leading character is not R.
If the UNTIL FIRST phrase is used and the specified character is not found, the TALLY will
contain the size of the string

EXAMINE---REPLACING.

EXAMINE A TALLYING ALL P REPLACING BY Q

Will store 3 in the TALLY register and will change the content of A to QQRIQ.
EXAMINE A REPLACING FIRST I BY M

Will change the content of A to PPRMP.


EXAMINE A REPLACING UNTIL FIRST I BY Y

Will change the content of A to YYYIP.


In each of the cases A is assumed to be defined as before.

INSPECT TALLYING Statement


The INSPECT statement specifies that characters, or groups of characters, in a data
item are to be counted (tallied) or replaced or both.
It will count the occurrence of a specific character (alphabetic,
numeric, or special character) in a data item.
It will fill all or portions of a data item with specified characters,
such as spaces or zeros.
It will convert all occurrences of specific characters in a data item
to user-supplied replacement characters.

Format:
>>___INSPECT___identifier-1______TALLYING____________________________________________________>
<___________________________________________________________________________________
<_______________________________________________________
|
>____identifier-2___FOR____ __CHARACTERS____ ____________ _| _____________________ __ | __|_____>
|
|_|phrase 1 |__|
|
|
< _____________________________________ |
|
<_______________________ | |
|__ __ALL _________ ___ __identifier-3___ __ ___________ _| _| _|
|_LEADING______|
|_literal________|
|_ | phrase 1 _|
>_____REPLACING____________________________________________________________________________>
<_______________________________________________________________________________
>_______ __CHARACTER BY____ _identifier-5__ ______ _______________ __|__________________ __|____>
|
|_literal-3____|
|__| phrase
|_|
|
|
<_______________________________________________________
|
|
<________________ | |
|__ ALL_____ ______ ___identifier-3___ ___BY__ _identifier-5__ ____ ______________| _| _|
|_LEADING_|
|_literal-1________|
|_literal-3____|
|_| phrase 1 |__|
phrase 1:
|__ __BEFORE__ __ _____________ __ _identifier-4__________________________________________________|
|_AFTER___|
|_INITIAL_____| |_literal-2__|

Notes:

TALLING Phrase counts the occurrence of a specific character (alphabetic, numeric,


or special character) in a data item.
Identifier-1:
Identifier-1 is the inspected item and can be any of the following:

An alphanumeric data item

An numeric data item with USAGE DISPLAY

An external floating point item


Identifier-2
Is the count field, and must be an elementary integer item defined without the symbol P in
its PICTURE character-string
You must initialize identifier-2 before execution of the INSPECT statement begins.
Identifier-3 or literal-1
Is the tallying field (the item whose occurrences will be tallied).

Eg:
PROCEDURE DIVISION.
INSPECT HELLO TALLYING TALLY-COUNT FOR ALL A
Let the picture of HELLO be X(20) and suppose its content before the execution of the
above statement is as follows :

APARNAbKUMARIbAMMAbb
If picture of TALLY-COUNT is 9(2) and originally contains 08, then after the execution
of the statement, TALLY-COUNT will contain 14, as there are a total of 6 As in HELLO.

If ALL in the statement is changed to LEADING , TALLY-COUNT will be increased


to 9, as there is only
one leading A. if CHARACTERS is specified instead of ALL
A, TALLY-COUNT will be increased to 28 as there are a total of 20 characters in HE LLO.

INSPECT REPLACING Statement


This phrase fills all or portions of a data item with specified characters, such as spaces or Zeros.
When REPLACING CHARACTERS is used the identifier-5 must be 1 character in length
Format:
>>___INSPECT___identifier-1___REPLACING______________________________________________>
<___________________________________________________________________________
>_______ __CHARACTERS BY___ __identifier-5__ ____ ___________ ___ | ____________ __| ___>
|
|_literal-3______|
|_| phrase 2 |_|
|
|
<__________________________________________________ |
|
<_____________
| |
|_ ALL_____ _______ identifier-3_ ___BY__ __identifier-5__ _ _________ _| _| _|
|_LEADING_|
|_literal-1___|
|_literal-3______| |_| phrase 1 |_|
phrase 1:
|___ BEFORE_ __ ________ __ identifier-4_ ________________________________________________|
|_AFTER_| |_INITIAL_| |_literal-2___|
INSPECT DATA1 REPLACING ALL BY 0
INSPECT DATA2 REPLACING FIRST ZERO BY SPACE
INSPECT DATA3 REPLACING CHARACTER ZERO BY X
INSPECT DATA4 REPLACING LEADING 0 BY SPACE

REPLACING Phrase
-identifier-3 or literal-1
Is the subject field (the item whose occurrences are replaced).
Identifier-3 can be:

An elementary alphanumeric data item

A numeric data item with USAGE DISPLAY

An external floating point item


Literal-1 must be non-numeric, and can be any figurative constant that does not begin with the word ALL. If
literal-1 is a figurative constant, it is considered to be a 1-character nonnumeric literal.
Identifier-5 or literal-3
Is the substitution field
Identifier-5 can be:

An elementary alphanumeric data item

A numeric data item with USAGE DISPLAY

An external floating point item


Literal-3 must be nonnumeric, and can be any figurative constant that does not begin with the word ALL.

The following replacement rules apply:


When the subject field is a figurative constant, the single-character substitution field(which
must be 1 character in length) replaces each character in the inspected item equivalent
to the figurative constant.

When the substitution field is a figurative constant, the substitution field replaces each
non-overlapping occurrence of the subject field in the inspected item.

When the subject and substitution fields are character-strings, the character-string specified
in the substitution field replaces each non-overlapping occurrence of the subject field in the
inspected item

UNIT 8

SORT / MERGE

SORT/MERGE

SORT Statement

MERGE Statement

SORT PROCEDURES

RELEASE/RETURN Statements

SORT Statement
The SORT statement accepts records, sorts them according to specified keys, and makes the
sorted results available for further processing.
Format 1:
SORT file-name-1 ON ASCENDING/DESCENDING KEY data-name-1 USING file-name-2
GIVING file-name-3.

Format 2:
SORT file-name-1 ON ASCENDING/DESCENDING KEY data-name-1 INPUT PROCEDURE IS
Procedure-name-1[THRU Procedure-name-2] USING file-name-2 GIVING file-name-3.
Format 3:
SORT file-name-1 ON ASCENDING/DESCENDING KEY data-name-1 INPUT PROCEDURE IS
Procedure-name-1[THRU Procedure-name-2] USING file-name-2
OUTPUT PROCEDURE IS Procedure-name-3[THRU Procedure-name-4]
GIVING file-name-3.

Notes:
The SORT Statement accepts records from one or more files. Sorts them according to the specified key(s),
and makes the sorted records available either through an OUTPUT PROCEDURE or in an output file.
The SORT Statement can appear any where in the procedure division except in the declarative portion.
File-name-1
The name given in the SD entry that describes the records to be sorted.
No pair of file-names in a SORT statement can be specified in the same SAME SORT AREA , or Same
SORT-MERGE AREA clause. File-names associated with the giving clause (file-name-3)
cannot be specified in the SAME AREA clause.
File-names associated with the giving clause (file-name-3) can be specified in the SAME AREA clause.
ASCENDING / DESCENDING KEY phrase
This Phrase specifies that records be to be processed in ascending or descending sequence
(depending on the phrase specified), based on the specified sort keys.
When the GIVING phrase is specified , all the sorted records I the file-name-1 are automatically transferred
to the output files ( file-name-3).

MERGE Statement
The MERGE statement combines two or more identically sequenced files(that is, files that have already
been sorted according to an identical set of ascending/descending keys) on one or more keys and makes
records available in merged order to an output procedure or output file.
Format:
>>___MERGE__file-name-1____ _____ ___ __ASCENDING__ ___ _______ __data-name-1__| __|_>
>___ _____________________________________________________ __USING__file-name-2_______>
|__ ________________ __SEQUENCE__ ____ _alphabet-name-1_|
|_COLLATING____|
|_IS_|
<__________________
>_____file-name-3__|___________________________________________________________________>
>___ __OUTPUT PROCEDURE___ ___ __procedure-name-1__ __________________________ _ _><
|_
|_IS_|
|_ _ THROUGH_ procedure-name-2_| _|
|
|_THRU____|
|
|
<________________
|
|_ GIVING___file-name-4__| _________________________________________________________|

Notes:
The MERGE statement combines two or more identically sequenced files(that is, files that have already
been sorted according to an identical set of ascending/descending keys) on one or more keys and makes
records available in merged order to an output procedure or output file.
A MERGE statement can appear anywhere in the Procedure Division except in a Declarative Section.
The file names given must be in the SD entry.
When the MERGE statement is executed, all records contained in file-name-2, file-name-3,., are
accepted by the merge program and then merged according to the key(s) specified.

SORT PROCEDURES

Procedures can add, delete, alter or edit the records

With SORT .INPUT PROCEDURE you can specify processing to be


performed on the records before they are sorted

With SORT ..OUTPUT PROCEDURE you can specify processing to be


performed on the records after they are sorted

In an input procedure the RELEASE statement is used to place a record into the
file to be sorted

In an output procedure the RETURN statement is used to extract a record from


the sorted file

Notes:

INPUT PROCEDURE Phrase


This phrase specifies the name of a procedure that is to select or modify input records before the sorting operation
begins.
The input procedure can consist of any procedure needed to select, modify or copy the records that are made available
one at a time by the RELEASE statement to the file referenced by file-name-1. The range includes all statements that
are executed as the result of a transfer of control by CALL, EXIT, GO TO, and PERFORM statements in the range of
the input procedure, as well as all statements in declarative procedures that Sare executed as a result of the execution of
statements in the range of the input procedure. The range of the input procedure must not cause the execution of any
MERGE, RETURN, or SORT statement.
If an input procedure is specified, control is passed to the input procedure before the file referenced by file-name-1 is
sequenced by the SORT statement. The compiler inserts a return mechanism at the end of the last statement in the input
procedure. When control passes the last statement in the input procedure, the records that have released to the file
referenced by file-name-1 are sorted.

OUTPUT PROCEDURE Phrase


This phrase specifies the name of a procedure that is to select or modify output records
from the sorting operation.
The output procedure can consist of any procedure needed to select, modify, or copy the records that are
made available one at a time by the RETURN statement in sorted order from the file referenced by filename-1. The range includes all statements that are executed as the result of a transfer of control by CALL,
EXIT, GO TO, and PERFORM statements in the range of the output procedure. The range also includes
all statements in declarative procedures that are executed as a result of the execution of statements in the
range of the output procedure. The range of the output procedure must not cause the execution of any
MERGE, RELEASE, or SORT statement.
If an output procedure is specified, control passes to it after the file referenced by file-name-1 has been
sequenced by the SORT statement. The compiler inserts a return mechanism at the end of the last
statement in the output procedure and when control passes the last statement in the output procedure, the
return mechanism provides the termination of the sort and then passes control to the next executable
statement after the SORT statement. Before entering the output procedure, the sort procedure reaches a
point at which it can select the next record in sorted order when requested. The RETURN statements in
the output procedure are the requests for the next record.

RELEASE Statement
The RELEASE statement is only used within the INPUT PROCEDURE of a SORT

The RELEASE statement makes the contents of record-name-1 available to the initial phase of
the SORT process

Upon completion of the INPUT PROCEDURE, the sort file consists of all records placed
there by the RELEASE statement
Format:
____RELEASE____record-name-1____ _____________________________ ____________________><
|_FROM___identifier-1___________|

Figure 8-5 RELEASE Statement


Notes:
The RELEASE statement transfers records from an input/output area to the initial phase of a sorting operation.
The RELEASE statement can only be used within the range of an INPUT PROCEDURE associated with a
SORT statement.
Within an INPUT PROCEDURE, at least one RELEASE statement must be specified.

RETURN Statement

The RETURN statement is used only within the OUTPUT PROCEDURE of a


SORT or MERGE
The RETURN statement acts like a READ and makes the next record from the
sort/merge processing available to the application
The AT END clause must be specified

Format:
>>___RETURN___file-name-1___ ______________ ____ _____________________________ _______>
|_ RECORD __|
|_INTO___identifier-1___________|
>___ _____ ____END___imperative-statement-1____________________________________________>
|_ AT _|
>___ _____________________________________________________ ___ ______________ _____>
|_NOT____ _____ __END______imperative-statement-2______|
|_ END-RETURN_|
|_AT__|
Notes:
The RETURN statement transfers records from the final phase of a sorting or merging operation to an
OUTPUT PROCEDURE.
The RETURN statement can be used only within the range of an OUTPUT PROCEDURE associated with a
SORT or MERGE statement.

EXAMPLE : SORT
IDENTIFICATION DIVISION.
PROGRAM-ID. SORTING.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT IN-FILE ASSIGN TO DD1
ORGANIZATION IS SEQUENTIAL.
SELECT WORK-FILE ASSIGN TO DD2
SELECT OUT-FILE ASSIGN TO DD3
ORGANIZATION IS SEQUENTIAL.
DATA DIVISION.
FILE SECTION.
FD IN-FILE.
01 IN-REC.
02 NUMPICX(2).
02 NAMEPICX(10).
02 ADDR PICX(10).
02 FILLERPICX(58).
SD WORK-FILE.
01 WORK-REC.
02 WNUMPICX(2).
02 WNAMEPICX(10).
02 WADDR PICX(10).
02 FILLERPICX(58).
FD OUT-FILE.
01 OUT-REC PICX(80).
WORKING-STORAGE SECTION.
PROCEDURRE DIVISION.
SORT WORK-FILE ON ASCENDING KEY WNUM USING IN-FILE GIVING OUT-FILE.
STOP RUN.

UNIT 9
CALL Statement

CALL Statement
The CALL statement transfers control from one object program to another within the run unit

CALL identifier-1

USING [BY CONTENT/BY REFEERENCE] data-

name-1 [, data-name-2]
Literal-1
[ ; ON OVERFLOW imperative-statement ]

Notes:
The CALL statement transfers control from one object program to another within the run unit.
The program containing the CALL statement is the calling program; the program identified in the CALL
statement is the called subprogram. Called programs can contain CALL statements; however, a called program
must not execute a CALL statement that directly or indirectly calls the calling program unless it has the
RECURSIVE attribute.

CALL BY CONTENT/REFERENCE
The CALL.BY REFERENCE technique allows the sub-program to access and process the
data- items in the callers storage.

The CALL.BY CONTENT technique allows the sub-program to access and process a copy of the
items from the callers storage. The sub-program cannot change the original data values in the
callers
storage.
A single CALL statement may have both data passing techniques.

data-

WORKING-STORAGE SECTION.
01 RECORD-A.
05 FIELD1 PIC
05 FILLER
.
PROCEDURE DIVISION.
.
CALL xxxxxxxx USING BY REFERENCE RECORD-A
BY CONTENT LENGTH OF RECORD-A
Notes:
BY REFERENCE Phrase
If the BY REFERENCE phrase is either specified or implied for a parameter, the corresponding data item in the
calling program occupies the same storage area as the data item in the called program.

BY CONTENT Phrase
If the BY CONTENT phrase is specified or implied for a parameter, the called program cannot change the
value of this parameter as referenced in the CALL statements USING phrase, though the called program
can change the value of the data item referenced by the corresponding data-name in the called programs
Procedure Division header. Changes to the parameter in the called program do not affect the
corresponding argument in the called program.
BY VALUE Phrase
The BY VALUE phrase applies to all arguments that follow until overridden by another BY REFERENCE
or BY CONTENT phrase.
If the BY VALUE phrase is specified or implied for an argument, the value of the argument is passed, not
a reference to the sending data item. The called program can modify the formal parameter corresponding
to the BY VALUE argument, but any such changes do not affect the argument since the called program
has access to a temporary copy of the sending data item.
These options are Compiler dependent.

LINKAGE SECTION

The LINKAGE SECTION of the DATA DIVISION describes data made available
from another program

Storage is NOT reserved

The VALUE clause may not be specified (except for level-88 items)
Notes:
The Linkage Section describes data made available from another program or method. The Linkage Section may be
composed of two entry types:

Record-description-entry

Data-item-description-entry

GLOBAL DATA

The GLOBAL clause specifies that a data-name is available to every program contained
within the program that declares it, as long as the contained program does not itself have a
declaration for that name. All data-names subordinate to or condition-names or indexes
associated with a global name are global names.
The GLOBAL clause can be specified in the Working-Storage Section, the File Section,
the Linkage section, and the Local-Storage Section, but only in data description entries
whose level-number is 01 or FD.
An item may have both GLOBAL and EXTERNAL clauses.
GLOBAL only applies to Nested Programs.

Notes
GLOBAL in FILE SECTION.
The GLOBAL clause specifies that the file connecter named by a file-name is a global name. A global file-name is availabl
to the program that declares it and to every program that is contained directly or indirectly in that program.

A file name is global if the GLOBAL clause is specified in the file description entry for that file-name. A record name is
global if the GLOBAL clause is specified in the record description entry by which the record-name is declared or, in the
cause of record descreiption entries in the File Section, if the GLOBAL clause is specified in the file description entry for th
file-name associated with the record description entry

GLOBAL in Data Descriptions


The GLOBAL clause specifies that a data-name is available to every program contained within the
program that declares it, aslong as the contained program does not itself have a declaration for that name.
All data-names subordinates to or condition-names or indexes associated with a global name are global
names.

A data-name is global if the GLOBAL clause is specified either in the data description entry by which the
data-name is declared or in another entry to which that data description entry is subordinate.
A statement in a program contained directly or indirectly within a program which describes a global name
reference that name without describing it again.
Two programs in a run unit can reference common data in the following circumstances:
1.
The data content of an external data record can be referenced from any program provided that
program has described that data record.
2.
If a program is contained within another program, both programs can refer to data possessing the
global attribute either in the containing program or in any program that directly or
indirectly contains the containing program.

Sample Program
ID DIVISION.
PROGRAM-ID. MPGM.
..
DATA DIVISION.
WORKING-STORAGE SECTION.
01 MNTEC PIC X(32) GLOBAL.
PROCEDURE DIVISION.
MOVE BEGINNING CONTENTS TO MNTEC
CALL SUBPGM
DISPLAY MNTEC.
STOP RUN.
IDENTIFICATION DIVISION.
PROGRAM-ID. SUBPGM.
DATA DIVISION.
WORKING-STORAGE SECTION.
PROCEDURE DIVISION.
DISPLAY ENTERING SUBPROGRAM.
DISPLAY MNTEC.
MOVE ENDING CONTENTS TO MNTEC.
DISPLAY LEAVING SUBPGM.
EXIT PROGRAM.
END PROGRAM SUBPGM.
END PROGRAM MPGM.

UNIT 10

PROGRAM EXECUTION PROCESS

PROGRAM EXECUTION PROCESS

COMPILATION

LINK-EDITING

LOAD MODULE EXECUTION

FLOW CHART OF EXECUTION PROCESS USING JCL

Three steps are needed to process a COBOL program:

Compilation
Link-editing
Load module execution

SOURCE
PROGRAM
COMPILATION
OBJECT
MODULE

MESSAGES AND
LISTING

LINK
EDITING
LOAD
MODULE
LOAD
MODULE
EXECUTION
OUTPUT

MESSAGES AND
LISTINGS

Notes:
The source program is the input to the compilation step. The output from the compilation step is
called an object module.
The object module is the input to the link-edit step. The output of the link-edit step is the load module,
which must be saved as a member of a partitioned dataset.
The load module created from the source program is executed in execution step.

THREE STEPS JCL USED TO EXECUTE A COBOL SOURCE CODE.


The following listing shows the general format of JCL used to process a COBOL program.
//JOBNAME JOB,,
// CLASS=A,MSGCLASS=H,MSGLEVEL=(1,1),
//
NOTIFY=&SYSUID
1 //STEP1 EXEC PGM=IGYCRCTL
//STEPLIB DD DSNAME=IGY310.SIGYCOMP,DISP=SHR
//SYSPRINT DD SYSOUT=*
//SYSLIN DD DSNAME=MTPLB00.COBOL.OBJLIB,DISP=(MOD,PASS),
//
SPACE=(TRK,(10,10))
//SYSUT1 DD UNIT=SYSDA,SPACE=(CYL,(1,1))
//SYSUT2 DD UNIT=SYSDA,SPACE=(CYL,(1,1))
//SYSUT3 DD UNIT=SYSDA,SPACE=(CYL,(1,1))
//SYSUT4 DD UNIT=SYSDA,SPACE=(CYL,(1,1))
//SYSUT5 DD UNIT=SYSDA,SPACE=(CYL,(1,1))
//SYSUT6 DD UNIT=SYSDA,SPACE=(CYL,(1,1))
//SYSUT7 DD UNIT=SYSDA,SPACE=(CYL,(1,1))
//SYSIN DD DSN=MTPLB00.COB.PGM(PGM1),DISP=SHR

2 //STEP2 EXEC PGM=HEWL


//SYSLIB DD DSNAME=CEE.SCEELKED,DISP=SHR
//SYSPRINT DD SYSOUT=*
//SYSLIN DD DSNAME=MTPLB00.COBOL.OBJLIB,DISP=(OLD,DELETE)
//SYSLMOD DD DSNAME=MTPLB00.COBOL.LOADLIB(PGM1),
//
DISP=(MOD,PASS),
//
SPACE=(TRK,(10,10,1))
3 //STEP3 EXEC PGM=PGM1
//STEPLIB DD DSN=MTPLB00.COBOL.LOADLIB,DISP=SHR
Notes:
Each job step can be executed alone or in combination as a job.
In the first step, the COBOL compiler is IGYCRCTL and the input source code to this
Is specified in the SYSIN DD statement. The output created from this step is the object code, as stored
in the SYSLIN DD statement.
In the second step, the link-edit program is HEWL. The object code created from the previous step is the
input to this step, as specified in the SYSLIN DD statement. A load module is created which is saved as
a member of a PDS, as specified in the SYSLMOD DD statement.
The load module created from the previous step is now executed on the EXEC statement

COMPILATION PROCESS
A specific computer has a specific set of instruction that is fixed during the design
of the machine. This set of instructions constitutes what is commonly called
he machine language.
A program written in language other than the machine language is called a source
program. Whether it is a high-level language program or an assembly-language
program, the program cannot be executed directly.
The source language program should be translated to a machine language
program known as the object program.
If the source is a high level language, the corresponding translator program
is called a compiler.
Compiler is used to translate COBOL program into language that the computer
can process i.e. object code.

GENERAL COMPILER

//
//

The following statements show general JCL for a compilation job step.
//JOBNAME JOB ,,
CLASS=A,MSGCLASS=H,MSGLEVEL=(1,1),
NOTIFY=&SYSUID

//STEP1 EXEC PGM=IGYCRCTL


//STEPLIB DD DSNAME=IGY310.SIGYCOMP,DISP=SHR
//SYSPRINT DD SYSOUT=*
//SYSLIN DD DSNAME=MTPLB00.COBOL.OBJLIB,DISP=(MOD,PASS),
//
SPACE=(TRK,(10,10))
//SYSUT1 DD UNIT=SYSDA,SPACE=(CYL,(1,1))
//SYSUT2 DD UNIT=SYSDA,SPACE=(CYL,(1,1))
//SYSUT3 DD UNIT=SYSDA,SPACE=(CYL,(1,1))
//SYSUT4 DD UNIT=SYSDA,SPACE=(CYL,(1,1))
//SYSUT5 DD UNIT=SYSDA,SPACE=(CYL,(1,1))
//SYSUT6 DD UNIT=SYSDA,SPACE=(CYL,(1,1))
//SYSUT7 DD UNIT=SYSDA,SPACE=(CYL,(1,1))
//SYSIN DD DSN=MTPLB00.COB.PGM(PGM1),DISP=SHR

JCL KEYWORDS

STEP1 - The name of the job step. The exec statements specify that the COBOL
compiler (IGYCRCTL) is to be invoked.
STEPLIB - Definition of the data set where the COBOL compiler resides.
SYSLIN Definition of the data set that receives output.

SYSUT1 TO SYSUT7 Definitions of utility data sets used by the compiler


to process the source program. All SYSUT files must be on direct-access storage devices.
SYSIN Definition of the data set to be used as input to the job step.

CONTROL ON COMPILATION
The compiler lists errors in COBOL program statements and provides information to
help you debug program. You can direct and control compilation with the following:

Compiler-directing statements
Compiler options

COMPILER-DIRECTING STATEMENTS

Basis statement basis statement provides a complete program as the


source for a compilation.
*CONTROL or *CBL statement this statement suppresses or allows output to be produced.
Copy statement This statements place prewritten text in a COBOL program.
Delete statement This statement removes COBOL statements from the basis source program.
Eject statement This statement specifies that the next source statement is to be printed
at the next page.
Enter statement - The compiler treats this statement as a comment.
Insert statement This statement adds COBOL statements to the basis source program.
Replace statement This statement is used to replace source program text.
Skip1/2/3 statement These statements specify lines to be skipped in the source listing.
Title statement This statement specifies that a title be printed at the top of each page
of the source listing.
Use statement The use statement provides declaratives to specify the following:
Error handling procedures exception/error
User label-handling procedures label
Debugging lines and sections debugging

COMPILER OPTIONS
Compiler options help to control the compilation of program. Specify these options
in the PARM field of the JCL or on the process statement in program before
IDENTIFICATION DIVISION.
Syntax:
//STEP1 EXEC PGM=IGYCRCTL, PARM=SSRANGE,LIB,DYNAM,LIST

COMPILER OPTIONS DESCRIPTIONS

A] Diagnostic options
SSRANGE: SSRANGE is use to generate code that checks if subscripts or indexes
attempt to reference an area outside the region of the table. Variable-length items also
checked to confirm that their current length is within their maximum defined length.
Default is NOSSRANGE.
DUMP: Default is NODUMP. The dump option is use to produce a system dump at compile time.
FLAG: Default is FLAG (I). The syntax is FLAG (x, y), where x and y can be I, W, E, S, U.
To produce diagnostic messages for errors o a severity level x or above at the
end of the source listing using FLAG (x).
TEST: Default is NOTEST. Test is use to produce object code that can be executed
with batch or interactive debug.

B] VIRTUAL STORAGE OPTIONS


DYNAM: Default is NODYNAM. Use DYNAM to cause separately compiled programs
invoked through the call literal statement to be loaded dynamically at run time.
RENT: Default is NORENT. If program compiled using rent, then it generated as a
reentrant object module.
BUFSIZE: BUFSIZE option is use to allocate an amount of main storage to the buffer
for each compiler work data set.
Syntax is BUFSIZE (nnnnn/nnnK) where nnnnn denotes a decimal number that must be
at least 256. nnnK specifies a decimal number in 1K increments.
SIZE: Syntax is SIZE (nnnnn/nnnK/MAX).
nnnnnn specifies a decimal number that must be 778240.
nnnK specifies a decimal number in 1K increments.
The minimum acceptable value is 760K.
MAX requests the largest available block of storage in the user region for use during compilation.
Use SIZE to indicate the amount of main storage available for compilation.
Where 1K = 1024 bytes decimal.
DATA: Default is data (31). Specify the DATA(24) compiler option for programs running
in 31-bit addressing mode that are passing data parameters to programs in 24-bit
addressing mode.

C] SOURCE LANGUAGE OPTIONS


LIB: Default is NOLIB. COPY, BASIS, or REPLACE statements are use in a program that
time specify the lib option.
APOST/QUOTE: Default is QUOTE.
Specify QUOTE when you want the quotation mark () to be the
delimiter character for literals.
APOST use when you want the apostrophe () to be the delimiter
character for literals.
WORD: Use WORD(xxxx) to specify that an alternate reserved-word table is to be used during
compilation.Default is NOWD. WORD(xxxx) specifies the ending characters of the
name of the reserved-word table (IGYCxxxx) to be used in compilation. IGYC are the first
four standard characters of the name, and xxxx can be 1 to 4 characters in length.
NUMBER: Use number if you want program line numbers to be used in error messages line
number. Default is NONUM.
SEQUENCE: Default is sequence. If you specify sequence the compiler examines
column 1 to 6 of source statements to check that the statements are arranged
in ascending order according to their EBCDIC collating sequence.
CURRENCY: Default is NOCURR. The CURRENCY option to provide an alternate
default currency symbol to be used for the COBOL program. The default
is NOCURR. NOCURRENCY specifies that no alternate default currency
symbol will be used.

D] MAPS AND LISTINGS OPTIONS


XREF: Default is NOXREF. You can specify XREF, XREF (FULL) or XREF (SHORT). Use XREF to get a sorted crossreference listing. EBCDIC data-names and procedure names listed in alphanumeric order. DBCS data-names and procedurenames listed based on their physical order in the program.
LANGUAGE: Default is LANGUAGE (ENGLISH). To select the language in which compiler output will be printed
use language option.
LINECOUNT: Use LINECOUNT (nnn) to specify the number of lines to be printed on each page of the compilation listing, or
use LINECOUNT (o) to suppress pagination. Default is LINECOUNT (60).
LIST: Use list as a compiler option to produce listing of the assembler-language expansion of source code. Default is NOLIST.
MAP: Use map to produce a listing of the items defined in the data division. Default is NOMAP.
OFFSET: Use offset to produce a line numbers, statement references listings. Default is NOOFFSET.
SOURCE: To get a listing of source program using source compiler option. Default is SOURCE.
SPACE: Use space option to select single, double or triple spacing in source code listing. SPACE is meaningful only when
source is in effect. Default is SPACE (1).
VBREF: Default is NOVBREF. To get a cross-reference among all verb types used in the source program and line numbers in
which they are used.
TERMINAL: To send progress and diagnostic messages to the SYSTERM data set use TERMINAL option. Default is
NOTERMINAL.

E] OBJECT DECK OPTIONS


COMPILE: Use the COMPILE option if you want to force full compilation even in the presence
of serious errors. Default is NOCOMPILE(s).
DECK: To produce object code in the form of 80-column card image using DECK option.
Default is NODECK. For DECK option you define SYSPUNCH in JCL for compilation.
NAME: To generate a link-edit NAME card for each object module. NAME is also used to
generate names for each load module. Default is NONAME or NAME(NOALIAS).
OBJECT: To place the generated object code on disk or tape to be later used as input for
the linkage editor. Default is OBJECT.
PGMNAME: Syntax is PGMN(CO/LU/LM). Default is PGMNAME (COMPAT).
CO COMPAT
LU LONGUPPER
LM LONGMIXED
The PGMNAME option controls the handling of names used in the following:
Program names defined in the PROGRAM-ID paragraph.
Program entry point names on the entry statements.

F] OBJECT CODE OPTIONS

ADV: Default is ADV. ADV is meaningful only if you use WRITEADVANCING in source code. With ADV in effect,
the compiler adds 1 byte to the record length to account for the printer control character. Use NOADV if you have
already adjusted record length to include 1 byte for the printer control character.
AWO: Default is NOAWO. With AWO specified, the apply WRITE-ONLY clause will be in effect if any file within the
program is physical sequential with blocked V-mode records. The clause will be in effect even if it was not specified
within the program.
FASTSRT: FASTSRT allows IBM DFSORT or its equivalent, to perform the input and output instead COBOL. Default
is NOFASTSRT.
NUMPROC: Default is NUMPROC (NOPFD). Use NUMPROC(NOPFD) if you want the compiler perform invalid
sign processing. NUMPROC (PFD) is a performance option that can be used to bypass invalid sign processing.
OPTIMIZE: Default is NOOPTIMIZE. Use OPTIMIZE to reduce the run time of object program.
OUTDD: Default is OUTDD (SYSOUT). Use OUTDD if you want to run-time display output on the data set other than
SYSOUT.
TRUNC: Default is TRUNC (STD). TRUNC (STD) to control the way arithmetic fields are truncated during MOVE
and arithmetic operation.
ZWB: Default is ZWB. With ZWB, the compiler removes the sign from a sign external decimal field when comparing
this field to an alphanumeric elementary field during execution.

G] OTHER OPTIONS:
EXIT: DEFAULT is NOEXIT. If you specify the EXIT option without providing a least
one sub option, NOEXIT will be in effect. The sub options can be specified
in any order, separated by either commas or spaces

COMPILER ERROR MESSAGES


The messages for compilation errors found in program are displayed at the end of
the listing for each program. A summary of all errors found during compilation
is displayed at the bottom of listing. Each message issued by the compiler is of the
following form:
LineID
[nnnnnn]

Mwssage code
IGYppxxxx-L

Message text
Text of Message

nnnnnn The number of the source statement of the last line the compiler was processing.
IGY The Prefix that identifies this message as coming from COBOL compiler.
pp - Two characters that identify which phase of the compiler discover the error.
xxxx A 4-digit number that identifies the error message.
L A character that indicates the severity level of the error I, W,E,S or U

COMPILER ERROR MESSAGES CODES


Errors the compiler can fall into five categories of severity.
I (Informational, Return code=0) An informational-level message is an aid to the user.
No action is required from the user and the program will execute correctly.
W (Warning, Return Code=4) A warning-level massage calls attention to the possible
error. It is probable that the program will execute correctly as written.
E (Error, Return Code=8) An error-level message indicates the condition that
is definitely an error. The compiler has attempted to correct the error but results of
the program execution may not be what the user expects. The user should correct
the error.
S (Severe, Return Code=12) A severe-level massage indicates a condition that is
serious error. The compiler was unable to correct the error. The program will not
execute correctly and execution should not be attempted.
U (Unrecoverable, Return Code=16) An unrecoverable message indicates an error
condition of such magnitude that the compilation was terminated.

LINK-EDITING
Creating a Load Module
Large program may be developed in parts so that the program is in the form of a number
of routines. Each of these routines is separately translated. The object routines or object
module must then be combined together to form a load module or run unit, which is finally executed.
The step that accomplishes the job of linking the object routines or load modules into one
load module is called linkage editor.
The linkage editor converts an object module into a load module, and stores it in a partitioned
data set.
Linkage editor
//STEP2 EXEC PGM=HEWL
//SYSLIB DD DSNAME=CEE.SCEELKED,DISP=SHR
//SYSPRINT DD SYSOUT=*
//SYSLIN DD DSNAME=MTPLB00.COBOL.OBJLIB,DISP=(OLD,DELETE)
//SYSLMOD DD DSNAME=MTPLB00.COBOL.LOADLIB(PGM1),
//
DISP=(MOD,PASS),
//
SPACE=(TRK,(10,10,1))
SYSLMOD and SYSPRINT are the data sets used for linkage editor output.

LINK-EDIT OPTIONS
Syntax:
//STEP2 EXEC PGM=HEWL, PARM=CALL,PRINT,AMODE
Figure: Link-edit Options
Notes:
CALL: Use CALL if your program calls external routines, in which case you want external references to
be resolved by automatic library call.
PRINT: When you use the print option, link-edit messages and the module map are written on the data set
defined by the SYSLOUT DD statement.
AMODE: AMODE use to override the default RMODE attribute established by the compiler.
RENT: RENT option is use to have the linkage editor mark the load module as being reentrant and reusable.
REUS: REUS option is use to have the linkage editor mark the load module as being reusable.

LOAD MODULE EXECUTION

Executing compiled program


The program is ready for execution that has completed the compiling and link editing successfully.
Syntax:
//STEP3 EXEC PGM=PGM1
//STEPLIB DD DSN=MTPLB00.COBOL.LOADLIB,DISP=SHR

EXECUTION TIME OPTIONS


Specify run-time options in the PARM parameter of the EXEC statement that starts execution.
Syntax:
//STEP3 EXEC PGM=A,PARM=[user-parameter] [/execution-options]
Figure 10.7 Execution time options
Notes:
Where user-parameter is the parameter to be passed to the program being executed.
The execution-options are list of run-time options. A slash must immediately precede the first run time option.
NOSSRANGE & SSRANGEL: NOSSRANGE suppresses run-time checking of index, subscript,
reference modification and variable length group ranges. NOSSRANGE turns off run-time checking if compiled
with SSRANGE.
LANGUAGE: LANGUAGE option is use to specify the language and character set for those run-time
messages generated prior to the full initialization.
DEBUG & NODEBUG: NODEBUG suppresses the batch debugging features specified by the use for
DEBUGGING declaratives.
NOSTAE & STAE: NOSTAE prevents the run-time environment from intercepting an ABEND.

UNIT 10

COBOL Intrinsic Functions

Intrinsic Functions

Intrinsic functions allow you to access certain values that are derived at run time
Examples
Current-date
Length
Lower-case
Date-of-integer

Coded as part of statements in the Procedure Division

FUNCTION is now a reserved word

Notes:
Intrinsic functions are coded in statements in the procedure division. The function is evaluated and the
value participates in the statement execution. Functions may not stand alone they must be coded as part of
another statement.
Notice that the word FUNCTION is now a reserved word in COBOL. But the names of the functions are
not reserved.

Instrinsic Functions Syntax

Specify the reserve word FUNCTION followed by the name


of the function

Instrinsic Functions may not be used as a receiving operand


Examples
Move function current-date to d-string
If function date-of-integer(base-date)
When function day-of-integer(base-date)

Intrinsic Functions Arguments and Values

The number and format of the arguments depend on the function

The resulting value is an elementary data item implicitly defined by COBOL

Numeric and integer functions may only be used where arithmetic expressions may be used

If function value is a character(alphanumeric) string, the reference may be followed


by a reference modification
Move function current-date (1:8) to rpt-string
Notes:

The number and format of the arguments depend on the function

The resulting value is an elementary data item implicitly defined by COBOL

The value is a character string, a numeric value, or an integer

The length of the result depends on the function and the length of the argument(s)

COBOL Intrinsic Functions Date Formats


Range: January 1, 1601 to December 31, 9999

Gregorian Date YYYYMMDD

Integer Date - 1 to 3,067,671 number of days since December 31, 1600

Julian Date YYYYDDD


Notes:
Before we examine date type intrinsic functions, we need to define threee basic date formats that
can work with
Gregorian date, or Standard date
An eight digit date of the form YYYYMMDD
In the range of January 1, 1601 throug December 31, 9999
With MM being from 01 through 12 and DD being from 01 through 31, dependent
upon the month

COBOL

Integer date
An integer in the range 1 to 3,067,671
Represents the number of days since December 31, 1600
For example, January 1, 1994 is 143908 as an integer date

Julian date
A seven digit integer of the form YYYYDD
DDD is between 1 and 366, must be valid for the year(that is, leap year are
taken into account)

COBOL Instrinsic Functions- CURRENT-DATE


MOVE FUNCTION CURRENT-DATE(1:8) TO DATE-ON-FILE
Returns a character string length 21
YYYYMMDDHHmmsshhShhmm
System Gregorian date
Current time in 24 hour clock
Difference from GMT
Notes:
Current-date returns a character string of length 21, as follows:
YYYYMMDDHHmmsshhShhmm

Representing
A Gregorian date(YYYYMMDD)
Current time in hours (24-hour clock), minutes, seconds, and hundredths of a
second(HHmmsshh)
Difference of local time zone from Greenwich Mean Time as a + or - followed by
the hours and minutes difference (Shhmm)

COBOL Intrinsic Functions DATE-OF-INTEGER


COMPUTE RPT-DATE = FUNCTION DATE-OF-INTEGER(INT-DATE)
* If INT-DATE is integer 144337 then RPT-DATE is integer 19960317
Returns a Gregorian date using an inputted integer date
*
*

Based on number of days since Dec. 31, 1600


Integer could have been output of date intrinsic function modified by
arithmetic

Notes:

Date-of-integer converts an integer date to a Gregorian date


Function date-of-integer(argument)

The argument must be a valid integer date


The function reference is an integer representing YYYYMMDD

COBOL Intrinsic Functions INTEGER-OF-DAY


COMPUTE INT-DATE = FUNCTION INTEGER-OF-DAY(JUL-DATE)
* If JUL-DATE is integer 1996107 then INT-DATE is integer 144337
Returns an integer using an inputeed Julian date
*
*

Number of days since Dec. 31, 1600


Integer can be used for date arithmetic or date comparisons.

Notes:
Integer-of-day converts a Julian date to an integer date
Function integer-of-day(argument)
The argument must be a valid Julian date(YYYYDDD)
The function reference is an integer date

COBOL Intrinsic Functions DAY-OF-INTEGER

COMPUTE JUL-DATE = FUNCTION DAY-OF-INTEGER(INT-DATE)


* If INT-DATE is integer 144337 then JUL-DATE is integer 1996107

Returns an Julian date using an inputeed Julian date


Based on number of days since Dec. 31, 1600
Integer could have been output of date intrinsic function of Gregorian

Notes:
Day-of-integer converts a Integer date to an Julian date
Function integer-of-day(argument)
The argument must be a valid integer date
The function reference is an integer representing YYYYDDD

date

New Intrinsic Functions Overview

New Intrinsic Functions


DATE-To-YYYYMMDD
DAY-TO-YYYYDDD
YEAR-TO-YYYY

First function argument is date with two position year


(yymmdd, yyddd, or yy)
Second function argument is an optional integer that is used in determination of
100-year range used in YY to YYYY conversion. Default is 50
Returned value is a date of the same type as the first argument but with a four
digit year

Notes:

New Intrinsic Functions


The second argument to these three functions is called the sliding window,
and it works this way:
Add the second argument to the current (run-time) year ( as a four digit year), giving an ending
year.
For example, if a program is running in 1998 and the sliding window is 20, then the result of
the add is 2018.
Subtract 99 from the ending year to get a 100-year range.
For example, 1919-2018
For two digit years in the range of 00 to last-two-digits-of-end, assign the century from the
ending date; for two digit years in the range of last-two-digts-of-start to 99, assign the century
from the starting date.

For example, the ranges are 00-18 and 19-99, so given a year of 82, assign a century
of 19; given a year of 17, assign a century of 20.

Intrinsic Function: DATE-TO-YYYYMMDD

Syntax

FUNCTION DATE-TO-YYYYMMDD (YYMMDD[SW])

Examples

COMPUTE FUNCTION DATE-TO-YYYYMMDD (IN-HIRE-DATE) TO OUT-HIRE-DATE


IF FUNCTION DATE-TO-YYYYMMDD (BIRTH-DATE-20) > QUERY-DATE THEN .

VALUE EXAMPLES:
RUN-TIME
YEAR
1998

INPUT VALUE

SW Argument

FUNCTION VALUE

890315

-10

18890315

1998

770122

-10

19770122

1998

890315

-1

19890315

1998

770122

-1

19770122

1998

890315

19890315

1998

770122

19770122

1998

890315

85

19890315

1998

770315

85

20770315

1998

890315

-120

1998

890315

120

Intrinsic Function: DATE-TO-YYYYDD

Syntax

FUNCTION DATE-TO-YYYYDD (YYDD[SW])

Examples

COMPUTE FUNCTION DATE-TO-YYYYDD (IST-LOGON-DAY) TO OUT-LOGON-DATE


IF FUNCTION DATE-TO-YYYYDD(ID-DATE-20) > QUERY-DATE THEN .

VALUE EXAMPLES:
RUN-TIME
YEAR
1998

INPUT VALUE

SW Argument

FUNCTION VALUE

89315

-10

1889315

1998

77122

-10

1977122

1998

89315

-1

1989315

1998

77122

-1

1977122

1998

89315

1989315

1998

77122

1977122

1998

89315

85

1989315

1998

77315

85

2077315

1998

89315

-120

1998

890315

120

Intrinsic Function: YEAR-TO-YYYY

Syntax

FUNCTION YEAR-TO-YYYY (YY[SW])

Examples:

MOVE FUNCTION YEAR-TO-YYYY(START-YEAR) TO OUT-START-YEAR


IF FUNCTION DATE-TO-YYYYMMDD(B-DATE-20) > QUERY-DATE THEN .

VALUE EXAMPLES:
RUN-TIME
INPUT VALUE
YEAR
1998
89

SW Argument

FUNCTION VALUE

-10

1889

1998

77

-10

1977

1998

89

-1

1989

1998

77

-1

1977

1998

89

1989

1998

77

1977

1998

89

85

1989

1998

77

85

2077

1998

89

-120

1998

89

120

COBOL Intrinsic Functions- Nesting functions

COMPUTE NEW-DUE-DATE =
FUNCTION DATE-OF-INTEGER
(FUNCTION INTEGER-OF-DATE(DATE-OF-ORDER) + 30)

IF DATE-OF-ORDER IS 19960317 then


FUNCTION INTEGER-OF-DATE(DATE-OF-ORDER) +30 is 14337+30 = 144367
FUCNTION DATE-OF-INTEGER(144367) gives NEW-DUE-DATE of 19960416

After Converting a Gregorian due to an integer date, and adding 30 days to the integer date, the
newly calculated Gregorian date is displayed

Length Intrinsic Functions


MOVE IN-REC(1:FUNCTION LENGTH(OUT-AREA)) TO OUT-AREA
* If the length of OUT-AREA is 10, only positions 1 to 10 of IN-REC are move to OUT-AREA
Returns a nine-digit integer specifying the number of bytes the argument takes in storage.
The LENGTH OF special register and LENGTH intrinsic function work similarly.
LENGTH intrinsic function is more robust because it can have a literal operand and it
works with null-terminated strings.
The syntax is different.
Notes:
The length intrinsic function takes a single argument (a non-numeric literal, a data element, a structure,
or an array) and returns a nine-digit integer specifying the numbe of bytes the argument takes in storage.
Move in-rec(1:function length (out-area) ) to out-area.

LOWER-CASE and UPPER-CASE Intrinsic Functions

MOVE FUNCTION UPPER-CASE(ANSWER) TO UPPER-ANSWER


*
IF ANSWER contains y then UPPER-ANSWER contains Y
Returns a string that is either all upper case or lower case.

Alphanumeric data items of same length all in required case returned


Very useful in comparing two strings
Notes:
These two intrinsic functions return a character string that contains all lower-case or all upper-case characters
Function lower-case(argument)
Function upper-case(argument)
The argument is an alphanumeric data item
The function reference is a string of the same length as the argument but with all letters forced to
lower-case or upper-case, respectively

REVERSE Intrinsic Functions

IF FUNCTIO REVERSE(ASTRING) = ASTRING


PERFORM FOUND-PALINDROME
* If ASTRING contained OTTO the paragraph FOUND-PALINDROME would be performed
Returns a string containing the characters of the argument in reverse order
Could be used to look for first non-blank character
In languages that are written from right to left

CHAR and ORD Intrinsic Functions

IF FUNCTION ORD(1) < FUNCTION ORD(A) PERFORM FOUND-ASCII


* If this IF is true then system is running using ASCII character set

CHAR(n) returns the character that is the n the character in coding sequence
ORD(char) returns the position that character belongs in the collating sequence
* Used where coding scheme, ASCII or EBCDIC are not know until compile time.

Arithmetic, Business, and Mathematical Intrinsic Functions

Trigonometric and Logarithmic Intrinsic Functions


Function name

Value returned

ACOS

Arc-cosine of numeric item

ASIN

Arc-sine of numeric item

ATAN

Arc-tangent of numeric item

COS

Cosins of numeric item

LOG

Natural logarithm of numeric item

LOG10

Logarithm to base 10 of numeric item

SIN

Sine of numeric item

TAN

Tangent of numeric item

Arithmetic, Business, and Mathematical Intrinsic Function 2


Statistical and other Mathematical Intrinsic Functions
Function name

Value returned

FACTORIAL

Factorial value of integer. Item

INTEGER

Greates integer not greater than numeric item

INTEGER-PART

Value of numeric item truncated at decimal point

MAX

Largest value in a list of values; all items in the list are of the
same type, one of: alphabetic, integer, numeric, or
alphanumeric

MEAN

Arithmetic mean of list of numeric items

MEDIAN

Median of list of numeric items

MIDRANGE

Mean of the minimum and maximu values in a list of


numeric items

MIN

Smallest value in a list of values; see MAX

Arithmetic, Business, and Mathematical Intrinsic Function 3


Statistical and other Mathematical Intrinsic Functions, 2
Function name

Value returned

MOD

Modulo value of integer item to integer base

ORD-MAX

Position of maximum item in a list

ORD-MIN

Position of miniumum item in a list

RANDOM

Random number based on supplied or default integer seed


number

RANGE

Value of maximum argument minus value of miniumum


argument; all arguments either integer or all numeric

REM

Remainder of dividing one numeric item by another


numeric item

SQRT

Square root of a numeric item

SUM

Sum of list of items, all items are numeric or all are


integer

Arithmetic, Business, and Mathematical Intrinsic Function, 4


Conversion Type Intrinsic Functions
Function name

Value returned

NUMVAL

Numeric value of numeric edited item

NUMVAL-C

Numeric value of numeric edited item with currency symbol

Investment / Depreciation Statistical Type Intrinsic Functions


Function name

Value returned

ANUITY

Ratio of annuity paid for integer periods at numeric interest,


on initial investment of 1

PRESENTVALUE

Present value using numeric discount rate for 1 or more


periods, the value in each period specified as a numeric item

STANDARDDEVIATION

Standard deviatio of list of numeric items

VARIANCE

Variance of list of numeric items

MIN and MAX Intrinsic Functions

COMPUTE MAX-HOLD = FUNCTION MAX(EMP1SALES, EMP2SALES,


EMP3SALES, EMP4SALES,EMP5SALES)
MAX-HOLD would contain the highest value of all elements in the list.
The MAX function returns the value of the largest item in a list of items, the MIN function returns
the value of the smallest item.
The argument in example are assumed to be numeric so compute had to be used

The ALL Subscript

COMPUTE TOTAL-IN = FUNCTION SUM(STORE-SALES(ALL)


TOTAL-IN will be equal to the summation of all elements of the STORE-SALES table array
When an intrinsic function may have a variable number of arguments, you may reference a table
as one or more of the arguments.

* If a multidimensional table, ALL may be used in place of one or more of the subscripts

Potrebbero piacerti anche