Académique Documents
Professionnel Documents
Culture Documents
By
SK.BILAL AHMED
+91 814376956
shaikbilalahme d@sify.com
Table of Contents
1. OBJ ECTIVE...............................................................................................................................................................5
2. INTRODUCTION......................................................................................................................................................6
HISTORY OF COBOL................................................................................................................................................6
ABOUT COBOL......................................................................................................................... .................................6
3. PROGRAM S TRUCTURE............................................................................................................................. ...........8
REFERENCE FORMAT: -..........................................................................................................................................8
SEQUENCE NUMBER A REA ........................................................................................................................ .........................8
INDICATOR A REA ..............................................................................................................................................................8
A REA A..........................................................................................................................................................................9
A REA B............................................................................................................................. ..............................................9
4. IDENTIFICATION DIVIS ION...............................................................................................................................10
PROGRAM -ID...........................................................................................................................................................10
5. ENVIRONMENT DIVIS ION..................................................................................................................................12
CONFIGURATION SECTION: -..............................................................................................................................12
INPUT-OUTPUT SECTION: -..................................................................................................................................13
I-O CONTROL...........................................................................................................................................................14
FILE-CONTROL............................................................................................................................................... .........14
RECORD FORMAT...................................................................................................................................................14
EFFICIENT FILE ORGA NIZATION AND MANA GEM ENT................................................................................16
SEQUENTIA L FILE .................................................................................................................................................16
INDEXED FILE ........................................................................................................................................................17
RELATIVE FILE ......................................................................................................................................................18
EX ERCIS ES..................................................................................................................................................................21
6. DATA DIVIS ION.....................................................................................................................................................22
LEVELS...................................................................................................................................... ................................22
CONDITION NAM ES (88-LEVEL)..........................................................................................................................23
DATA TYPES............................................................................................................................................................23
PICTURE CLAUSE............................................................................................................................... ....................24
PICTURE S TRING - RULES............................................................................................................................................24
FILE SECTION: -.......................................................................................................................................................25
WORKING-STORA GE SECTION: -........................................................................................................................26
REDEFINES...........................................................................................................................................................27
RESTRICTIONS ON REDEFINES............................................................................................................................. ........27
EXTERNAL...............................................................................................................................................................28
GLOBA L........................................................................................................................... .........................................29
JUSTIFIED............................................................................................................................. ................................29
SIGN.......................................................................................................................................................................30
SIGN CLAUSE EXAMPLES...............................................................................................................................................31
VA LUE CLAUSE: -...................................................................................................................................................31
EDITIN G: -.............................................................................................................................................................31
LINKA GE SECTION: -....................................................................................................................... ......................34
USA GE CLAUSE ........................................................................................................................... ...........................35
DISPLA Y: -................................................................................................................................................................37
INDEX: -.....................................................................................................................................................................37
POINTER: -................................................................................................................................................................38
SYNCHRONIZED.....................................................................................................................................................39
EX ERCIS ES..................................................................................................................................................................40
7. PROCEDUR E DIVIS ION.............................................................................................................. .........................41
SECTIONS AND PARA S: -......................................................................................................................................41
RULES FOR SECTION/PA RA NAMES: -.................................................................................................................. .......41
INPUT - OUTPUT VERBS........................................................................................................................................42
ACCEPT.....................................................................................................................................................................42
DISPLA Y....................................................................................................................................................................43
DISPLA Y - RULES.......................................................................................................................................................43
ARITHM ETIC OPERATIONS..................................................................................................................................44
ADD: -............................................................................................................................. ...........................................44
CORRESPONDING: -...............................................................................................................................................45
ADD CORRESP ONDING :-............................................................................................................................ .....................46
ON SIZE ERROR OCCURS..........................................................................................................................................47
ROUNDED PHRASE .....................................................................................................................................................47
SUBTRA CT............................................................................................................................ ....................................48
MULTIPLY ...............................................................................................................................................................50
DIVIDE.......................................................................................................................................................................51
COMPUTE.................................................................................................................................................................52
EX ERCIS ES..................................................................................................................................................................53
8. CONTROL FLOW VERBS.....................................................................................................................................55
CONDITIONA L EXPRESSIONS.............................................................................................................................55
RELATION OPERATORS........................................................................................................................................55
CLASS CONDITION.................................................................................................................................................56
SIGN CONDITION....................................................................................................................................................56
COMPLEX CONDITIONS........................................................................................................................................57
LOGICAL OPERATORS...........................................................................................................................................57
GO TO............................................................................................................................. ...........................................58
ALTER........................................................................................................................................................................60
CONTINUE................................................................................................................................................................62
EVA LUATE...............................................................................................................................................................63
PERFORM .................................................................................................................................................................65
PERFORM (Basic).................................................................................................................................................66
PERFORM (TIMES option)...................................................................................................................................67
PERFORM (UNTIL option)...................................................................................................................................67
PERFORM (VARYIN G)............................................................................................................................. .............69
EXIT..................................................................................................................................................... ......................73
EX ERCIS ES..................................................................................................................................................................74
9. NON-NUMERIC DATA MANIPULATION.........................................................................................................75
MOVE.........................................................................................................................................................................75
INITIA LIZE................................................................................................................................................................79
INSPECT....................................................................................................................................................................81
STRING......................................................................................................................................................................84
UNSTRING........................................................................................................... .....................................................85
SET.............................................................................................................................................................................86
SET - CONDITION NAME .............................................................................................................................. ...................86
10. SUB-PROGRAM....................................................................................................................................................89
CA LL..........................................................................................................................................................................89
CANCEL....................................................................................................................................................................91
ENTRY.................................................................................................. .....................................................................92
EXIT PROGRAM.......................................................................................................................................................92
STOP......................................................................................................................................... ..................................92
GOBA CK....................................................................................................................................................................93
END PROGRAM.......................................................................................................................................................93
11. FILE OPERATIONS..............................................................................................................................................94
OPEN .........................................................................................................................................................................94
CLOSE........................................................................................................................................................................94
READ..........................................................................................................................................................................95
START........................................................................................................................................................................99
WRITE........................................................................................................................... ...........................................101
REW RITE........................................................................................................................... ......................................104
DELETE...................................................................................................................................................................105
SORT ............................................................................................................................. ..........................................106
INPUT PROCEDURE:-.................................................................................................................. .........................107
OUTPUT PROCEDURE:-.......................................................................................................................................108
RELEASE............................................................................................................................. ....................................110
RETURN ............................................................................................................................. ....................................110
MERGE....................................................................................................................................................................111
INPUT/ OUTPUT ERROR HANDLING TECHNIQUES.......................................................................................113
THE END-OF-FILE PHRASE (AT EN D)............................................................................................................113
EXCEPTION/ERROR Declarative............................................................................................................. ..........114
FILE S TATUS key............................................................................................................................. ....................114
INVALID KEY phrase...........................................................................................................................................114
EX ERCIS ES................................................................................................................................................................115
12. TABLE HANDLING............................................................................................................................................116
OCCURS..................................................................................................................................................................117
FIXED LENGTH TABLES............................................................................................................................. .........117
VA RIABLE LENGTH TABLES.............................................................................................................................118
SET...........................................................................................................................................................................120
COMPLEX TA BLES...............................................................................................................................................121
TABLE PROCESSING ...........................................................................................................................................122
SEARCH............................................................................................................................. ......................................125
MERGE............................................................................................................................. .......................................130
EX ERCIS ES................................................................................................................................................................131
14. COMPILER OPTIONS.............................................................................................................. .........................134
APPENDIX 1...............................................................................................................................................................146
FILE STATUS CODES A ND M EANING..............................................................................................................146
REFERENCES............................................................................................................................................................148
Cobol
Object ive
1. Objective
NRI-IT
Page 5 of 148
Cobol
Introduction
2. Introduction
HISTORY OF COBOL
Conceived in 1959
COBOL II / COBOL 85
ABOUT COBOL
There was a growing need in the early days to have a high level language whic h will be best suited for
Business Applications. Hence In 1959, a new language COBOL COmmon Business Oriented
Language emerged.
Cobol is a High Level Structured Language. This is English like language, which is used to develop major
business applications. why most of business applications are developed using Mainframe COBOL ?
2.
3.
4.
The IDE NTIFICA TION DIVIS ION and ENV IRONME NT DIV ISION are the first 2 divisions that need to be
defined in the COBOL program. As their names indicate, these divisions contain ent ries that gives the
name of the program, author of the program, Source computer in which the program is written and the
object comput er in which the program may be run.
Let us consider a statement ADD PRINCIPAL, INTE RES T TO AMOUNT.
The meaning of this statement is quite apparent. The principal and interest are added to get amount. The
words PRINCIPAL, INTERES T, AMOUNT are called Data names. It is essential that all the data names
which are used in PROCE DURE DIV ISION needs to be defined at the outset.
Cognizant Academy
Page 6 of 148
Cobol
Introduction
Hence all the data definitions takes place in DA TA DIV ISION. Hence DA TA DIVIS ION appears before the
PROCEDURE DIV IS ION and it is the third division in the COBOL program. The data definition includes the
size of the data item, the type and any initial value which needs to be set are defined in DA TA DIVIS ION
entries.
The data that belongs to the input or output record is defined in FILE SECTION and the data names that
holds the intermediate results are defined in the WORK ING S TORAGE SECTION.
Now that we have defined all the nec essary data names and files to be used by the COBOL program, next
comes the algorithm. The last division in the COB OL program is the PROCE DURE DIV ISION where the
actual algorithm of the program is written. The P ROCEDURE DIV IS ION contains statements, which
specify operations to be performed by the computer.
Thus these 4 divisions form the core structure of COB OL program. These divisions will be explained in
detail in the following Chapters.
Cognizant Academy
Page 7 of 148
Cobol
Program Structure
3. PROGRAM STRUCTURE
Lets try to develop an application using COBOL program. For e.g. Consider Employee Management System in an
Organization. An Application contains series of programs, Data files, interfaces and Reports.
REFERENCE FORMAT: COBOL programs must be written in the COBOL referenc e format. Figure 4
shows the reference format for a COBOL source line.
11
12
72
73
80
Indicator Area
Column 7: Any sentence, entry, c lause, or phras e that requires more than one line can be continued
in Area B of the next line which is not a
comment line
blank line
Area A of a continuation line must be blank
If no hyphen (-) in indicator Area
last character of the preceding line is assumed to be followed by a space
If hyphen in Indicator Area
first non-blank character of this continuation line immediately follows the last nonblank char of continues line
If the continued line contains a non-numeric literal without a closing quotation mark:
all spaces at the end of the continued line (through column 72) are part of the
literal
Continuation line must contain a hyphen in the indicat or area
First non-blank character must be a quotation mark and Literal
continues with the character following the quotation mark
Cognizant Academy
Ver 1.0
Page 8 of 148
Cobol
Program Structure
Area A
Columns 8 through 11
The following items must begin in Area A:
Division header
Section header
Paragraph header or paragraph name
Level indic ator or level-number (01 and 77)
DECLARA TIVES and END DE CLA RA TIVES.
End program header.
Area B
Columns 12 through 72
Entries, sentences, statements, clauses
Continuation lines.
Cognizant Academy
Ver 1.0
Page 9 of 148
Cobol
4. IDENTIFICATION DIVISION
IDE NTIFICA TION DIV ISION is the first division in the COB OL program. There may be several paragraphs
in this division of which PROGRAM-ID is essential paragraph.
Each program has a Program id Name of the program. Author Person who is writing the program and
other information like dat e written, date compiled. Since the information identify a particular program,
these are defined in IDENTIFICATION DIVISION which is the First line of the COBOL program. Except
PROGRAM-ID all the other paragraphs are optional and are mainly for documentation purposes.
The syntax for
NRI-IT
Page 10 of 148
Cobol
IDENTIFICATION DIVISION.
PROGRAM-ID. EMPMAINT1.
AUTHOR. CTS.
DATE-WRITTEN. 01/01/01.
DATE-COMPILED.
******************************************************************
***********
BRIEF PROGRAM DESCRIPTION
************
* PROGRAM OBJECTIVE: This Program Maintains the Emp loyee file by updating the master file.
NRI-IT
Page 11 of 148
Cobol
5. ENVIRONMENT DIVISION
The identification division gives introduction about the program. Now we need to define the Machine
dependent details for our program. These details are given in
ENVIRONME NT DIVIS ION. The E NVIRONME NT DIVIS ION must follow the IDENTIFICA TION DIV IS ION
in the COB OL program. Among all the divisions this one is the most machine dependent division. The
computer and all the peripheral devices required by the program are described in this division.
The Environment Division consists of 2 sections
The Configuration Section
The Input-Output Section
NRI-IT
Page 12 of 148
Cobol
NRI-IT
Page 13 of 148
Cobol
I-O CONTROL.
I-O CONTROL is not used these days. This feature is invalid in COBOL 370.
Each data file used by the program should be defined in the FILE -CONTROL paragraph. This paragraph
also gives the medium through which the file can be accessed. By medium, in Mainframe environment, we
mean the DDNAMES in run JCL.
In this paragraph, we also describe what type of file it is, what organization is it, which access mode is
used to access the files etc.
The syntax is as follows
FILE-CONTROL.
SELECT
SELECT [OPTIONAL] filnam1 ASSIGN TO assignmtname1
[ORGANIZATION IS
{SEQUENTIAL,
INDEXED,
RELATIVE) ]
[ACCESS MODE IS { SEQUENTIAL
RANDOM
DYNAMIC } ]
[FILE STATUS IS dataname-1
[dataname-2] ].
SELECT; - This statement gives the relationship between the filename used in the program and
the data file used in the JCL.
Filname1: - This is the name used by COBOL to refer inside the program.
Assignmtname1: - DDNAME given in JCL.
OPTIONAL: This key word is used only for input files. When the key word OP TIONAL is used in the select clause, this
file need not be present during the execution. If this keyword is omitted, the file must be present.
RECORD FORMAT
Fixed
- Specify RE CORDING MODE F
- Max length of 01 level entry is less than BLOCK contains clause size AND either
Record contains clause has single size (Not a range)
All 01 level entry is same and no depending on option
NRI-IT
Page 14 of 148
Cobol
Unblocked
B L O C K E D
Variable
- Specify RE CORDING MODE V
- Max length of 01 level entry is less than BLOCK contains clause size AND either
Record contains clause has range
01 level entry is different or has depending on option
BDW
RDW
Data Record
BDF
SDF
BDF
SDF
Rec segment
SDF
Undefined Records
- Unspecified characteristics
- Compiler does not derive
- Specify RE CORDING MODE U
- Each block on external storage is treated as a logical record;
- Max record length is
As specified in Record Contains or varying clause
If omitted max 01 level entry size
- BLOCK contains clause is treated as comment
NRI-IT
Page 15 of 148
Cobol
A SAM or VSAM sequential file is the simplest file type. Either works for an application that uses only
sequential access of fixed-length or variable-lengt h records and no ins ertion of records between
existing ones.
A VSAM indexed file is the most flexible data set. It may be used for applications requiring both
sequential and random access in the same program. A indexed file can make use of fixed-lengt h or
variable-length records.
A VSAM relative file works well for an application that performs random insert and deletes operations.
A VSAM relative file can make use of fixed-length or variable-length records.
SEQUENTIAL FILE
The sequential files are used for Reports, transaction files, intermediate files for processing, Sort
files etc.
Records can be accessed in the order in which they appear in the file
Records can be updated
Records can be appended but not inserted
Records cannot be deleted
NRI-IT
Page 16 of 148
Cobol
NRI-IT
Page 17 of 148
Cobol
RELATIVE FILE
Also called Direct Access Files
Each record has a unique address and is identified by its Relative Record Number in the file
Records can be Accessed Randomly using their Relative Record Numbers
NRI-IT
Page 18 of 148
Cobol
ACCESS
ORG.
SEQ
RELATIVE
INDEXED
SEQ
RANDOM
DYNAMIC
INVALID
SEQ. OR
RANDOM
SEQ. OR
RANDOM
NRI-IT
Page 19 of 148
Cobol
NRI-IT
Page 20 of 148
Cobol
Exercises
EXERCISES
NRI-IT
Page 21 of 148
Cobol
DATA DIVISION
6. DATA DIVISION
Until now, we have defined the environment in which our application program will be executed, the data
files used by the program. Our application program needs to know the layout of the files used for it to
process the data. We define the file layout in the DA TA DIV ISION.
The DA TA DIV IS ION has the following sections.
FILE SECTION
WORKING-S TORAGE SECTION
LINKAGE SECTION
LEVELS
Mimic the hierarchy in the Logical Record
The lowest subdivision is an Elementary Item
Elementary items can be combined into group items
Elementary Items may form part of one or more Groups
Level Numbers 01 to 49, 77, 88
The level Number of the Element ary Items is greater than that of the group Item.
The 01 level number is root in the hierarchy of the logic al record
The size of the Group item is equal to the sum of the sizes of the element ary or sub-group items.
E.G.
01
ASSOC-REC.
05
ASSOC-NO
05
ASSOC-NAME.
10
FIRST-NAME
10
LAST-NAME
05
ASSOC-ADDRESS.
10
ADDR-LINE-1
10
ADDR-LINE-2
10
ADDR-LINE-3
10
TELEPHONE-NO
NRI-IT
Page 22 of 148
Cobol
DATA DIVISION
77 Level
Elementary Data Item not belonging to any group
Must begin in Area A
E.G
01 ASSOC-REC.
77 W04-TEMP-I
PIC X(01).
NRI-IT
Page 23 of 148
Cobol
DATA DIVISION
PICTURE CLAUSE
{ PICTURE IS pic-string1 PIC }
Specified for every Elementary Item
pic-string1 can contain a maximum of 30 Code Characters
Code Character repetitions can be indicated by an integer within ( )
Code
Char
9
X
A
V
P
S
B
0
/
,
.
*
$
+
CR
DB
Meaning
Numeric Data Item
Any allowable character from the character set
a Letter or Space
Assumed Decimal Point
Position of Assumed Decimal Point when it lies
outside
Data Item is Signed
Inserts space
Inserts zero
Inserts Slash
Inserts Comma
Inserts Decimal Point
Replaces leading zeros
Inserts Currency sign
Inserts Sign
Sample
Picture
9999
XXXX
AAAA
99V99
99PPV
PPP99
S9(4)
XXBXXX
9(5)000
XX/XX/XX
9,999
9,999.99
****9.99
$9,999.99
+99.99
-99.99
99.99DB
99.99CR
NRI-IT
Page 24 of 148
Cobol
DATA DIVISION
9999
0 through 9999
S99
S999V 9
Numeric-edited items
- B P V Z 9 0 / , . + - CR DB * $
- At-least one edit char or BLA NK WHEN ZERO clause
Alphanumeric items
- The symbol X or
- Combinations of the symbols A, X, and 9.
Alphanumeric-edited items
-A X 9 B 0 /
- Must contain at least one A or X, and at least one B or 0 or /.
FILE SECTION: The layouts of the files are described in this section. The files, which are defined in the SELECT clause,
should have an FD entry in the FILE SECTION. The record layout for the files is defined in the FD section
which is FILE DESCRITP TION entry for the files defined in the SELECT clause.
The File description entry is followed by the record description entry,
A Record Description entry is a 01 level group item along with its sub divisions.
If there are more than one 01 level, this means that the file defined is a Variable file which has different
record layouts.
NRI-IT
Page 25 of 148
Cobol
DATA DIVISION
FD file-name-1
[ BLOCK CONTAINS [ int1 TO ]
int2 { CHARACTERS
RECORDS } ]
[ RECORDING MODE IS { F V S U } ]
[ RECORD { CONTAINS int3 [TO int4] CHARACTERS } ]
[ DATA { RECORD IS
RECORDS ARE }
( data-name-2 ) ... ]
BLOCK CONTAINS: The BLOCK CONTA INS CHARA CTERS clause specifies the size of the physical records.
The int1 and int2 specifies the minimum and maximum character sizes of the physical record.
The BLOCK CONTA INS RECORDS clause specifies the number of logical records present in each
physical record (the actual data records in the main memory).
RECORD CONTA INS: The RE CORD contains clause gives the physical record. This has to match with record length in the DD
statement parameter.
E.G. FD INT91.
RECORDING MODE IS F
BLOCK CONTAINS 2 RECORDS.
01 NT91-HDR
PIC X(80).
WORKING-STORAGE SECTION: This section is used to define the temporary variables in the COB OL program. It is used like a scratch
pad inside the program.
The data in the working storage may be group item or elementary item.
Level 77 is used to define elementary data item in the working storage section.
Level 88 is used for Conditional variables.
Succeeds File Section
Used for Intermediate Storage
Common Practice to Group related items together
NRI-IT
Page 26 of 148
Cobol
DATA DIVISION
Example
01 I-ADDRESS.
05 I-ADD-LINE-1 PIC X(30).
05 I-ADD-LINE-2 PIC X(30).
05 I-ADD-LINE-3 PIC X(30).
Syntax for Data Description Entry
level
{data- name-1
FILLER}
[REDEF clause]
[BLANK-WHEN-ZERO clause] [EXTERNAL
clause] [GLOBAL clause] [OCCURS clause]
[JUST clause] [PIC clause] [SIGN clause] [USAGE
clause] [VALUE clause] .
REDEFINES
level {data- name-1
FILLER}
REDEFINES data-name-2
Allows the same area of memory to be referenced by more than one data-name with different
format and sizes
Multiple 01 levels of same FD are Implicitly Redefined
Restrictions on REDEFINES
OCCURS and RE DEFINES cannot be combined
Qualification of data-name-2 not required
Value Claus es only in Condition Names
Redefinition Ceases Whenever a Level No is <= that of data-name-1 or data-name-2 is encountered
The Size of Data-name-1 must be Less than or equal to Dat a-name-2
Data item lengths and types can also be respecified within an area.
NRI-IT
Page 27 of 148
Cobol
DATA DIVISION
REDEFINES Examples
05 NAME-2.
10 SALARY
PICTURE XXX.
10 SO-SEC-NO
PICTURE X(9).
10 MONTH
PICTURE XX.
05 NAME-1 REDEFINES NAME-2.
10 WAGE
PICTURE 999V999.
10 EMP-NO
PICTURE X(6).
10 YEAR
PICTURE XX.
When an area is redefined, all descriptions of the area are always in effect.
That is, redefinition does not cause any data to be erased and never supersedes a previous
description.
Thus, if B REDEFINES C has been specified, either of the two procedural statements, MOVE X TO B
and MOVE Y TO C, could be ex ecuted at any point in the program.
The BLA NK WHEN ZERO clause specifies that an item cont ains
nothing but spaces when its value is zero.
The BLA NK WHEN ZERO clause can be specified only for
elementary numeric or numeric -edited items. These items must be described, either implicitly or
explicitly, as USAGE IS DISPLAY
Useful for printing
Not allowed on 66 and 88 levels & on POINTE R and INDE X dat a
items
EXTERNAL
This clause indicates that the data item is external to the program and is common to the entire run unit
NRI-IT
Page 28 of 148
Cobol
DATA DIVISION
GLOBAL
This clause indicates that the data item is available to all the nested programs unless it is defined in
the contained program
Valid only for 01 Level
Valid only in Working Storage and File Section, not valid in Linkage Section
All data-names subordinate to or condition-names or indexes associated with a global name are global
names.
The search begins within the program that contains the reference and continues "outward" to
containing programs until a match for the GLOBA L name is found.
JUSTIFIED
{ JUSTIFIED
JUST}
RIGHT
The JUS TIFIED claus e overrides standard positioning rules for a receiving item of the alphabetic or
alphanumeric categories
Cant be specified for other categories
Does not affect initial values, as determined by the VALUE clause
Does not affect the setting of conditional variable when the associated condition name is set
Items described as USA GE IS POINTE R
NRI-IT
Page 29 of 148
Cobol
DATA DIVISION
JUSTIFIED - Examples
05 align- rt pic x(5)
88 c-rt
JUST RIGHT.
value RT.
1. MOVE RT TO align-rt
2. SET c-rt
TO TRUE
Value of align-rt
Before stmt-1
RTbbb
After stmt-1
bbbRT
After stmt-2
RTbbb
PICTURE
[ PICTURE IS string
PIC ]
Specifies the characteristics and editing requirements
Must be specified for every elementary item except an index data item or the subject of the
RENAMES clause. In these cases, use of this clause is prohibited.
The PICTURE claus e can be specified only at the element ary level
The PICTURE character-string can contain a maximum of 30 characters
SIGN
[SIGN IS
{LEADING
TRAILING} ]
[ SEPARATE CHARACTER ]
Specifies the position and mode of represent ation of the operational sign for a numeric entry.
The Sign Clause can be specified for a signed numeric data description entry (that is, one whose
NRI-IT
Page 30 of 148
Cobol
DATA DIVISION
VALUE CLAUSE: The VALUE clause is used to set an initial value to the working storage variable.
This can be specified only in the working storage variable.
The VALUE Clause can not be a part of RECORD DES CRIP TION entry in the FILE SECTION.
NRI-IT
Page 31 of 148
Cobol
DATA DIVISION
PICTURE
X(2)BX(3)BX(4)
9(2)/9(2)/9(2)
99,B999,B000
99,999
NRI-IT
Value of Data
19Mar1995
190395
1234
12345
Edited Result
19 Mar 1995
19/03/95
01, 234, 000
12,345
Page 32 of 148
Cobol
DATA DIVISION
Value of Data
1.234
12.34
123.45
1234.5
Edited Result
001.23
012.34
123.45
234.50
Value of Data
+6555.556
-6555.555
+1234.56
-123.45
-123.456
+123.456
+123.45
-123.45
+123.45
-123.45
Edited Result
555.55+
-6555.55
1234.56
-$123.45
-$123.45
$123.45
$0123.45
$0123.45DB
$0123.45
$0123.45CR
Floating Insertion
- $ + - Mutually exclusive
PICTURE
$$$$.99
$$$9.99
$,$$$,999.99
+,+++,999.99
$$,$$$,$$$.99CR
++,+++,+++.+++
NRI-IT
Value of Data
.123
.12
-1234.56
-123456.789
-1234567
0000.00
Edited Result
bbb$.12
bb$0.12
bbbb$1,234.56
b-123,456.78
$1,234,567.00CR
Bbbbbbb
Page 33 of 148
Cobol
DATA DIVISION
Value of Data
0000.00
0000.00
0000.00
0000.02
0000.00
0000.00
+123.456
-123.45
+12345678.9
+1234.56
-12345.67
Edited Result
****.**
Bbbbbbb
Bbbbbbb
$.02
bbbb.00
bb00.00
bb123.45+
**123.4512,345,678.90+
$b1,234.56bb
$b
***12,345.67bbDB
LINKAGE SECTION: The LINKAGE SECTION is used to define any data passed across programs.
i.e. the layout of the data passed is defined in the linkage section.
NRI-IT
Page 34 of 148
Cobol
DATA DIVISION
USAGE CLAUSE
The data can be stored in more than one internal form in the computer. In COB OL, a programmer is
allowed to specify the internal form of the data item so as to facilitate the us e of the data item more
efficiently. The USA GE clause specifies the format of a data item in comput er storage. These are forms of
internal representation
Computational
Display
Pointer
Packed decimal
The syntax of the USAGE clause is
USAGE IS {BINARY
COMP COMP UTA TIONAL
COMP-1 COMPUTA TIONA L-1
COMP-2 COMPUTATIONAL-2
COMP-3 COMPUTA TIONA L-3
COMP-4 COMPUTA TIONA L-4
DISPLAY
INDE X
PACKED-DE CIMA L
POINTER}
NRI-IT
Page 35 of 148
Cobol
DATA DIVISION
BINARY :Specified for binary data items. Such items have a decimal equivalent consisting of the decimal digits 0
through 9, plus a sign. Negative numbers are represented as the two's complement of the positive number
with the same absolute value.
The amount of storage occupied by a binary item depends on the number of decimal digits defined in its
PICTURE clause:
Storage Occupied
2 bytes (halfword)
4 bytes (fullword)
8 bytes
(doubleword)
COMPUTATIONAL or COMP:This is the equivalent of B INA RY. The COMPUTA TIONA L phrase is synonymous with BINARY.
COMPUTATIONAL-1 or COMP-1 (Floating-Point): Specified for internal floating-point items (single precision). COMP-1 items are 4 bytes long. The number is
actually represented in Hexadecimal form. Such representation is suitable for Arithmetic operations. The
PIC claus e cannot be specified for this item
PIC
S9(7) COMP-3
NRI-IT
Page 36 of 148
Cobol
DATA DIVISION
DISPLAY: The data item is stored in character form, 1 character for each 8-bit byte. This corresponds to the format
used for printed output.
DISP LAY can be explicit or implicit.
INDEX: A data item defined with the INDE X phrase is an index data item.
An index data item is a 4-byte elementary item (not necessarily connected with any table) that can be
used to save index-name values for fut ure reference. Through a SE T statement, an index data item can
be assigned an index-name value; such a value corresponds to the occurrence number in a table.
Direct references to an index data item can be made only in a SEARCH statement, a SE T statement, a
relation condition, the US ING phrase of the Procedure Division header, or the US ING phrase of the CALL
statement.
An index data item can be part of a group item referred to in a MOVE statement or an input/output
statement.
An index data item saves values that represent table occurrences, yet is not necessarily defined as part of
any table. Thus, when it is referred to directly in a SEARCH or SET statement, or indirectly in a MOVE or
input/output statement, there is no conversion of values when the statement is executed.
The USAGE IS INDE X clause can be written at any level. If a group item is described with the USAGE IS
INDE X clause, the elementary items within the group are index dat a items; the group itself is not an index
data item, and the group name cannot be used in SEARCH and SE T statements or in relation conditions.
The USAGE clause of an elementary item cannot contradict the USAGE clause of a group to which the
item belongs.
An index data item cannot be a conditional variable.
The DA TE FORMA T, JUS TIFIED, PICTURE, BLA NK WHEN ZERO, SYNCHRONIZE D, or VALUE
clauses cannot be used to describe group or elementary items described with the USAGE IS INDE X
clause.
NRI-IT
Page 37 of 148
Cobol
DATA DIVISION
SYNCHRONIZE D can be used with USAGE IS INDE X to obtain efficient use of the index data item.
POINTER: A data item defined with USAGE IS POINTE R is a pointer data item. A pointer data item is a 4-byte
elementary item.
You can use pointer data items to accomplish limited base addressing. Pointer dat a items can be
compared for equality or moved to other pointer items.
A pointer data item can only be used:
In a relation condition
In the USING phrase of a CALL statement, an E NTRY statement, or the Proc edure Division header.
The USA GE IS POINTER clause can be written at any level except level 88. If a group item is described with the
USA GE IS POINTER clause, the elementary items within the group are pointer data items; the group itself is not a
pointer data item and cannot be used in the syntax where a pointer data item is allowed. The USA GE clause of an
elementary item cannot contradict the USA GE clause of a group to which the item belongs.
Pointer data items can be part of a group that is referred to in a MOVE statement or an input/output statement.
However, if a pointer data item is part of a group, there is no conversion of values when the statement is executed.
A pointer data item can be the subject or object of a REDEFINES clause.
SYNCHRONIZED can be used with USA GE IS POINTER to obtain efficient use of the pointer data item.
A VA LUE clause for a pointer data item can contain only NULL or NULLS.
A pointer data item cannot be a conditional variable.
A pointer data item does not belong to any class or category.
The DATE FORMAT, JUSTIFIED, PICTURE, and BLA NK WHEN ZERO clauses cannot be used to describe
group or elementary items defined with the USA GE IS POINTER clause.
Pointer data items are ignored in CORRESPONDING operations.
A pointer data item can be written to a data set, but, upon subsequent reading of the record containing the pointer, the
address contained can no longer represent a valid pointer.
USA GE IS POINTER is implicitly specified for the ADDRESS OF special register.
NRI-IT
Page 38 of 148
Cobol
DATA DIVISION
SYNCHRONIZED
[ {SYNCHRONIZED { LEFT
SYNC }
RIGHT } ]
Specifies the alignment of an elementary item on a natural boundary in storage.
It is never required, but may improve performance on some systems for binary items used in
arithmetic.
NRI-IT
Page 39 of 148
Cobol
EXERCISES
EXERCISES
1. Write File Section entries for the following file
a. The employee Master file
Employee number char 10 (employee number consists of first 2 chars as their initials,
next 4 bytes the month and year of joining, the next 4 bytes a running sequence
number), Employee name char 30, Designation char 2, Department char 3, Date of
Birth char 10, Date of joining char 10
b. The employee transaction file
Employee number char 10, Employee name char 30, Designation char 2, Department
char 3, Date of Birth char 10, Date of joining char 10, run date char 10
c. The Error file
The Record number numeric 8, employee number char 10, error description char 40
d. The Card file
The employee number char 10, run date char 10
2. Write Working storage entries for the following layouts
The working storage variables to check the file status of each file, the presence of the
employee record in the master file
NRI-IT
Page 40 of 148
Cobol
Procedure Division
7. PROCEDURE DIVISION
Now we have defined the data variables used in the program, files used in the program. We need to
process the data available for us to produce the results.
The syntax of procedure division is
Rules for SECTION/PARA Names: Must not have more than 30 characters
Can contain (0-9) DIGITs, (A-Z) LE TTE Rs & Hyphens (-) only
Hyphen should be embedded
SENTENCE & STA TEME NT: SENTENCE is composed of one or more S TA TEMENTs.
STA TEME NT is a syntactically valid combination of words and symbols beginning with a verb
STA TEME NT can be
- Conditional
- Imperative
- Compiler Directing
NRI-IT
Page 41 of 148
Cobol
Procedure Division
ACCEPT
ACCEPT identifier1 [ FROM
{ mnemonic- name
environment-name
DATE
DAY
DAY-OF-WEEK
TIME } ]
- YYMMDD
DAY-OF-WEEK
- 9(6)
- 9(1)
- 1 TO 7 (Monday to Sunday )
DAY
- YYDDD (Julian)
- 9(5)
TIME
- HHMMSShs
- 9(8)
ACCEPT - Example
COBOL statement
ACCEP T in-parm
ACCEP T in-parm FROM card
NRI-IT
Page 42 of 148
Cobol
Procedure Division
JCL statement:
//SYSIN DD applicable parameters
LRE CL of DCB parameter can be up to a max of 256.
RECFM can be Fixed or Variable
Records are read until identifier is filled or EOF reached
DISPLAY
DISPLAY { identifier1
literal1 } ...
[ UPON { mnemonic- name1
environment-name1}]
[ WITH NO ADVANCING ]
When the UP ON is omitted, SYSOUT is the default device
Mnemonic-name is as specified in SPECIAL-NAMES
Environment-name can be SYSOUT, SYSLIS T, SYSLS T, SYSPCH, SYSPUNCH, CONS OLE
DISPLAY - Example
COBOL statement
DISP LAY Return code: i-ret-code
DISP LAY Return code: i-ret-code
UPON SYSLIS T
JCL statement
//SYOUT DD applicable parameters
//SYLIST DD applicable parameters
Default LRE CL for SYSOUT is 121 and RECFM is FBA
Records will be folded if length > LRECL - 1.
DISPLAY - Rules
Identifier-1 is converted automatically to external format, if required
Negative signed values cause a low-order sign overpunch
POINTERs are converted to an external PIC 9(10)
INDE X names cant be specified
NRI-IT
Page 43 of 148
Cobol
Procedure Division
ARITHMETIC OPERATIONS
BINA RY : + - * / **
UNA RY : + Precedence
- Unary
- Exponentiation
- Multiplication and Division
- Addition and Subtraction
Format 1
ADD { id-1
lit-1 } ...
TO ( id- m [ ROUNDED ] ) ...
[ ON SIZE ERROR imper-stmt1 ]
[ NOT ON SIZE ERROR
imper-stmt2 ]
[ END-ADD ]
Format 2
ADD { id-1 TO { id-3
lit-1 } ...
lit-3 }
GIVING ( id- m [ ROUNDED ] ) ...
[ ON SIZE ERROR imper-stmt1 ]
[ NOT ON SIZE ERROR
imper-stmt2 ]
[ END-ADD ]
NRI-IT
Page 44 of 148
Cobol
Procedure Division
Format 3
ADD { CORRESPONDING
CORR }
id-1 TO id-2 [ ROUNDED ]
[ ON SIZE ERROR imper-stmt1 ]
[ NOT ON SIZE ERROR
imper-stmt2 ]
[ END-ADD ]
CORRESPONDING: Quite often it is required to move some of the data item of one group to some other data item of other
group. If the names of the corresponding data items are distinct then separate MOVE statements have to
be used. But if the corresponding data items have identical names, then instead of separate MOVE
statements, MOVE CORRESPONDING can be used.
E.g.
1
NRI-IT
PAY-REC.
02
ID-NUMBER
02
NAME
02
DEPARTMENT
02
BASIC-PAY
02
FILLER
PRINT-REC.
02
FILLER
02
ID-NUMBER
02
FILLER
02
NAME
02
FILLER
02
DEPARTMENT
02
FILLER
02
BASIC-PAY
02
FILLER
02
DEDUCTIONS
02
FILLER
02
ALLOWANCES
02
FILLER
02
NET-PAY
PIC
PIC
PIC
PIC
PIC
9(5).
X(25).
X(20).
9999V99.
X(24).
PIC
PIC
PIC
PIC
PIC
PIC
PIC
PIC
PIC
X(5).
Z(5).
X(5).
X(25).
X(5).
X(20).
X(5).
ZZZZ.99
X(5).
PIC ZZZZ.99.
X(5).
PIC ZZZZ.99
X(5).
ZZZZ.99
PIC
PIC
PIC
Page 45 of 148
Cobol
Procedure Division
NRI-IT
Page 46 of 148
Cobol
Procedure Division
ROUNDED Phrase
After decimal point alignment, the number of places in the fraction of the result of an arit hmetic
operation is compared with the number of places provided for the fraction of the resultant identifier.
NRI-IT
Page 47 of 148
Cobol
Procedure Division
When the size of the fractional result exceeds the number of places provided for its storage, truncation
occurs unless ROUNDE D is specified. When ROUNDED is specified, the least significant digit of the
resultant identifier is increased by 1 whenever the most significant digit of the excess is greater than or
equal to 5.
ADD Examples
ADD A TO B
ADD 1 TO B
ADD A TO B ROUNDE D
ADD A TO B, C
ADD A TO B ROUNDE D
C ROUNDE D
ADD A TO B ROUNDE D , C
ON SIZE E RROR
MOVE 1 TO ERR-FLAG
ADD A, B, C, D TO X, Y, Z
ADD A , B, C, D TO E GIV ING X, Y
NRI-IT
Page 48 of 148
Cobol
Procedure Division
SUBTRACT { id-1
lit-1 } ...
FROM ( id- m [ ROUNDED ] ) ...
[ ON SIZE ERROR imper-stmt1 ]
[ NOT ON SIZE ERROR
imper-stmt2 ]
[ END-SUBTRACT ]
SUBTRACT { id-1
lit-1 } ...
FROM
{ id-2
lit-2 }
GIVING
( id- m [ ROUNDED ] ) ...
[ ON SIZE ERROR imper-stmt1 ]
[ NOT ON SIZE ERROR imper-stmt2 ]
[ END-SUBTRACT ]
SUBTRACT { CORRESPONDING
CORR }
id-1 FROM id-2 [ ROUNDED ]
[ ON SIZE ERROR imper-stmt1 ]
[ NOT ON SIZE ERROR
[ END-SUBTRACT ]
imper-stmt2
SUBTRACT Examples
SUB TRA CT 1 FROM A
SUB TRA CT A FROM B
SUB TRA CT A B FROM C D
SUB TRA CT A B FROM C GIV ING D
SUB TRA CT A FROM B
GIV ING CROUNDE D
SUB TRA CT A FROM B
ON SIZE E RROR
MOVE 1 TO ERROR-FLAG
NRI-IT
Page 49 of 148
Cobol
Procedure Division
MULTIPLY
MULTIPLY { id-1
lit-1 }
BY ( id-2 [ ROUNDED ] ) ...
[ ON SIZE ERROR imper-stmt1 ]
[ NOT ON SIZE ERROR
imperative-stmt2 ]
[ END-MULTIPLY ]
MULTIPLY { id-1
BY id-2
lit-1 }
GIVING id-3 ( [ ROUNDED ] ) ...
[ ON SIZE ERROR imper-stmt1 ]
[ NOT ON SIZE ERROR
imperative-stmt2 ]
[ END-MULTIPLY ]
MULTIPLY - Examples
MULTIPLY 5 BY A
MULTIPLY 5 BY A ROUNDE D
MULTIPLY A BY B
MULTIPLY A BY B GIVING C D
MULTIPLY A BY B ON SIZE ERROR
MOVE 1 TO ERROR-FLAG
MULTIPLY A BY B GIVING C
ON SIZE E RROR
MOVE 1 TO ERROR-FLAG
NRI-IT
Page 50 of 148
Cobol
Procedure Division
DIVIDE
DIVIDE { id-1 INTO
lit-1 }
( id-2 [ ROUNDED ] ) ...
[ ON SIZE ERROR imper-stmt1 ]
[ NOT ON SIZE ERROR
imperative-stmt2 ]
[ END-DIVIDE ]
DIVIDE { id-1 {BY
{ id-2
lit-1 } INTO} lit-2 }
GIVING ( id-3 [ ROUNDED ] ) ...
[ ON SIZE ERROR imper-stmt1 ]
[ NOT ON SIZE ERROR imperative-stmt2 ]
[ END-DIVIDE ]
DIVIDE A INTO B
DIVIDE A INTO B
ROUNDED
DIVIDE A INTO B C
DIVIDE A INTO B
GIVING C
DIVIDE 2 INTO A
GIVING B C
DIVIDE A BY B
GIVING C
DIVIDE A BY 5
GIVING B
REMAINDER C
BEFORE
A
B
C
AFTER
A
B
2
2
10
9
2
2
5
5
2
2
10
10
14
-
2
2
5
10
7
5
NRI-IT
Page 51 of 148
Cobol
Procedure Division
COMPUTE
COMP UTE
- More than one operation in a single statement
- Shortens Programs
- Avoids Intermediate data names
E XPRESS IONS
- Made up of Operat ors, Data Names & Literals
- Operators evaluated based on parenthesis and/or precedence
NRI-IT
Page 52 of 148
Cobol
Exercises
EXERCISES
1.
01
VAL-1
PIC
999V99
VALUE
999.45.
01
VAL-2
PIC
9(5)V999
VALUE
99008.301.
01
VAL-3
PIC
9(5)V99
VALUE
11.3.
01
VAL-4
PIC
9999
VALUE
300.
What will be contained in VAL-1,VAL-2,VAL-3,VAL-4 after executing the following statement
a.
b.
C.
D.
ADD VAL-1, VAL-2 GIVING VAL-3 ON SIZE ERROR MOVE ZERO TO VAL-3.
ADD VAL-2, VAL-4 GIVIGN VAL-3 ON SIZE ERROR MOVE ZERO TO VAL-3.
DIVIDE VAL-3 INTO VAL-4 GIVING VAL-3 ROUNDED
MULITPLY VAL-4 BY VALI-1 GIVING VAL-4 ON SIZE ERROR MOVE 1 TO VAL-4
COMPUTE A = 999.988
COMPUTE A ROUNDED = 999.985
COMPUTE B = 8888.50 / 5.25 + 99.5 / 5.0 * 4425.5 ON SIZE ERROR MOVE 1 TO B.
A = 1.555, B= 9999.99 C = -11115.96. COMPUTE B ROUNDED = C * A
COMPUTE B ROUNDED = C ROUNDED * A ROUNDED
4. A field name STRING-1 contains 80 chars. The char (/) or (,) is used to indicate the end of
a word within these 80 chars. Write the cobol statement to find the number of words in
STRING-1 and the length of the individual words
1. A field named NAME contains 40 characters. Write a COBOL statement to change all
instances of MR. by SRI and MRS by SMT
NRI-IT
Page 53 of 148
Cobol
Exercises
NRI-IT
Page 54 of 148
Cobol
RELATION OPERATORS
Causes a comparison of two operands. Operands can be an Identifier, Literal or Arithmetic
Expression
Syntax
operand-1 relop operand-2
Operand-1, operand-2 can be an identifier, literal, arithmetic expression, index-name or a pointer.
Relational Operators
[NOT] >
[NOT] <
IS [NOT] EQUAL TO
[NOT] =
>=
<=
NRI-IT
Page 55 of 148
Cobol
Example
l-A JOES
l- B JOE taken as JOE
l-A > l- B is TRUE
CLASS CONDITION
Numeric or Alphabetic or user defined class-name check of the operand
Numeric test cannot be done for an item declared as alphabetic (P IC A)
Alphabetic test cannot be done for item declared as Numeric (PIC 9)
Packed-decimal allowed for Numeric test
Syntax
IF id-1 IS [ NOT ]
{NUMERIC
ALPHABETIC
ALPHABETIC-LOWER
ALPHABETIC-UPPER
class- name }
SIGN CONDITION
operand-1 IS [ NOT ]
{POSITIVE
NEGATIVE
ZERO }
Determines whet her algebraic value is less than greater than or equal to zero
operand-1 must be a numeric identifier, or arithmetic containing at least one reference to a
variable
NRI-IT
Page 56 of 148
Cobol
Condition Name
It is a subset of relational condition
It tests a conditional variable to determine whether its value is equal to any value(s) associated
with the condition-name.
condition-name is used in conditions as an abbreviation for the relation condition.
Syntax :
condition-name-1
Conditional expression
Examples
IF ASSOC-AGE > 80
SET SENIOR-ASSOC TO TRUE
END-IF
IF ASSOC-SAL IS POSITIVE
SET DEBIT-AMOUNT TO TRUE
END-IF
COMPLEX CONDITIONS
Formed by
- Combining simple conditions
- Nested IFs
- Logical Connectives
Logical Operators
- Used to combine simple conditions
- Abbreviating conditions
- For negation
LOGICAL OPERATORS
NOT
- Logical Negation
OR
- Logical Inclusive
AND
- Logical Conjunction
NRI-IT
Page 57 of 148
Cobol
EVALUATION RULES
Precedence
- Arithmetic Expression
- All Relational Operators
- NOT
- AND
- OR
If a condition is put in parenthesis, it is evaluated and its truth value depends on the truth value of
its constituents
Examples
A > B OR NOT C OR D
= (A>B) OR NOT (A>C) OR (A>D)
GO TO
The GO TO statement transfers control from one part of the Procedure Division to another. The GO TO
statement has four formats:
NRI-IT
Page 58 of 148
Cobol
Unconditional GO TO: The unconditional GO TO statement transfers control to the first statement in the paragraph or section
named in procedure-name
Must be a proc edure or a section in the same Procedure Division as the GO TO statement. The number
of procedure-names must not exceed 255.
identifier-1
Must be a numeric elementary data item, which is an integer.
If equal to 1, control is transferred to the first statement in the procedure named by the first occurrence
of procedure-name-1
If equal to 2, control is transferred to the first statement in the procedure named by the second
occurrence of procedure-name-1, and so forth.
NRI-IT
Page 59 of 148
Cobol
If the value of identifier is anything other than a value within the range of 1 through n (where n is the
number of procedure-names specified in this GO TO statement), no control transfer occurs.
Instead,
ALTER
Changes the trans fer point specified in a GO TO statement
The altered GO TO statement transfers control to the first statement of the paragraph named in
the ALTER statement.
ALTER procedure-name-1 TO
PROCEED TO
procedure-name-2
procedure-name-1 must be that contains only one sentence: a GO TO without the DEPE NDING
ON phras e
NRI-IT
Page 60 of 148
Cobol
ALTER - Example
PROCEDURE DIVISION.
.....
A1-PARA.
GO TO A1-FIRST-TIME.
A1-FIRST- TIME.
INIT W-REC-COUNTER.
ALTER A1-PARA TO
A1-NEXT-TIME.
A1-NEXT-TIME.
......
GO TO . is a GO TO form for ALTER and can be used in the above instead of GO TO A1FIRST-TIME.
IF
IF condition-1 THEN
{ statement-1 ...
NEXT SENTENCE }
[ ELSE [ statement-2 ...
NEXT SENTENCE ] ]
[ END-IF ]
NE XT SE NTE NCE means execution should move to stmt after the
next separator period
Never use NE XT SENTE NCE and Period as IF terminator. It is not a
good programming practice
statement-1, statement-2
Can be any one of the following:
An imperative statement
A conditional statement
An imperative statement followed by a conditional statement.
NRI-IT
Page 61 of 148
Cobol
CONTINUE - Example
IF YEAR-IS-NOT-LEAP
CONTINUE
ELSE
ADD 1 TO NO-OF-FEB-DAYS
END-IF
The above IF usage is preferred compared to IF NOT given below:
IF NOT YEAR-IS-NOT-LEAP
ADD 1 TO NO-OF-FEB-DAYS
END-IF
NRI-IT
Page 62 of 148
Cobol
EVALUATE
Provides a shorthand notation for a series of nested IF statements.
It can evaluate multiple conditions.
conditions.
Provides better readability.
When a satisfiable WHE N is met, processing breaks off from the rest of the evaluate block
NRI-IT
Page 63 of 148
Cobol
1.
Each selection object within the set of selection objects for the first WHEN phras e is
compared to the selection subject having the s ame ordinal position within the set of selection
subjects. One of the following conditions must be satisfied if the comparison is to be satisfied:
a.
If the items being compared are assigned numeric or nonnumeric values, or a range of
numeric or nonnumeric values, the comparison is satisfied if the value, or one value in the range
of values, assigned to the selection object is equal to the value assigned to the selection subject,
according to the rules for comparison.
b.
If the items being compared are assigned truth-values, the comparison is satisfied if the
c.
If the selection object being compared is specified by the word A NY, the comparison is
2.
If the above comparison is satisfied for every selection object within the set of selection
objects being compared, the WHE N phrase containing that set of selection objects is selected as
the one satisfying the set of selection subjects.
3.
If the above comparison is not satisfied for every selection object within the set of
selection objects being compared, that set of selection objects does not satisfy the set of selection
subjects.
4.
This proc edure is repeat ed for subsequent sets of selection objects in the order of their
appearance in the source program, until either a WHEN phrase satisfying the set of selection
subjects is selected or until all sets of selection objects are exhausted.
NRI-IT
Page 64 of 148
Cobol
Example 1
EVALUATE proc-type ALSO
cust-type
WHEN 1 ALSO 1
MOVE 1 TO RESULT
WHEN 3 ALSO 1 THRU 2
MOVE 2 TO RESULT
WHEN 2 ALSO 1
MOVE 3 TO RESULT
WHEN OTHER
MOVE 0 TO RESULT
END-EVALUATE
In this example subject of Evaluation is an Expression. Depending on these values the control
passes to the corresponding WHEN.
Example 2
EVALUATE TRUE
WHEN l-VALUE < 100
MOVE 1 TO RESULT
WHEN l-VALUE < 1000
MOVE 2 TO RESULT
WHEN l-VALUE < 10000
WHEN OTHER
MOVE 0 TO RESULT
END-EVALUATE
In this example, the subject is TRUTH value. Depending on the values the WHEN phrase
satisfying the TRUTH value is executed.
If a WHEN does not have a associated imperative statement it is a do- nothing condition (same as
coding CONTINUE)
PERFORM
The PERFORM statement trans fers control explicitly to one or more procedures and implicitly returns
control to the next executable statement after execution of the specified procedure(s) is completed.
An out-of-line PE RFORM statement (P rocedure-name-1 is specified).
An in-line PERFORM statement (Procedure-name-1 is omitted). An in-line PERFORM statement must
be delimited by the END-PE RFORM phrase.
NRI-IT
Page 65 of 148
Cobol
The in-line and out-of-line PE RFORM statements cannot be combined. For example, if procedurename-1 is specified, imperative-statement-1 and the END-PE RFORM phrase must not be specified.
Executes group of consecutive statements written inline (called INLINE PERFORM) or elsewhere
(called OUT-OF-LINE PERFORM) in a program
Has four formats
Departs from normal sequence of execution and implicit return to next statement after completion
PERFORM (Basic)
PERFORM
{ proc- name1[{ THRU proc- name2
THROUGH } ]
imp-statement-1 END-PERFORM
}
Example 1 (Out-of- line)
PERFORM PARA-1 THRU PARA-2
In this example the execution of PERFORM statement will start with execution of first statement in PARA-1
and ends with execution of last statement in PARA -2. All the paragraphs in bet ween these 2 paragraphs
will be execut ed. And then control returns to the statement next to the perform statement. This transfer of
control occurs implicitly
Example 2 (Inline)
PERFORM
MOVE 1 TO FLAG-1
MOVE 2 TO FLAG-2
END-PERFORM
In the above example the control is not transferred anywhere. This will execute the statements within the
perform statement. This perform is called inline perform statements which does not contain any section
name or paragraph name. This perform statement should end wit h an END-PE RFORM statement
NRI-IT
Page 66 of 148
Cobol
PERFORM (TIMES)
Example
PERFORM B1-PROCESS
THRU B1-PROCESS-EXIT
10 TIMES
In this example the number of times perform statement is going to be ex ecuted is predet ermined. Hence
this perform statement will be executed 10 times.
NRI-IT
Page 67 of 148
Cobol
until-phrase
UNTIL condition WITH TEST { BEFORE
AFTER } ]
In the UNTIL phrase format, the procedure(s) referred to are performed until the condition
specified by the UNTIL phrase is true. Control is then passed to the next exec utable statement
following the PERFORM statement.
Here the condition is tested before only at the beginning of each execution by default
But this default is overridden by TES T AFTE R phrase. If the TES T AFTER phrase is specified, the
statements to be performed are executed at least once before the condition is tested (corresponds to
DO UNTIL).
In either case, if the condition is true, control is trans ferred to the next executable statement
following the end of the PERFORM statement. If neither the TES T BEFORE nor the TES T AFTER
phrase is specified, the TES T BEFORE phrase is assumed.
Ente
r
True
Condition
EXI
T
False
NRI-IT
Page 68 of 148
Cobol
PERFORM (UNTIL)
Example
MOVE 10 TO I-CNT
PERFORM UNTIL I-CNT = ZERO
WRITE OUT-REC FROM I-ERR-REC (I-CNT)
SUBTRACT 1 FROM I-CNT
END-PERFORM
In the above example, the WRITE and SUBTRACT statements will be executed until the I-CNT
becomes zero. Here perform will be executed 10 times.
PERFORM (VARYING)
PERFORM
{ proc-name1[THRU proc-name2]
varying-phrase after-phrase
varying-phrase imp-stmt-1 END-PERFORM
}
varying-phrase
[ WITH TEST
{BEFORE
AFTER } ]
VARYING { id-1
FROM { id-2 lit-1
Inx- nm1 }
inx- nm-2}
BY { id-3
UNTIL cond-1
lit-2 }
after-phrase
( AFTER { id-4
FROM
{ id-5 lit-1
inx- nm1 }
inx- nm-2}
BY { id-6
UNTIL cond-2
lit-2 } ) ...
After-phrase provides for varying more than one identifier
If any of the operands specified in cond-1 or cond-2 is subscripted or reference modified, the
subscript or reference-modifier is evaluat ed each time the condition is tested.
NRI-IT
Page 69 of 148
Cobol
and the statements to be performed are executed, if at all, only when all specified tests fail. When
TES T AFTE R is indicated, the statements to be performed are executed at least once, before any
condition is tested.
Changing the values of identifiers and/or index -names in the VARY ING, FROM, and BY phras es
during execution changes the number of times the procedures are exec uted.
NRI-IT
Page 70 of 148
Cobol
Ente
r
True
Cond1
Exi
t
False
Add increment to
indentifier-1
NRI-IT
Page 71 of 148
Cobol
True
Cond1
Exi
t
False
True
Cond2
NRI-IT
Page 72 of 148
Cobol
EXIT
Provides a return mechanism for the Perform statement having Exit para as the last paragraph
The E XIT statement provides a common end point for a series of paragraph.
Must be preceded by a paragraph name
Must be the only statement in the paragraph
Falls thru if there is no associated Perform
Provides a common exit point for a series of paragraphs (by executing a GO TO PARA-E XIT in the
paragraph)
EXIT - Example
PROCEDURE DIVISION.
....
PERFORM B1-PROCESS
UNTIL A > 5.
.....
B1-PROCESS.
.
ADD 1 TO A.
IF NOT-VALID-ACTION
PERFORM B1-PROCESS-EXIT
...
B1-PROCESS-EXIT
EXIT.
NRI-IT
Page 73 of 148
Cobol
Exercises
EXERCISES
1. Rewrite the following IF statement-using condition names. Also indicate how the condition
names are to be defined in the DATA DIVISION.
IF MARKS >= 90 MOVE O TO GRADE
ELSE IF MARKS >= 75 MOVE E TO GRADE
ELSE IF MARKS >= 60 MOVE D TO GRADE
ELSE IF MARKS >= 50 MOVE C TO GRADE
ELSE IF MARKS NOT > 40 MOVE B TO GRADE
ELSE MOVE F TO GRADE
2. The following is the information about the patient file
Description
Length
Name
30
Sex
1 (Male M, Female - F)
Age
Height
Weight
A paragraph named PROCESS-PARA needs to be executed only if the patient is Male whose age
is between 25 and 45 yrs and Height is 160 175 cms and weight is 60 75 kgs.
Write the necessary IF statement using suitable condition names. Also write the record
description entry for the patient file
NRI-IT
Page 74 of 148
Cobol
MOVE
MOVE { id-1 TO id-2 ...
lit-1 }
All identifiers can be either group or elementary items.
The data in the sending item is moved into the data item referenced by each identifier-2 in the order in
which it is specified.
NRI-IT
Page 75 of 148
Cobol
MOVE {CORRESPONDING
CORR} id-1 TO id-2
Both identifiers must be group items
Both identifiers following the keyword CORRESPONDING must name group items. In this discussion,
these identifiers are referred to as identifier-1 and identifier-2.
A pair of data items (subordinate items), one from identifier-1 and one from identifier-2, correspond if
the following conditions are true:
In a MOVE statement, at least one of the data items is an elementary item, and the move is permitted
by the move rules.
The subordinate items are not identified by the keyword FILLE R.
Neither identifier-1 nor identifier-2 is described as a level 66, 77, or 88 item, nor is either described as
a USAGE IS INDE X item. Neither identifier-1 nor identifier-2 can be referenc e-modified.
The subordinate items do not include a RE DEFINES, RE NAMES, OCCURS, or USAGE IS INDE X
clause in their descriptions.
However, identifier-1 and identifier-2, they can cont ain or be subordinate to items containing a
REDEFINES or OCCURS clause in their descriptions.
Neither identifier-1 nor identifier-2 nor the two subordinate items are described as USAGE IS
POINTER items.
Identifier-1 and/or identifier-2 can be subordinate to a FILLE R item.
Valid and Invalid Elementary Moves
NRI-IT
Page 76 of 148
Cobol
Sending
Item
Alphabetic
and
SPACE
Alphanume
ric(2)
Alphanume
ric-Edited
Numeric
Integer and
ZERO(5)
Numeric
Noninteger(6)
NumericEdited
Receiving Ite m
Alpha
Numeric
numeric
Edited
Yes
No
Alphab
etic
Aplhanu
me ric
Numeric Edited
Yes
Yes
Yes
Yes
Yes
Yes(3)
Yes(3)
Yes
Yes
Yes
No
No
No
Yes
Yes
Yes
Yes
No
No
No
Yes
Yes
No
Yes
Yes
Yes
Yes
No
2.
3.
Figurative constants and nonnumeric literals must consist only of numeric characters and will be
treated as numeric integer fields.
4.
Figurative constants and nonnumeric literals must consist only of numeric characters and will be
treated as numeric integer fields. The ALL literal cannot be used as a sending item.
5.
6.
7.
Includes floating-point literals, external floating-point data items (USA GE DISP LAY), and internal
floating-point data items (USA GE COMP -1 or USAGE COMP-2).
8.
NRI-IT
Page 77 of 148
Cobol
will be equal to the number of characters in data-name-1 plus one minus leftmost-characterposition. The evaluation of length must result in a positive nonzero integer.
Example
77 name
pic x(25).
77 first-name pic x(10).
77 last- name pic x(15).
MOVE name(1:10)
MOVE name(11:)
TO first- name
TO last-name
Move - Rules
Pointer and Index variables not allowed
- In MOV E CORR - ignored
Length, Sub-string, Reference modification evaluation
- For source variable only once - before the move to the 1st target variable
- For each target variable before the move
MOVE a(b) TO b, c(b)
Occurs depending on Clause object (ODO) location
- When not in same group
ODO object value decides the length
Set value prior to MOVE
NRI-IT
Page 78 of 148
Cobol
INITIALIZE
Sets selected categories of data fields to predet ermined values.
It is functionally equivalent to one or more MOVE
Can be at
- Group level
- Elementary level
INITIALIZE ( id-1
[REPLACING
{ALPHABETIC
ALPHANUMERIC DATA
NUMERIC
ALPHANUMERIC-EDITED
NUMERIC-EDITED }
BY {id-2
lit-1 }] ) ...
When id-1 specifies a group item only those items that belong to the category denoted by the
REPLA CING phrase will be initialized by the value denoted by id-2/lit-1
Example
01 A.
02
02
02
02
A1
A2
A3
A4
PIC
PIC
PIC
PIC
9(5).
X(4).
9(3).
Z(3)9.99.
NRI-IT
Page 79 of 148
Cobol
Example
1
A.
2 A1
PIC 9(5).
02 A2
PIC X(10).
02 B REDEFINES A2.
03 B1
PIC 9(4).
03 B2
PIC 9(4)V99.
INITIALIZE A
In the above example A1 will be zeroes
A2 will be filled with spaces and not zeroes.
INITIALIZE B
This will fill B1 and B2 with zeroes
INITIALIZE - Rules
Category of Id-2 should be compatible that of CORR REPLACING
Whether identifier-1 references an elementary or group item, all operations are performed as if a
series of MOVE statements had been written, each of which had an elementary item as a receiving
field.
Same Category cant be repeated
If the REPLA CING phrase is specified:
If identifier-1 references a group item, any elementary item within the data it em referenced
by identifier-1 is initialized only if it belongs to the category specified in the REPLA CING phrase.
If identifier-1 references an elementary item, that item is initialized only if it belongs to the
category specified in the REP LACING phrase.
All such elementary receiving fields, including all occurrences of
affected, wit h the following
exceptions:
NRI-IT
Page 80 of 148
Cobol
INITIALIZE - Examples
INITIALIZE id-1
Length of Id-1
9(5)
X(5)
99XX9
Before
12345
AB123
12AB3
After
00000
Bbbbb
Bbbbb
INSPECT
Specifies that characters, or groups of characters in a data it em are
to be
- Counted (tallied)
- 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.
NRI-IT
Page 81 of 148
Cobol
being compared:
1.
When both the TALLYING and REPLACING phrases are specified, the INSPECT
The first comparand is compared wit h an equal number of leftmost contiguous characters
in the inspected item. The comparand matches the inspected characters only if both are equal,
character-for-character.
3.
If no match occurs for the first comparand, the comparison is repeated for each
successive comparand until either a match is found or all comparands have been acted upon.
4.
TALLYING/ REPLA CING phrase descriptions. In the inspected item, the first character following
the rightmost matching character is now considered to be in the leftmost character position.
The
If no match is found, then, in the inspected item, the first character following the leftmost
The process
If the CHARA CTE RS phrase is specified, an implied 1-character comparand is used in the
The actions taken in rules 1 through 6 (defined as the comparison cycle) are repeated until
the rightmost character in the inspected item has either been matched or has been considered as
being in the leftmost character position. Inspection is then terminated.
Format 1
INSPECT id-1
TALLYING
id-2 FOR
{CHARACTER ALL
{id-3 lit-1} LEADING
{id-3 lit-1}}
[{BEFORE
AFTER} INITIAL {id-4 lit-2}]
NRI-IT
Page 82 of 148
Cobol
INSPECT id-1
Format 2
REPLACING
{CHARACTER ALL
{id-2 lit-1} LEADING
{id-2 lit-1}}
BY {id-3 lit-2}
[{BEFORE
AFTER} INITIAL {id-4 lit-3}]
Format 3
INSPECT id-1
CONVERTING
{id-2 lit-1}
TO
{id-3 lit-2}
[{BEFORE
AFTER} INITIAL {id-4 lit-3}]
INSPECT - Examples
77 countr
PIC 9 VALUE ZERO.
01 data-1
PIC X(6).
INSPECT data-1 TALLYING countr FOR CHARACTERS AFTER INITIAL "S"
REPLACING ALL "A" BY "O"
DATA-1
COUNTR
DATA-1
Before After
After
ANSELM
SACKET
PASSED
3
5
3
ONSELM
SOCKET
POSSED
NRI-IT
0
0
000LM
0000T
Page 83 of 148
Cobol
INSPECT - Examples
INSPECT data-1 CONVERTING abcdefghijklmnopqrstuvwxyz" TO
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
AFTER INITIAL "/" BEFORE INITIAL"?"
Before
After
a/five/?six
r/Rexx/RRRr
zfour?inspe
a/FIVE/?six
r/REXX/RRRR
zfour?inspe
STRING
Strings toget her the partial or complet e contents of two or more data items or literal into one single
data item.
One S TRING statement can be written instead of a series of MOVE statements.
Process is called concatenation
FIELD-1
FIELD-2
FIELD-3
FIELD-4
PIC
PIC
PIC
PIC
X(4)
X(6)
X(9)
X(14)
VALUE
VALUE
VALUE
VALUE
ABCD.
MA IN .
121,34,56.
SPACES.
NRI-IT
Page 84 of 148
Cobol
In the above example, FIELD-1 does not contain any delimiters, all 4 characters are moved to
FIELD-4
First 2 characters of FIELD-2 are moved to FIELD-4 as third character is the delimiter
First 3 characters of FIELD-3 are moved to FIELD-4 as 4th character is the delimiter
STRING - Rules
Receiving fields must not be
- Edited field
- With Justified clause
- With reference modification
Pointer variable must be
- Elementary and Numeric
- Large enough to hold max length of rec eiving field
ON OVE RFLOW executed when pointer Value <= 0 or exceeds max length of receiving field
UNSTRING
Causes contiguous data in a sending field to be separated and placed into multiple receiving
fields:
- Number of characters placed in each receiving field
- Count of the total number of characters transferred
- Special action when all the receiving fields are filled before the end of the sending item
Useful to convert display format dat a to compact form
UNSTRING id-1
[DELIMITED BY ALL {id-2 lit-1}
[OR ALL {id-3 lit-2} ...]]
INTO ( id-4
[DELIMITER IN id-5] [ COUNT IN id-6] ) ...
[WITH POINTER IN id-7 ] [TALLYING IN id-8 ]
[ON OVERFLOW imperative stmt-1]
[NOT ON OVERFLOW
imperative stmt-2]
[END-UNSTRING]
NRI-IT
Page 85 of 148
Cobol
UNSTRING - Example
FULL-NM = EDISON, THOMAS ALVA
UNSTRING
FULL-NM DELIMITED BY , OR SPACE
INTO LAST-NM COUNT IN LAST-NM-CNT
FIRST-NM COUNT IN FIRST-NM-CNT
MID-NM COUNT IN MID-NM-CNT
LAST-NM = EDISON LAST-NM-CNT = 6
FIRST-NM= THOMAS FIRST-NM-CNT = 6
MID-NM = ALVA
MID-NM-CNT = 4
UNSTRING - Rules
If the DELIMITED BY phrase is not specified, the number of characters examined is equal to the
size of the current data receiving field.
If the POINTE R phrase
- Is not specified an implicit value of 1 is assumed
If specified, the source field is examined from the relative character position specified by the value in
the pointer field.
SET
SET - CONDITION NAME
SET cond- name1 ... TO TRUE
The value associated with a cond-name1 is placed in its conditional variable
If more than one Value is defined for the cond-name1 then the 1st is used
If multiple condition-names are specified, the results are the same as if a separate SE T statement
had been written for each condition-name in the same order in which they are specified in the SET
statement.
NRI-IT
Page 86 of 148
Cobol
Example
77 I-EOF-FLAG PIC x.
88 C-EOF VALUE Y.
SET C-EOF TO TRUE
(I-EOF-FLAG will have the value Y after the execution of the SET statement)
77 I-ACTION-FLAG PIC X.
88 C-ADD
VALUE A space.
88 C-DEL
VALUE D.
88 C-MOD
VALUE M.
SET C-ADD TO TRUE
(Will get value A - first lit in value clause)
SET - Pointer Data
SET { id-1
ADDRESS OF id-2 } ...
TO { ADDRESS OF identifier-3
id-4
NULL
NULLS }
id-1 and id-4 must be POINTERs
id-2 and id-3 must be 01 or 77 levels in LINKA GE
NULL, NULLS sets the receiving field to cont ain the value of an invalid address.
NRI-IT
Page 87 of 148
Cobol
SET Indexes
SET index-name-3
UP BY
identifier-3
DOWN BY integer-2
When this form of the SE T statement is executed, the value of the receiving field is increased (UP BY)
or dec reas ed (DOWN BY) by a value that corresponds to the value in the sending field.
The receiving field can be specified by index-name-3. This index-name value both before and after
the SET statement execution must correspond to the occurrence numbers in an associated table.
The sending field can be specified as identifier-3, which must be an elementary integer data item, or
as integer-2, which must be a nonzero int eger.
When the Format 2 SET statement is executed, the contents of the receiving field are inc reased (UP
BY) or decreased (DOWN BY ) by a value that corresponds to the number of occurrences represented
by the value of identifier-3 or integer-2. Receiving fields are acted upon in the left-to-right order in
which they are specified. The value of t he incrementing or dec rementing field at the beginning of SE T
statement execution is used for all receiving fields.
NRI-IT
Page 88 of 148
Cobol
Sub-Program
10. Sub-Program
CALL
Trans fers control from one object program to another within the run unit.
Called program starts executing from:
- Top of program
- ENTRY label (not good programming practice)
Trans fer control methods
- Call nested program
- Static call
- Dynamic call
Parameters to called program:
- By reference
- By content
Use RE TURN-CODE special register to pass return codes
Return of control depends on the termination stmt issued by the called program
- Stop run unit
- Return to called program
NRI-IT
Page 89 of 148
Cobol
Sub-Program
CALL - Examples
CALL SUBPGM1.
CALL l-SUBPGM-1 USING
l-PARM1 l-PARM2.
CALL l-SUBPGM1
USING
BY CONTENT
l-PARM1
l-PARM2
BY REFERENCE
l-PARM3.
CALL - Calling pgm
WORKING-STORAGE SECTION.
77 l-subpgm-1 pic x(8) value SUBPGM1.
01 l-parm1.
05 l- name
05 l-emp- no
01 l-parm2.
05 l-salary
05 l- hra
05 l- leave
01 l-parm3.
05 l- gross
05 l-deduct
pic x(30).
pic 9(4).
pic s9(9)v99 comp-3.
pic s9(9)v99 comp-3.
pic s9(2)v9 comp-3.
pic s9(9)v99 comp-3.
pic s9(9)v99 comp-3.
PROCEDURE DIVISION.
....
CALL l-SUBPGM1 USING
BY CONTENT
l-PARM1 l-PARM2
BY REFERENCE l-PARM3.
IDENTIFICATION DIVISION.
PROGRAM-ID. 1-SUBPGM1.
NRI-IT
Page 90 of 148
Cobol
Sub-Program
LINKAGE SECTION.
01 L-PARM3.
05 l- gross
pic s9(9)v99 comp-3.
05 l-deduct pic s9(9)v99 comp-3.
01 L-PARM1.
05 l- name
pic x(30).
05 l-emp- no pic 9(4).
01 L-PARM2.
05 l-salary
pic s9 (9) v99 comp-3.
05 l- hra
pic s9(9)v99 comp-3.
05 l- leave
pic s9(2)v9 comp-3.
PROCEDURE DIVISION USING
L-PARM1 L-PARM2 L-PARM3.
CALL - Rules
The correspondence of identifiers in the usi ng clause of called and calling programs is positional
File-name in using is only for QSAM files
Addre ss of option can be used only for Linkage variables with level 01 or 77
Exception or Overflow cond occurs when the called program cannot be made available.
Called program must not execute a CALL statement that directly or indirectly calls the calling
program (Recursion not allowed)
CANCEL
CANCEL {id-1 lit-1}
Ensures that the next time the referenced subprogram is called it will be ent ered in its initial state.
All programs contained in the Canceled program are also canceled.
Same as executing an E XIT PROGRAM or GOBACK in the called subprogram if it possesses the
INITIAL attrib.
NRI-IT
Page 91 of 148
Cobol
Sub-Program
ENTRY
ENTRY lit-1 [USING id-1 ...]
Establishes an alternate entry point
Execution of the called program begins at the first executable stmt
following the E NTRY stmt whose literal corresponds to the CA LL stmt literal or identifier
Not a recommended way of entering a program
EXIT PROGRAM
EXIT PROGRAM
Specifies the end of a called program and returns control to the calling program
When no CALL statement is active, control passes through t he exit point to the next executable
stmt
When there is no next executable stmt in a called program, an implicit E XIT PROGRAM stmt is
executed
E XIT PROGRAM stmt in a called program with INITIAL attribute is equivalent to executing a
CANCEL
An E XIT PROGRAM ex ecuted in a main program has no effect.
STOP
STOP {RUN
lit-1}
Halts execution of the program :
- Permanently (RUN option)
- Temporarily (Lit-1 option)
literal communicated to operator and execution suspended
NRI-IT
Page 92 of 148
Cobol
Sub-Program
END PROGRAM
END PROGRAM program- name .
An END PROGRAM header terminates a nested program or separates one program from another
in a sequence of programs.
The program-name must be same as the program-name declared in the corresponding
PROGRAM-ID paragraph.
An END P ROGRAM is optional for the last program in a sequence only if that program does not
contain any nested source programs.
NRI-IT
Page 93 of 148
} ...
Opens the file for processing
E XTE ND is allowed only for sequential files (not for VSE)
OUTP UT clears the file of its existing records
CLOSE
CLOSE file- name1 ...
Closes the open file
Terminates the file processing
READ
Format-1 - Sequential Read
READ file-name-1 NEXT RECORD
[ INTO identifier-1 ]
[ AT END imperative-stmt-1]
[ NOT AT END imperative-stmt-2 ]
[ END-READ ]
NE XT phrase is optional for SEQUENTIA L access mode & a must for DYNAMIC
When the REA D NE XT statement is the first statement to be executed aft er the OPE N statement
on the file, the next record is the first record in the file
USAGE:1.
The sequential read is used when the exact key value is not known and if we want to
This sequential read is also used when Alternate key is used as key to the indexed file.
When we need to process records with part of the key matching, we use sequential read.
For E.G, The key field of the EMP-MA TE R file is Emp-no, Designation., date-of-joining, if we want
to process all employees belonging to designation Associates, we use sequential read of the
indexed file
The result of the execution of a READ statement with the INTO phrase
is equivalent to the
If the KEY phras e is not specified, the prime RE CORD KEY becomes the key of reference for this
request. When dynamic access is specified, the prime RE CORD KEY is also used as the key of
reference for subsequent executions of sequential READ statements, until a different key of reference
is established.
KEY Phrase: - When the KEY phrase is specified, dat a-name becomes the key of reference for this
request. When dynamic access is specified, this key of reference is used for subsequent executions
of sequential REA D statements, until a different key of reference is established.
But since the record description contains two 01 levels and its a variable length file
Contents of record area after second READ is executed:
01234567890123456789??????????
The last 10 characters of the record area is undefined. I.e. This storage area can hold any
characters depending on the sequence of reads and any process done inside the program using
RECORD-1. In the above example, assume there was no processing then the last 10 bytes would
contain UVWXYZ1234. But this area cannot be accessed, when we use RECORD-2 layout
because this is implicitly redefined item
More on File Position Indicators
The file position indicator is a conceptual entity used to facilitate exact specification of the next
record to be accessed within a given file during certain sequences of input-output operations. Only the
OPEN, CLOSE, READ and S TART statements affect the setting of the file position indicator. The
concept of a file position indicator has no meaning for a file opened in the output or extends mode.
Indicates the next record to be accessed for sequential COBOL requests
You do not specify them anywhere in your program
It is set by successful:
1.
2.
The successful execution of an OPE N INPUT or OPE N I-O statement for sequential files sets
the file position indicator to 1.
3.
Execution of an OPE N INPUT or OPE N I-O statement sets the file position indicat or:
4.
For VSAM sequential and indexed files, to the characters with the lowest ordinal position in the
collating sequence associated with the file.
5.
6.
If the record is no longer accessible , i.e. it has been deleted, the file position indic ator is updated
to point to the next existing record in the file
The file position indicator has no meaning for random processing
READ - Example
File- Indexed, Dynamic Access
Record Description:
01 ASSOC-REC
05 ASSOC-NO-KEY PIC 9(4).
05 ASSOC-NAME PIC X(10).
Assoc #
Assoc Name
0004
RAJESH
0010
RAMESH
0015
GOPAL
0016
RAGHAVAN
0100
SARITA
0401
RANI
Operation
OPEN input
READ next
READ Key 0100
READ next
READ key 0015
READ key 0090
READ next
Record Area
Not defined
0004 Rajesh
0100 Sarita
0401 Rani
0015 Gopal
Undefined (Invalid key)
Undefined
START - Rules
Invalid Key arises if the record position is empty
When KEY phrase is not specified KEY EQUAL TO primary key is
implied
File position indicator points to the first record in the file whose key
field satisfies the comparison
When the KEY phrase is specified, the file position indicator is
positioned at the logical record in the file whose key field satisfies the comparison.
When the KEY phrase is not specified, KEY IS EQUAL (t o the prime
record key) is implied.
When the S TART statement is executed, a comparison is made
between the current value in the key data-name and the corresponding key field in the file's index.
PROGRAM COLLA TING SEQUENCE clause, if specified, has no
effect
The file position indicator points to the first record in the file whose
key field satisfies the comparison. If the operands in the comparis on are of unequal lengths, the
comparis on proceeds as if the longer field were trunc ated on the right to the length of the shorter field.
All other numeric and nonnumeric comparison rules apply
START
File- Indexed, Dynamic Access
Record Description:
01 ASSOC-REC
05 ASSOC-NO-KEY PIC 9(4).
05 ASSOC-NAME PIC X(10).
Assoc # Assoc Name
0004
RAJESH
0010
RAMESH
0015
GOPAL
0016
RAGHAVAN
0100
SARITA
0401
RANI
OPERATION
OPEN I-O
START ASSOC.NOKEY = 0004
READ NEXT
START ASSOC-NOKEY > 0016
READ NEXT
START ASSOC-NOKEY > 0401
POINTER VALUE
TOP OF FILE
0004
REC-AREA
NOT DEFINED
NOT DEFINED
0010
0100
0004 RAJESH
0004 RAJESH
0401
UNKNOWN
0100 SARITA
0100 SARITA
Before the WRITE statement is executed, you must set the prime record key (the RECORD KEY
data item, as defined in the File-Control ent ry) to the desired value.
If the ALTE RNA TE RECORD KEY clause is also specified in the File-Control entry, each alternate
record key must be unique, unless the DUPLICA TES phrase is specified. If the DUPLICA TES phrase
is specified, alternate record key values may not be unique. In this case, the system stores the
records so that later sequential access to the records allows ret rieval in the same order in whic h they
were stored.
When ACCESS IS SEQUENTIA L is specified in the File-Cont rol entry, records must be released in
ascending order of RE CORD KEY values.
REWRITE
REWRITE record- name
[ FROM id-1]
[ INVALID KEY imperative-stmt-1]
[ NOT INVALID KEY
imperative-stmt-2 ]
[ END-REWRITE ]
Updates an existing record in a file
File should be opened in I-O mode
REWRITE - Rules
File should be opened in I-O
After REWRITE record is not available in the rec area
After a REWRITE statement with the FROM phrase is executed, the information is still available in
identifier-1
File position ind not affected
For Sequential files
DELETE
DELETE file- name-1 RECORD
[ INVALID KEY imperative-stmt-1]
[ NOT INVALID KEY imperative-stmt-2]
[ END-DELETE ]
Removes a record from an indexed or relative file
For indexed files, the key can then be reused for record addition.
For relative files, the space is then available for a new record with the
same RELA TIVE KEY value.
If the FILE STA TUS claus e is specified in the File-Control entry, the associated status key is updated
when the DE LE TE statement is executed.
The file position indicator is not affected by execution of the DE LE TE statement.
For a file in sequential access mode, the last input/output statement must have been a successfully
executed READ statement. When the DELE TE statement is executed, the system removes the record
retrieved by that READ statement.
For a file in sequential access mode, the INVALID KEY and NOT INVALID KEY phrases must not be
specified. However, an E XCEP TIONERROR procedure can be specified.
When the DELE TE statement is executed, the system removes the record identified by the contents of
the prime RE CORD KEY dat a item for VSAM indexed files, or the RELA TIVE KEY data item for VSAM
relative files. If the file does not contain such a record, an INVA LID KEY condition exists.
DELETE - Rules
File should opened for I-O
In sequential access mode, the last input/output statement must have been a successfully
executed READ
SORT
While processing sequential files, it is sometimes necessary that the records should appear in
some predetermined sequence. The proc ess of sequencing records in file in some predetermined
order on some fields is called SORTING
The fields based on which the records are sequenced are called SORT KEYS.
The sequencing can be ascending or descending order of the KEY.
FD
1
EMP-FILE.
EMP-REC.
02
ID-NUM
02
NAME
02
DEPARTMENT
02
BASIC-PAY
02
ALLOWANCE
02
DEDUCTION
PIC 9(6).
PIC X(24).
PIC X(10).
PIC 9(5)V99.
PIC 9(4)V99.
PIC 9(4)V99.
We want to sort this file on DEPARTME NT on ascending sequence and then within each
DEPARTME NT, arrange BAS IC-PAY on descending sequence. This means that the records with same
DEPARTME NT value are to be arranged from highest to lowest value of the BASIC-PAY. The work file
and output files are S ORT-FILE and OUTPUT-FILE. The FD and SD entries for these files are as follows
SD
01
FD
1
SORT-FILE
SORT-REC.
02
FILLER
02
DEPARTMENT
02
BASIC-PAY
02
FILLER
OUTPUT-FILE
OUT-REC
PIC X(30).
PIC X(10).
PIC 9(5)V99.
PIC X(12).
PIC X(59).
INPUT PROCEDURE:The sort statement before the start of the sorting process implicitly performs the specified input procedure.
This procedure reads the records from input file, performs the necessary processing and then release the
records to Sorting operation by RELEASE statement which is discussed later in this chapt er
OUTPUT PROCEDURE:The output procedure is performed implicitly by sort statement in order to perform editing on the sorted
records. The output procedure gets the sorted records by means of RE TURN statement that is discussed
later in this chapter.
SORT file-1 { ON
{ASCENDING
DESCENDING} KEY id-1... } ...
[WITH DUPLICATES IN ORDER]
[COLLATING SEQUENCE IS alphabet- name-1]
{USING file-2
INPUT PROCEDURE IS
proc-nm-1 [THRU proc-nm-2]}
{GIVING file-3
OUTPUT PROCEDURE IS
proc-nm-3 [THRU proc-nm-4]}
SORT - Examples
SORT sorted-emp- file
ASCENDING s-last-nm
s-first- nm
DESCENDING s-emp- nbr
USING emp- file
OUTPUT PROCEDURE
write-emp-list THRU
write-emp-list-exit
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT EMP-FILE ASSIGN TO EMPMSTR.
SELECT SORTED-EMP-FILE ASSIGN TO EMPSORT.
SELECT EMP-LIST ASSIGN TO REPORT.
DATA DIVISION.
FILE SECTION.
FD EMP-FILE
LABEL RECORDS ARE OMITTED.
01 EMP-REC.
05 EMP-NBR
PIC 9(4).
05 LAST-NM
PIC X(20).
05 FIRST-NM
PIC X(20).
05 MID-NM
PIC X(20).
SD SORTED-EMP-FILE
LABEL RECORDS ARE OMITTED.
01 SORT-EMP-REC.
05 S-EMP-NBR PIC 9(4).
05 S-LAST-NM PIC X(20).
05 S-FIRST-NM PIC X(20).
05 S-MID-NM
PIC X(20).
PROCEDURE DIVISION.
.....
SORT sorted-emp- file
ASCENDING s-last-nm s- first-nm
DESCENDING s-emp- nbr
USING emp- file
OUTPUT PROCEDURE write-emp- list THRU
write-emp-list-exit
...
WRITE-EMP-LIST.
......
WRITE-EMP-LIST-EXIT.
EXIT.
Collating Sequences
- COLLATING SEQUENCE option of the SORT statement that is defined in SPECIALNAMES paragraph
- PROGRAM COLLATING SEQUENCE if specified in the Configuration Section
- Default is EBCDIC
RELEASE
Transfers records to the initial phase of sort operation
Its like WRITE statement
RELEASE sort-rec-name-1
[FROM id-1]
If INPUT PROCEDURE is used, at- least one RELEASE stmt must be executed
RELEASE - Examples
MOVE
emp-rec
RELEASE sort-emp-rec
TO
sort-emp-rec
RELEASE sort-emp-rec
FROM emp-rec
RETURN
Trans fers records from the final phase of a sorting or merging operation to an OUTP UT
PROCEDURE.
Its like READ statement
WRITE-EMP-LIST.
SET c-not-sort-eof TO TRUE
PERFORM read-sorted-rec
THRU read-sorted-rec-exit
PERFORM UNTIL c-sort-eof
PERFORM string-emp-name
THRU string-emp-name-exit
MOVE w-emp-name TO rep- name
MOVE s-emp- nbr TO rep-emp-nbr
WRITE emp- list-rec
PERFORM read-sorted-rec
THRU read-sorted-rec-exit
END-PERFORM
.
WRITE-EMP-LIST-EXIT.
EXIT.
MERGE
Sometimes it becomes necessary to create a new output file from 2 input files. These 2 files needs to be
merged and new file needs to be created
For example A Company has its marketing operations divided into 2 zones and for each zone there is file.
Each of these files contains zone name, district name, salesman name, product name and amount of sales
for a particular product. The files are sorted on product name. We need to merge these 2 files into a single
file to get a single transaction file to update the master file.
The MERGE verb is used to merge 2 or more identical files sorted on the same field
MERGE file-1 { ON
{ASCENDING
DESCENDING} KEY id-1... } ...
[COLLATING SEQUENCE IS alphabet-name-1]
USING file-2 [file-3 ...]
{GIVING file-4
OUTPUT PROCEDURE IS
proc-nm-1 [THRU proc-nm-2]}
The input files to be merged through ME RGE statement are file-2, file-3. The file-1 is the work file, which
should be defined in the SD entry. The file-2 and file-3 should be sorted on the key used to
merge these 2 files.
MERGE - Examples
MERGE sorted-emp-ph- file
ASCENDING s-last-nm
s-first- nm
DESCENDING s-emp- nbr
USING emp-ph- file
emp-addon-ph- file
GIVING new-emp-ph- file
MERGE - Rules
When US ING / GIV ING option is specified the input / output file(s) to merge must not be open
The key used in the ME RGE statement cannot be variably located.
When the file referenced by filename-1 is merged control passes to first stmt in the OUTPUT
PROCEDURE.
Collating Sequences
-
COLLA TING
SEQUENCE
option
of
MERGE
statement
SPECIAL-NAMES paragraph
- PROGRAM COLLA TING SEQUENCE specified in the Configuration Section
Default is EBCDIC
that
is
defined
in
If you code an A T END phrase, upon end-of-file the phrase is executed. If you do not code an A T END
phrase, the associated E RROR declarative is executed. Following an A T END condition, the contents of
the associated record area are undefined, and attempts to move data to or from the associated rec ord may
result in a protection exception.
EXCEPTION/ERROR Declarative
You can code one or more ERROR declarative procedures in your program that will be given
control if an input/output error occurs. You can have:
A single, common procedure for the entire program
Group procedures for each file open mode (whether INP UT, OUTPUT, I-O, or E XTE ND)
Individual proc edures for each particular file
INVALID KEY phrases operate for only limited types of errors, whereas the ERROR declarative
encompasses all forms.
2.
INVALID KEY phrases are coded directly onto the input/output verb, whereas ERROR declaratives are
coded separately.
3.
INVALID KEY phrases are specific for one single input/output operation, whereas ERROR declaratives
are more general.
If you specify INVALID KEY in a statement that causes an INVA LID KEY condition, control is transferred
to the INVALID KEY imperative statement. In this case, any ERROR declaratives you have coded are not
executed.
Cobol
EXERCISES
EXERCISES
1. Assume there is a Transaction sequential file with record length 80 characters. The following
are the fields in the transaction file
Emp- no
10 chars
Emp- name
30 chars
Emp-birth-date
8 chars(ddmmyyyy)
Emp-designation
8 chars
Emp-department
6 chars
date-of-joining
8 chars
Emp-status
2 chars
Gross-salary
8 numeric with 2 decimal
The master file is the indexed file with the same fields as above.
This transaction file records needs to be inserted in the master indexed file if the emp- no is not
present and if the emp-status id NA (new active). If the records is present and if the emp-status id
is TT the emp record from the master file needs to be deleted as he is an terminated employee. If
the record is present, and the emp status is OA which is old active, the record in the indexed file
needs to be updated.
Write the COBOL code to do the processing of the transaction and master files. COBOL code
includes environment division, data division and procedure division entries.
Cobol
Table Handling
MONTH-TABLE.
02
MON-1
02
MON-2
02
MON-3
02
MON-4
02
MON-5
02
MON-6
02
MON-7
02
MON-8
02
MON-9
02
MON-10
02
MON-11
02
MON-12
PIC X(9)
PIC X(9)
PIC X(9)
PIC X(9)
PIC X(9)
PIC X(9)
PIC X(9)
PIC X(9)
PIC X(9)
PIC X(9)
PIC X(9)
PIC X(9)
VALUE
VALUE
VALUE
VALUE
VALUE
VALUE
VALUE
VALUE
VALUE
VALUE
VALUE
VALUE
JANUARYbb.
FEBRUARYb .
MARCHbbbb.
APRILbbbb.
MAY bbbbbb.
JUNEbbbbbb.
JULYbbbbbb.
AUGUSTbbb.
SEPTEMBER.
OCTOBERbb.
NOVEMBERb.
DECEMBERb.
In the above example, the same data month name is being repeated 12 times. Instead of defining the
elements like this we can define it as a table with 12 elements. Each element of the table can be referred
using a Subscript or an index. Now lets us look at how the table can be defined in COBOL
01
MONTH-TABLE.
02
MON-NAME PIC X(9) OCCURS 12 TIMES.
This table can be fixed length tables and Variable length tables. The tables or Arrays are define using
OCCURS in COBOL. Now lets look at Occurs clause in detail.
Cobol
Table Handling
OCCURS
Used for defining Tables(A rrays)
The OCCURS clause specifies tables whose elements can be referred to by indexing or
subscripting.
It also eliminates the need for separate entries for repeated data items.
Occurs clause can be specified for element ary or group item.
VALUE clause cannot be specified for associated data name defined with OCCURS clause or any
sub item to the occurs clause
REDEFINES and OCCURS clause cannot appear for the same data item. However RE DEFINES
clause can appear for a group item whos e sub item contains occurs clause
The occurs clause is used to define single dimension and multi-dimensional tables.
Tables can be Fixed Length or Variable Lengt h
Cant be defined for a data item which:
- Has a level number of 01, 66, 77, or 88.
- Describes a redefined data item
Cobol
Table Handling
Example
03 YEAR PIC
9(4)
OCCURS
In the above example the displacement of first element is zero, 2nd is 4, 3rd is 8 and so on. I.e. the
index I1 assumes these values for occurrenc e numbers 1,2,3 and so on.
The value of Index item is set by the occurrence number and not the internal value
The value of index is set using SET clause. The statements like Move or Add cannot be used on
index
Index name is implicitly defined
Index name cannot be associated with any other data hierarchy
Must be initialized before it can be used using SE T and PERFORM VARY ING
PIC
99
P1
PIC
REC-1.
2
02 P2 PIC
XX.
In this example depending on the value of A1, the size of the table may vary from 1 to 90.
The syntax is
Cobol
Table Handling
If subject of OCCURS is defined as E XTE RNA L then ODO ought to be defined as E XTE RNA L
The int-1 and int-2 defined must be positive integers.
The data name-1 can be defined at the same level as ODO but it cannot be defined as sub item to
ODO.
Example
01 REC-1.
02
A1
PIC
99.
02
P1
PIC
XX.
02
P2
PIC
99 OCCURS 1 TO 90 DEPENDING ON A1.
The above example is valid.
01 REC-1.
02
P1
PIC XX.
02
P2
PIC 99 OCCURS 1 TO 90 DEPENDING ON A1.
02
A1
PIC 99.
This definition is invalid
GLOBAL definition needs rules similar to E XTE RNA L
ODO cannot be RE DEFINE D
PIC 99.
PIC XX.
PIC 99
OCCURS 1 TO 90 TIMES DEPENDING ON A1.
REDEFINES P2
Cobol
Table Handling
SET
SET { id-1
index- name-1 } ...
TO
{ id-2
index- name-2
int-1 }
SET
index-name-1 ...
{ UP
BY
{ id-3
DOWN BY }
int-1 }
SET - Examples
05 TABLE-ITEM OCCURS 10
INDEXED BY INX-A
PIC X (8).
To set the index INX-A to 5th occurrence of TABLE-ITEM use stmt:
SET INX-A TO 5
The Value in INX-A would be
(5 - 1) * 8 = 32.
To refer to 6th element we could use relative indexing
- TABLE-ITEM (INX-A+1)
Or Set the index first using
- SET INX-A UP BY 1 and then refer as TABLE-ITEM(INX-A)
Sending flds
Index Name
Index data ite m
Integer data item
Numeric literal
Index Name
V
V*
V
V
Receiving Fields
Index Data Item Integer Data Item
V*
V
V*
-
Cobol
Table Handling
Note : * - No Conversion
COMPLEX TABLES
Data item wit h Occurs Depending On is followed by
- Non-subordinate item
- Non-subordinate item with Occurs Depending On
Data item wit h Occurs Depending On is nested
01
FILLER.
05
CTR1
05
CTR2
05
FIELD-A.
1
10
TABLE-1.
15
REC-1 OCCURS 1 TO 5
DEPENDING ON CTR1
10
EMP-NR
2
10
TABLE-2 OCCURS 5
3
INDEXED BY INDX.
4
15
TABLE-ITEM
PIC S99.
PIC S99.
PIC X(3).
PIC X (5).
PIC 99.
5
15
20
Cobol
Table Handling
Watch out...
The location of non-subordinate items following the item with OCCURS claus e is affected by new
value of the ODO object.
- If you want to preserve the contents of these items, prior to the change in the ODO object, save
all non subordinate items following the variable item and after the change in the ODO object,
restore all the items back.
Cobol
Table Handling
A1
PRICE-1
DATA-REC.
05
PRODUCT-CODE
05
PRICE-REC OCCURS 36
10
PERIOD
10
PROD-PRICE
PIC 99.
PIC S9 (7) V99.
PIC X (6)
TIMES.
PIC X (10).
PIC S9 (7) V99.
Now we want to find the average price of the product for a period.
MOVE ZERO TO TOTAL.
MOVE 1 TO A1.
PERFORM ADD-PRICE-PARA 36 TIMES.
COMPUTE AVERAGE = TOTAL / 36
ADD-PRICE-PARA.
COMPUTE TOTAL = PROD-PRICE (A1) + TOTAL
ADD 1 TO A1.
This is one form of PERFORM statement used for FIXE D length tables.
Now we want to find the price of a product for period 011999 (mmyyyy)
MOVE 1 TO A1
PERFORM FIND-PRICE-PARA UNTIL
(PERIOD = 011999 OR
A1 > 36)
FIND-PRICE-PARA
IF PERIOD = 011999
MOVE PROD-PRICE (A1)
TO PRICE-1
END-IF
ADD 1 TO A1
In this form, the paragraph is executed repetitively until the period id 011999 or until the subscript of the
table is greater than the maximum table limits.
The same fixed length table can be defined as variable length table.
Cobol
Table Handling
In this case again we want to find the price of a product for period 011999(mmyyyy)
77 PRICE-1
PIC S9 (7) V99.
01 DATA-REC.
05 PRODUCT
PIC X(10).
05 TAB-CNT
PIC S9(04) COMP.
05 DATA-TABLE OCCURS 1 TO 37 TIMES
DEPENDING ON TAB-CNT
INDEXED BY INX-1.
07 PERIOD
PIC X(6).
07 PROD-PRICE
PIC S9(7)V9(02).
PROCEDURE DIVISION.
SET INX-1 TO 1.
PERFORM FIND-PRICE-PARA VARYING INX-1 BY 1 UNTIL
INX-1 > TAB-CNT OR
PERIOD = 011999
FIND-PRICE-PARA
IF PERIOD = 011999
MOVE PROD-PRICE(INX-1)
END-IF
TO PRICE-1
In the above statement the increment of the INDE X is not given explicitly.
It is done automatically.
Either fixed length or variable length the table can be in the sorted order by defining a key for the table.
The sorted table reduces the time of search, when a search is performed on the table.
The example for SORTE D TAB LES
02 ASSOC-DATA OCCURS 10
TIMES ASCENDING KEY IS
A-NAME INDEXED BY INX-1.
05 A-NAME
PIC X(20).
05 A-NUM
PIC 9(04).
The data have to be sorted in the correct order (ascending or descending) by the programmer.
Cobol
Table Handling
SEARCH
To search a table element that satisfies a specified condition
Options
- SEARCH VARY ING
Linear Search
- SEARCH ALL
Binary Search, valid only for sorted tables with key specified.
SEARCH - Sequential
SEARCH id-1
[ VARYING { id-2
index- name-1 } ]
[ AT END imperative-statement-1 ]
WHEN condition-1 { imper-stmt2
NEXT SENTENCE }
[ WHEN condition-2 { imper-stmt3
NEXT SENTENCE } ] ...
[ END-SEARCH ]
This search is serial search or linear search.
The table may sorted or not
WHENs are performed one after another for each table entry until TRUE or NO more WHEN cond
AT END executed if no match
Set starting points of id-2 or index. The inc rement of the index or id-2 is taken care of by the
search statement itself.
The search statement can be performed on he table defined by OCCURS and INDE XE D BY
phrase.
The search verb starts with initial value of index and tests whet her condition stated in the when
clause have been satisfied or not. If none of the conditions are satisfied the index is incremented by 1
automatically. The process is continued until the index value exceeds the size of the table and the
search is terminated. When one of conditions is satisfied before the index value reaches the size of the
table, the statements following the WHEN claus e is executed. If these statements are not present,
then execution is transferred to next statement. The value of the index remains set at the point where
the condition has been satisfied.
Cobol
Table Handling
When the SEARCH terminates without finding the necessary value, the index contains
unpredictable values.
Example
77 NAME
PIC X(20).
05 ASSOC-TABLE OCCURS 350 TIMES
INDEXED BY I-1.
10 ASSOC-NAME
PIC X (20).
10 ASSOC-NUM
PIC 9(4).
SET I-1 TO 1.
SEARCH ASSOC-TABLE
AT END
DISPLAY NAME NOT FOUND
WHEN NAME = ASSOC-NAME (I-1)
DISPLAY NAME FOUND.
Cobol
Table Handling
START
If the value of
index
associated
with id-1 is >
size of the
table
YES
Go to
next
executabl
e
statement
NO
Is
condition-1
true?
YES
Execute imperat ive
statement-2
Go to
next
executabl
e
statement
NO
Is
condition2 true?
YES
Execute imperat ive
statement-3
NO
Index associated with
id-1 is incremented by
1
id-2/ index-name-1 is
incremented by 1
Figure 12.1 Flow Chart for SEARCH with Varying and When option
Go to
next
executabl
e
statement
Cobol
Table Handling
SEARCH ALL
SEARCH ALL id-1
[ AT END imperative-statement-1 ]
WHEN { dataname-1= equal-clause
Condition-name-1}
[ AND { dataname-1= equal-clause
Condition-name-1} ] ...
{ imper-stmt2
NEXT SENTENCE }
[ END-SEARCH ]
Equal-clause can be { id-2 lit-1
arithexp-1}
This SEARCH all is the Binary search.
For
this
search
the
table
needs
to
be
in
sorted
order
using
Cobol
Table Handling
77 NAME
PIC X(20).
05 ASSOC-TABLE OCCURS 350 TIMES
ASCENDING KEY IS A-NAME
INDEXED BY I-1.
10 A-NAME
PIC X(20).
10 A-NUM
PIC 9(4).
SEARCH ALL ASSOC-TABLE
AT END
DISPLAY NAME NOT FOUND
WHEN NAME = A-NAME(I-1)
DISPLAY NAME FOUND
Cobol
Table Handling
MERGE
Combines two or more identically sorted files and makes records available
in merged order
MERGE file-1 { ON
{ASCENDING
DESCENDING} KEY id-1... } ...
[COLLATING SEQUENCE IS alphabet-name-1]
USING file-2 [file-3 ...]
{GIVING file-4
OUTPUT PROCEDURE IS
proc-nm-1 [THRU proc-nm-2]}
MERGE - Examples
MERGE sorted-emp-ph- file
ASCENDING s- last-nm
s-first- nm
DESCENDING s-emp-nbr
USING emp-ph-file
emp-addon-ph- file
GIVING new-emp-ph- file
MERGE - Rules
When US ING / GIVING option is specified the input / output file(s) to merge
must not be open
The key used in the ME RGE statement cannot be variably located.
When the file referenced by filename-1 is merged control passes to first
stmt in the OUTP UT PROCE DURE.
Collating Sequences
-
Default is EBCDIC
Cobol
Exercises
EXERCISES
1.
2. How many times will the procedure named PROCESS-ROUTINE be executed by the
following PERFORM statements?
a. PERFORM PROCESS-ROUTINE VARYING A FROM 1 BY 1 UNTIL A = 15.
b. PERFORM PROCESS-ROUTINE VARYING A FROM 1 BY 1 UNITL A > 15.
3. The following are DATA DIVISION entries.
77
I
PIC 99.
77
TOTAL
PIC 99.
1
TABLE-1.
02
FILLER
PIC
X (9) VALUE
IS
123456789.
01
TABLE-2
REDEFINES TABLE-1.
02
A
OCCURS
9
TIMES
PIC 9.
Indicate how many elements of the array A would be added to TOTAL and what will be the final
value of TOTAL when the control goes to PARA-2 in the following program segment?
MOVE ZERO TO TOTAL.
PERFORM PARA-1 VARYING I FROM 1 BY 2 UNTIL I > 9.
GO TO PARA-2
PARA-1.
ADD A (I) TO TOTAL.
PARA-2.
4. A table contains the monthly sales data for 12 months of the year and for the 4 sales zones
where each zone has 8 districts. Write the PROCEDURE DIVISION statements to find the
total sale of each district within each zone and then find the total sale of each zone. Store these
totals in 2 tables - one district total and the other containing the zone totals. Write the Data
division entries to define all these tables.
5. The following is a PROCEDURE DIVISION statement.
PERFORM PARA-AGAIN VARYING I FROM 1 BY 1 UNTIL I > 4
AFTER J FROM 0 BY 1 UNTIL J < -2
AFTER K FROM 1 BY 2 UNTIL K > 8.
How many times is the procedure named PARA-AGAIN executed?
Which data name varied least rapidly and which varied most rapidly.
Cobol
Exercises
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 re-coding them. These entries and proc edures 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, logic ally replacing the entire COPY
statement, beginning with the word COPY and ending with the period, inclusive.
When the REP LACING 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.
A COPY statement can appear in the source program anywhere a character string
or a separat or can appear.
COPY { text-name
lit-1 }
[ { OF
{ lib-name
IN }
lit-2 } ]
[ SUPPRESS ] [ REPLACING
( op-1 BY op-2 ) ... ] .
op-1 and op-2 can be either pseudo-text, an identifier, a literal, or a
COBOL word
(except COPY).
Compile r Directive
COPY Example
01 :TAG:.
02 :TAG:-WEEK
PIC S99.
02 :TAG:- GROSS-PAY PIC 9(5)V99.
02 :TAG:- HOURS
PIC S999
OCCURS 1 TO 52 TIMES DEPENDING ON :TAG:-WEEK OF :TAG:.
COPY PAYLIB REPLACING ==:TAG:== BY ==Payroll==.
Cobol
Co mpiler Directives
01 PAYROLL.
02 PAYROLL-WEEK
PIC S99.
02 PAYROLL-GROSS-PAY PIC S9(5)V99.
02 PAYROLL-HOURS
PIC S999
OCCURS 1 TO 52 TIMES
DEPENDING ON PAYROLL-WEEK OF PAYROLL.
Compile r Directive
COPY - Rules
Copy statement can be nested but
- Cant contain REPLA CING option
Should not cause recursion
If S UPPRESS
- Specified then listing will not contain the statement within the COPY member
- If not then listing will contain the statements with a C after the source program
line number
Cobol
Co mp iler Options
NRI-IT
Cobol
Co mp iler Options
Reserved word list
- WORD
Processing of COPY ETC..
- LIB
Provision of User Exit
- E XIT
ADV / NOADV
Default is: ADV
ADV has meaning only if you use WRITE . . . ADVANCING in your source code.
With ADV in effect, the compiler adds 1 byte to the record length to account for the printer control
character. Use NOA DV if you have already adjusted your record length to include 1 byte for the printer
control character
CMPR2 / NOCMPR2
Default is: NOCMP R2
Use CMPR2 when you want the compiler to generate code that is compatible wit h code generated by
VS COBOL II Release 2.
COBOL II Release 2 will also compile successfully under IB M COBOL for MVS & VM wit h CMPR2 in
effect and will provide compatible results.
COMP ILE / NOCOMP ILE (W/E/S)
Default is: NOCOMP ILE(S )
Abbreviations are: C / NOC
Use the COMPILE option only if you want to force full compilation even in the presence of serious
errors. All diagnostics and object code will be generated. Do not try to run the object code generated
if the compilation resulted in serious errors--the results could be unpredictable or an abnormal
termination could occur.
DA TA(24/31)
Default is: DATA(31)
Language E nvironment provides services that control the storage used at run time. IBM COBOL for
MVS & VM uses these servic es for all storage requests.
For reent rant programs, the DA TA (24|31) compiler option and the HEAP run-time option control
whet her storage for dynamic data areas (such as WORKING-S TORAGE section and FD record areas)
is obtained from below the 16-megabyte line or from unrestricted storage.
NRI-IT
Cobol
Co mp iler Options
When you specify the run-time option HEAP (BE LOW), the DA TA (24|31) compiler option has no
effect; the storage for all dynamic data areas is allocated from below the 16-megabyte line. However,
with HEAP (A NYWHERE ) as the run-time option, storage for dynamic data areas is allocated from
below the line if you compiled the program wit h the DA TA (24) compiler option or from unrestricted
storage if you compiled with the DA TA (31) compiler option.
Specify the DA TA (24) compiler option for programs running in 31-bit addressing mode that is passing
data parameters to programs in 24-bit addressing mode. This ensures that the data will be
addressable by the called program.- With NORE NT compiler option, DA TA (31) has no effect
DECK / NODECK
Default is: NODECK
Abbreviations are: D / NOD
Use DE CK to produce object code in the form of 80-column card images. If you use the DECK option,
be certain that SYSPUNCH is defined in your JCL for compilation.
- SYSPUNCH ddname must for DE CK opt
DYNAM / NODY NAM Default
is: NODYNAM Abbreviations are:
DYN / NODY N
Use DY NAM to cause separately compiled programs invoked through the CALL literal statement to be
loaded dynamically at run time. DY NAM causes dynamic loads (for CALL) and deletes (for CA NCE L)
of separately compiled programs at object time. Any CALL identifier statements that cannot be
resolved in your program are also handled as dynamic calls.
- DYNAM forced RES IDE NT option
NRI-IT
Cobol
Co mp iler Options
FLAG(x,y) / NOFLA G
NRI-IT
Cobol
Co mp iler Options
MAP / NOMAP
NRI-IT
Cobol
Co mp iler Options
NUMP ROC(PFD or NOP FD or MIG)
NRI-IT
Cobol
Co mp iler Options
OPTIMIZE / NOOP TIMIZE
The COBOL optimizer is activated when you use the OP TIMIZE compiler option. The purpose of the
OPTIMIZE compiler option is to do the following:
Eliminate unnecessary transfers of control or simplify inefficient branches, including thos e generated
by the compiler that are not evident from looking at the source program.
Simplify the compiled code for both a PERFORM statement and a CALL statement to a contained
(nested) program. Where possible, the optimizer places the statement inline, eliminating the need for
linkage code.
This optimization, known as procedure integration, is further discussed in "PERFORM Procedure
Integration" If procedure integration cannot be done, the optimizer uses the simplest linkage possible
(perhaps as few as two instructions) to get to and from the called program.
Eliminate duplicate computations (such as subscript computations and repeated statements) that have
no effect on the results of the program.
Eliminate constant computations by performing them when the program is compiled.
Eliminate constant conditional expressions.
Aggregate moves of contiguous items (such as those that often occur with the use of MOVE
CORRESP ONDING) into a single move. Both the source and target must be contiguous for the
moves to be aggregated.
Delete from the program, and identify with a warning message, code that can never be performed
(unreachable code elimination).
The FULL suboption requests that the compilers discard any unreferenced data items from the DA TA
DIV IS ION, and suppress generation of code to initialize these data items to their VALUE clauses.
For unit testing your programs, you might find it easier to debug code that has not been optimized. But
when the program is ready for final test, specify OPTIMIZE, so that the tested code and the production
code are identical. You might also want to use the option during development, if a program is used
frequently without recompilation. However, the overhead for OP TIMIZE might outweigh its benefits if
you re-c ompile frequently, unless you are using the assembler language expansion (LIS T option) to
fine tune your program.
OPTIMIZE & TES T - mutually exclusive
OUTDD(ddname)
- To get run-time DISP LAY output on a data set other than SYSOUT
NRI-IT
Cobol
Co mp iler Options
QUOTE / APOS T Default
NRI-IT
Cobol
Co mp iler Options
Hook: - The hook-loc ation suboption controls where compiled-in hooks will be generated to provide
information to the debugger.
NONE: - No hooks will be generated.
BLOCK: - Hooks will be generated at all program entry and exit points.
PATH: - Hooks will be generated at all program entry and exit points and at all path points. A
path point is anywhere in a program where the logic flow is not necessarily sequential or can change.
Some examples of path points are IF-THE N-E LSE constructs, PERFORM loops, ON S IZE ERROR
phrases, and CALL statements.
STMT: - Hooks will be generated at every statement and label, as well as at all program entry
and exit point. In addition, if the DA TEPROC option is in effect, hooks will be generat ed at all date
processing statements.
ALL: - Hooks will be generated at all statements, all path points, and at all program entry and
exit points. In addition, if the DA TEPROC option is in effect, hooks will be generated at all date
processing statements.
Symbol: - The symbol-table suboption controls whether dictionary tables will be generated.
SYM: - Dictionary and calculation tables will be generated.
NOSYM: - Dictionary and calculation tables will not be generat ed.
SSRANGE / NOSS RA NGE
Default is: NOSSRANGE
Abbreviations are: SSR / NOSSR
Use SSRA NGE to generate code that checks if subscripts (including ALL subscripts) or indexes try to
reference an area outside the region of the table. Each subscript or index is not individually checked
for validity; rather, the effective address is checked to ensure that it does not cause a reference
outside the region of the table. Variable-length items will also be checked to ensure that the reference
is within their maximum defined length.
Reference modification expressions will be checked to ensure that:
The reference modification starting position is greater than or equal to 1.
The reference modification starting position is not greater than the current length of the
subject data item.
The reference modification length value (if specified) is greater than or equal to 1.
The reference modification starting position and length value (if specified) do not reference
an area beyond the end of the subject data item.
- Use it while testing
NRI-IT
Cobol
Co mp iler Options
TRUNC (OP T or S TD or BIN)
Use TRUNC(S TD) to cont rol the way arithmetic fields are truncated during MOVE
and arithmetic operations. TRUNC (S TD) applies only to USAGE BINA RY receiving fields in MOVE
statements and arithmetic expressions. When TRUNC (S TD) is in effect, the final result of an
arithmetic expression, or the sending field in the MOVE statement, is truncated to the number of digits
in the PICTURE clause of the B INA RY receiving field.
TRUNC (OP T): - TRUNC (OP T) is a performance option. When TRUNC (OP T) is specified, the
compiler assumes that the data conforms to PICTURE and USAGE specifications of the USAGE
BINA RY receiving fields in MOVE statements and arithmetic expressions. The results are
manipulated in the most optimal way, either truncating to the number of digits in the PICTURE claus e,
or to the size of the binary field in storage (halfword, fullword, or doubleword).
TRUNC (B IN) :-
The TRUNC(BIN) option applies to all COB OL language that processes USAGE
NRI-IT
Cobol
Co mp iler Options
WORD(xxxx) / NOWORD
Default is: NOWORD
Abbreviations are: WD / NOWD
xxxx :- Are the ending characters of the name of the reserved word table (IGY Cxxxx) to be used in
your compilation. IGY C are the first 4 standard characters of the name, and xxxx can be 1 to 4
characters in length.
Use WORD(xxxx) to specify that an alternate reserved word table is to be used during compilation.
Alternate reserved word tables provide changes to the IBM-supplied default reserved word table.
XREF(FULL or S HORT) / NOXREF
Default is: NOXRE F
Abbreviations are: X / NOX
You can choose XREF, XREF (FULL), or XREF (S HORT).
Use XREF to get a sort ed cross-reference listing. EBCDIC data-names and procedure-names are
listed in alphanumeric order. DBCS data-names and proc edure-names are listed based on their
physical order in the program, and appear before the EB CDIC data-names and procedure-names,
unless the DB CS XREF installation option is selected wit h a DB CS ordering program. In this case,
DBCS data-names and procedure-names are ordered as specified by the DBCS ordering program.
Also included is a section listing all the program names that are referenced in your program, and the
line number where they are defined. External program names are identified as such.
If you use XREF and SOURCE, cross-reference information will also be printed on the same line as
the original source in the listing. Line number references or other information, will appear on the right
hand side of the listing page. On the right of source lines that reference intrinsic functions, the letters
'IFN' will appear with the line numbers of the location where the function's arguments are defined.
Information included in the embedded references lets you know if an identifier is undefined or defined
more than once. (UND or DUP will be printed); if an item is implicitly defined (IMP), such as special
registers or figurative constants; and if a program name is external (E XT).
If you use XREF and NOSOURCE, you'll get only the sorted cross-reference listing.
XREF (SHORT) will print only the explicitly referenced variables in the cross-reference listing. XREF
(SHORT) applies to DBCS data names and procedure-names as well as EBCDIC names.
NOXREF suppresses this listing.
NRI-IT
Cobol
Co mp iler Options
ZWB / NOZWB
NRI-IT
Cobol
APPENDIX 1
APPENDIX 1
FILE STATUS CODES AND MEANING
2 char code
- Status key 1
- Status key 2
Status key 1 tells the type of error
Status key 2 gives the detail
Status key 1
0 - Successful Completion
1 - At end condition
2 - Invalid key condition
3 - Permanent error condition
4 - Logic error
9 - Implementor defined (VSAM)
Successful Completion-0
0 - No further info
1 - Duplicate - Read, (Re) Write
2 - Length error for Fixed files
5 - Optional file not present
At end condition-1
0 - End of file
4 - Relative key > max possible
Invalid Key-2
1 - Ascending key violation/Rewrite change primary Key
2 - Duplicate key when not allowed (Primary, Alternate or relative key)
3 - Record not found
4 - Write beyond boundary
Permanent error-3
0 - no further info
4 - Due to boundary violation
5 - File not available (ddname not found/defined)
7 - Invalid open mode on open
8 - Open of file closed with lock
9 - DCB conflict during open
Logic error-4
NRI-IT
Cobol
APPENDIX 1
NRI-IT
Cobol
References
References
1.
2.
3.
4.
- Nancy stern
- Philippakis and Kazmier
- Roy & Dastidar
- Paul N.
- Anne prince