0% found this document useful (0 votes)
853 views224 pages

Cobol

Cobol is a programming language that was developed in 1959 and saw increasing usage from the 1960s onward. It has undergone several revisions and standards including COBOL-68, COBOL-74, and COBOL-2002 which added object orientation. Cobol programs use four main divisions - identification, environment, data, and procedure - to define the program, its environment, data, and processing logic in a structured manner using sections, paragraphs, sentences and statements.

Uploaded by

rahulravi007
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
853 views224 pages

Cobol

Cobol is a programming language that was developed in 1959 and saw increasing usage from the 1960s onward. It has undergone several revisions and standards including COBOL-68, COBOL-74, and COBOL-2002 which added object orientation. Cobol programs use four main divisions - identification, environment, data, and procedure - to define the program, its environment, data, and processing logic in a structured manner using sections, paragraphs, sentences and statements.

Uploaded by

rahulravi007
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 224

COBOL

Dec 7, 2021 1
Introduction

Dec 7, 2021 2
The history of COBOL in a bird's-
eye view:
• 1959  The American Department of Defense (DOD) asked a
group of specialists to develop a business language that met
their demands. 
• 1960  First proposal for COBOL - COmmon Business Oriented
Language -, named COBOL-60. 
• 1961  First COBOL compilers are getting used. 
• 1965  From this year the usage of COBOL starts to increase a
lot.
• 1968  The American National Standards Institute (ANSI) sets
the first official COBOL standard: COBOL-68. 
• 1970  The International Organization for Standardization (ISO)
makes ANSI's COBOL-68 an international standard. 
• 1974  The new COBOL-74 standard is set.
• 1985  The new COBOL-85 standard is set.
• 1989  Intrinsic functions are added to the standard. 
• 2002  The long awaited object oriented COBOL 2002 standard
is set.  

Dec 7, 2021 3
COBOL
• US defense department took the initiative for
developing a high level computer language in 1958.

• CODASYL (Conference On Data System Language)


was formed. CODASYL recommended the design and
structure of Cobol which has been accepted by all
computer vendors.

• First cobol compiler was released in 1962.

• Since then cobol has been continuously revised and


updated incorporating new facilities and features.

• IBM announced their latest release of Cobol in 2000


which is known as IBM Cobol or Cobol for MVS. It
supports object oriented concept.
Dec 7, 2021 5
Cobol Structure

Program

Divisions

Section(s)

Paragraph(s)

Sentence(s)

Statement(s)
Dec 7, 2021 6
Sections

• A section is a block of code made up of one or


more paragraphs.

• A section begins with the section name and ends


where the next section name is encountered or
where the program text ends.

• A section name consists of a name devised by the


programmer or defined by the language followed
by the word SECTION followed by a full stop.

– FILE SECTION.
– SelectRecords SECTION.

Dec 7, 2021 7
Paragraphs
• Each section consists of one or more paragraphs.

• A paragraph is a block of code made up of one or


more sentences.

• A paragraph begins with the paragraph name and


ends with the next paragraph or section name or the
end of the program text.

• The paragraph name consists of a name devised by


the programmer or defined by the language followed
by a full stop.
– PrintFinalTotals.
– PROGRAM-ID.
Dec 7, 2021 8
Sentences and Statements
• A paragraph consists of one or more sentences.
• A sentence consists of one or more statements and
is terminated by a full stop.
– MOVE 0.21 TO VatRate
COMPUTE VatAmount = ProductCost * VatRate.
– DISPLAY "Enter name " WITH NO ADVANCING
ACCEPT StudentName
DISPLAY "Name entered was " StudentName.
• A statement consists of a COBOL verb and an
operand or operands.
– SUBTRACT Tax FROM GrossPay GIVING NetPay
– READ StudentFile
AT END SET EndOfFile TO TRUE
END-READ
Dec 7, 2021 9
A Full COBOL program
IDENTIFICATION DIVISION.
PROGRAM-ID. MYProgram.
AUTHOR. Globsyn.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Num1 PIC 9 VALUE ZEROS.
01 Num2 PIC 9 VALUE ZEROS.
01 Result PIC 99 VALUE ZEROS.
PROCEDURE DIVISION.
CalculateResult.
ACCEPT Num1.
ACCEPT Num2.
MULTIPLY Num1 BY Num2 GIVING Result.
DISPLAY "Result is = ", Result.
STOP RUN.
Dec 7, 2021 10
The Four Divisions
DIVISIONS are used to identify the principal
components of the program text. There are four
DIVISIONS in all.

IDENTIFICATION DIVISION.
ENVIRONMENT DIVISION.
DATA DIVISION.
PROCEDURE DIVISION.

Although some of the divisions may be omitted


the sequence in which the DIVISIONS are specified is
fixed and must follow the pattern shown above.
Dec 7, 2021 11
Functions of the four divisions.
• The IDENTIFICATION DIVISION is used to supply
information about the program to the programmer and
to the compiler.
• The ENVIRONMENT DIVISION describes to the compiler
the environment in which the program will run.
• As the name suggests, the DATA DIVISION is used to
provide the descriptions of most of the data to be
processed by the program.
• The PROCEDURE DIVISION contains the description of
the algorithm which will manipulate the data previously
described. Like other languages COBOL provides a
means for specifying sequence, selection and iteration
constructs.
Dec 7, 2021 12
IDENTIFICATION DIVISION.
• The purpose of the IDENTIFICATION DIVISION is to
provide information about the program to the
programmer and to the compiler.
• Most of the entries in the IDENTIFICATION
DIVISION are directed at the programmer and are
treated by the compiler as comments.
• An exception to this is the PROGRAM-ID clause.
Every COBOL program must have a PROGRAM-ID.
It is used to enable the compiler to identify the
program.
• There are several other informational paragraphs in
the IDENTIFICATION DIVISION but we will ignore
them for the moment.
Dec 7, 2021 13
The IDENTIFICATION DIVISION Syntax

• The IDENTIFICATION DIVISION has the


following structure
IDENTIFICATION DIVISION.

PROGRAM-ID. NameOfProgram.

[AUTHOR. YourName.]
[DATE-WRITTEN. ……….]
[DATE-COMPILED. ……..]

Dec 7, 2021 14
The IDENTIFICATION DIVISION Syntax
• Only first two lines are mandatory
IDENTIFICATION DIVISION.
PROGRAM-ID. NameOfProgram.
[AUTHOR. YourName.]

The keywords IDENTIFICATION DIVISION represent


the division header and signal the commencement of
the program text.

• The paragraph name PROGRAM-ID is a keyword. It


must be specified immediately after the division
header.
• The program name can be up to 30 characters long.
Allowed characters are Alphabetic (at least one), digit
and hyphen (not to as a start or end character)
Dec 7, 2021 15
Environment Division
• The ENVIRONMENT DIVISION describes to the
compiler the environment in which the program will
run. Syntax:
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
SOURCE-COMPUTER. Computer-name [ [WITH] DEBUGGING MODE].
WITH DEBUGGING MODE, activates a compile-time switch for
debugging lines (D in col.7) to be recognized. Otherwise such lines
will be treated as comment lines.
Except WITH DEBUGGING MODE, this paragraph is syntax checked.
OBJECT-COMPUTER. Computer-name. (e.g., IBM-390)
SPECIAL-NAMES. Environment-name [ IS ] user-defined-name.
(e.g., CONSOLE IS myinput, SYSIN IS mydata etc.
Dec 7, 2021 16
Environment Division
INPUT-OTPUT SECTION.
FILE-CONTROL .
SELECT file-name (1) ASSIGN [ TO ] assignment-name (2)
[ RESERVE n [AREA(S)] ]
[ ORGANIZATION [IS] SEQUENTIAL/INDEXED/RELATIVE (3) ]
[ key description ]
[ ACCESS [MODE] [IS] SEQUENTIAL/RANDOM/DYNAMIC ]
[ FILE STATUS IS data-name ].
(1) file-name is the name by which the file will be referred to within
the source program.
(2) user defined name by which the file be physically assigned runtime
by the JCL.
//assignment-name DD DSNAME= physical-file-name,…, (3)
(2) DCB=(…DSORG=PS)
RESERVE : no. of file/block buffers for I-O. If omitted, no. of
buffers
Dec 7, 2021
is taken from JCL. If JCL does not specify then the 17
installation default is taken.
Environment Division
The default for ORGANIZATION and ACCESS is
Sequential.
Key description required only if the file organization is:
indexed – RECORD [KEY] [IS] data-name1
[ALTERNATE RECORD [KEY] [IS] data-name2
[ WITH DUPLICATES] ]
relative – RELATIVE [KEY] [IS] data-name3
data-name1 & data-name2 will be defined while describing the
record format. Data-name3 must be defined by the programmer.

File status is an user-defined 2-character alphanumeric data


field. 1st character is called status-key1 and the other status-
key2. After each I-o operation, the OS returns a value in the file
status field which indicates success of the operation.
0 0 : successful operation
1 * : AT END condition
3 * : Invalid key condition
other-value : I-O error
Dec 7, 2021 18
Environment Division

I-O-CONTROL.
[ RERUN ON file-name [ EVERY ] [ integer
RECORDS] or [END OF REEL] ]
[ SAME AREA [ FOR ] file-name1 [file-name2…..] ]
[ SAME RECORD AREA [ FOR ] file-name1 [file-

name2…..] ]

RERUN for check pointing / restart


SAME AREA – same file buffer
SAME RECORD AREA – same record buffer
Dec 7, 2021 19
The DATA DIVISION
• The DATA DIVISION is used to describe most of the
data that a program processes.

• The DATA DIVISION is divided into two main


sections:
– FILE SECTION.
– WORKING-STORAGE SECTION.

• The FILE SECTION is used to describe most of the


data that is sent to, or comes from the computer’s
peripherals. All files are to be declared here.

• The WORKING-STORAGE SECTION is used to


describe the general variables used in the program.
Dec 7, 2021 20
DATA DIVISION Syntax
DATA DIVISION.
FILE SECTION.
file-description & record description entries

WORKING-STORAGE SECTION.
entries to describe data/variables used by
the program. These are not part of any file(s).

LINKAGE SECTION.
describes data made available from another
program. Inter program communication.

Dec 7, 2021 21
DATA DIVISION
DATA DIVISION.
FILE SECTION.
FD file-name 1
[ BLOCK [CONTAINS] int-1 [TO int-2] [CHARACTERS or RECORDS] ] 2
[ RECORD [ CONTAINS ] int-3 [ TO int-4 ] CHARACTERS ] 3
[ LABEL [RECORDS ARE] [RECORD IS] [STANDARD] [OMITTED] ] 4
[ VALUE OF ID [ IS ] data-name ] 5
[ RECORDING [ MODE ] [ IS ] [ F or V ]. 6

FD -> File Description.


BLOCK specifies the block (physical record) size.
LABEL ignored for DASD files. Useful for processing alien tapes.
VALUE clause is treated as comments.
RECORDING specifies format of physical records – fixed, variable etc.
– ignored for VSAM files
Dec 7, 2021 22
DATA DIVISION

FD entry will be immediately followed by record


description.
FD MyFile
BLOCK CONTAINS 2048 CHARACTERS.
01 MyRec PIC X(80).
01 YourRec.
05 Name PIC X(40).
05 DOB PIC X(06).
05 Address PIC X(40).
…….. (explain record types/length
…….. implicit redefines etc.)

Dec 7, 2021 23
DATA DIVISION
WORKING-STORAGE SECTION.
entries to describe data/variables used by
the program. These are not part of any file(s).
Level-number data-name [ PIC clause] [ REDEFINES-clause]
[ BLANK WHEN ZERO clause] [ JUSTIFIED clause] [ OCCURS
clause] [ sign clause] [ Synchronized clause] [ USAGE clause]
[ VALUE clause]
level-number : 01 and 77 must begin in Area A.
02 – 49 can begin in area A or B.
88 can begin in area A or B, but must be associated
with (preceding) an elementary or group item and
must be followed by VALUE clause.
Dec 7, 2021 24
DATA DIVISION
05 Month PIC 99.
88 ValidMM VALUE 01 THRU 12.
05 DD PIC 99.
88 ValidDD VALUE 28, 29, 30 31.
VALUE can be a single value or a range of
values or a combination of both.
Each 88-level entry implicitly has the picture
characteristics of the conditional variable.
Associated with one variable, you can have as
many 88 level entries as you require.

Data-name – already discussed.


Explain FILLER.
Dec 7, 2021 25
DATA DIVISION
data-description-entry-clauses are:
• ( [ redefines-clause ]
• || [ blank-when-zero-clause ]
• || [ external-clause ]
• || [ global-clause ]
• || [ justified-clause ]
• || [ occurs-clause ]
• || [ picture-clause ]
• || [ sign-clause ]
• || [ synchronized-clause ]
• || [ usage-clause ]
Dec 7, 2021 26
• || [ data-value-clause ] )
DATA DIVISION
redefines-clause=
• "REDEFINES" data-name

blank-when-zero-clause=
• "BLANK" [ "WHEN" ] ( "ZERO" | "ZEROS" | "ZEROES" )

justified-clause=
• ( "JUSTIFIED" | "JUST" ) [ "RIGHT" ]

occurs-clause=
• "OCCURS" integer [ "TIMES" ]
[ "INDEXED" [ "BY" ] { index-name }+ ]
occurs-clause=
• "OCCURS" [ ( integer | zero ) "TO" ] integer [ "TIMES" ] 
"DEPENDING“ [ "ON" ] qualified-data-name
[ "INDEXED" [ "BY" ] { index-name }+ ]
Dec 7, 2021 27
DATA DIVISION
picture-clause=
• ( "PICTURE" | "PIC" ) [ "IS" ] picture-string
sign-clause=
• [ "SIGN" ["IS"]] ("LEADING"|"TRAILING") ["SEPARATE" ["CHARACTER"]]
synchronized-clause=
• ( "SYNCHRONIZED" | "SYNC" ) [ ( "LEFT" | "RIGHT" ) ]
usage-clause=
• ["USAGE" [ "IS"]] ("BINARY"| "COMP"| "COMP-1”|”COMP-2”|COMP-3”
 |"COMPUTATIONAL" | "COMPUTATIONAL-1/-2/-3”
|"DISPLAY" | "INDEX" | "PACKED-DECIMAL"  )
condition-value-clause=
• ("VALUE" ["IS"] | "VALUES" ["ARE"] ) { literal [ ("THROUGH" | "THRU“)
 literal ] }
data-value-clause= "VALUE" [ "IS" ] literal
Dec 7, 2021 28
DATA DIVISION

REDEFINES-clause
05 DAT1 …….
05 DAT2 REDEFINES DAT1.
DAT1 redefined item and DAT2 is redefining item.
Level nos. of DAT1 and DAT2 must be identical and
must not be 66 or 88. You can redefine as many times
as you require.
Explicit and Implicit redefinition.

Dec 7, 2021 29
DATA DIVISION
BLANK WHEN ZERO(es) can be specified only for
numeric-edited items with USAGE DISPLAY.

JUSTIFIED [or, JUST] [RIGHT]


Can be used with only Alphabetic and Alphanumeric
field.

OCCURS clause cannot be used with 01, 66, 77 and


88 levels.

OCCURS DEPENDING ON.

Dec 7, 2021 30
DATA DIVISION
SIGN [ IS] [ LEADING or TRAILING] [ SEPARATE]
can be specified only for signed numeric data (i.e., having
“S” in the PIC). Default is Trailing.
If SEPARATE is specified, it occupies 1 character.
PIC 99 – 2 characters
PIC S99 – 2 characters
PIC S99 SIGN SEPARATE – 3 characters

SYNCHRONIZED [ or, SYNC] [RIGHT or LEFT]


Binary Numeric items can be synchronized at half-word or
full word boundary introducing slack bytes if required.
Non-numeric items can be synchronized either at the
LEFTDec
(default)
7, 2021 or RIGHT. 31
DATA DIVISION

LINKAGE SECTION.
The data made available from another
program (Inter program communication)
are described under Linkage Section.
You cannot specify VALUE Clause for items
other than level-88 items in this section.

Dec 7, 2021 32
COBOL Program Text Structure

IDENTIFICATION DIVISION.
Program Details
ENVIRONMENT DIVISION. NNOTE
OTE
The
Thekeyword
Environment in which the keyword
DIVISION
DIVISIONand andaa
program is compiled & executed ‘full-stop’
‘full-stop’isis
used
usedininevery
every
DATA DIVISION. case.
case.
Data Descriptions
PROCEDURE DIVISION.
Program instructions
Dec 7, 2021 33
Example
IDENTIFICATION DIVISION.
PROGRAM-ID. MyProgram.
AUTHOR. Globsyn.

ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
SOURCE-COMPUTER. IBM-390.

DATA DIVISION.
WORKING-STORAGE SECTION.
01 Num1 PIC 9 VALUE ZEROS.
01 Num2 PIC 9 VALUE ZEROS.

PROCEDURE DIVISION.
PARA-1.
MOVE 5 TO NUM1.
STOP RUN.
Dec 7, 2021 34
COBOL coding rules
• Almost all COBOL compilers treat a line of COBOL code
as if it contained two distinct areas. These are known
as;
Area A and Area B
• When a COBOL compiler recognizes these two areas, all
division, section, paragraph names, FD entries and 01
level numbers must start in Area A. All other sentences
must start in Area B.

• Area A is four characters wide and is followed by Area B.

IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID. ProgramFragment.
PROGRAM-ID. ProgramFragment.
** This
This is
is aa comment.
comment. It
It starts
starts
** with
with an asterisk in column 11
an asterisk in column
Dec 7, 2021 35
COBOL coding rules
Sequence Area A Area B Pgmr-id
1 2 3 4 5 6 7 8 9 10 11 12 13…………….72 73…80
Indicator area
Sequence area – Serial number of source lines
Indicator area – continuation line (hyphen)
– comment line ( * or / )
– debugging line ( D or d )
Area A – all division, section, paragraph names,

FD entries and 01 level numbers must


start in Area A.
Area B – All other sentences must start in Area B.
Blank lines and comment lines may appear
anywhere,
Dec 7, 2021 as many times as required. 36
Describing DATA.
• Bits
• Binary
• Hex
• ASCII / EBCDIC
• Bytes (characters) – DBCS (double byte ch. string)
• Word
• Half-word
• Double-word
• While coding in mainframe, you can use
either lower-case or upper-case (recommended).
But case does play an important role while
determining the content
Dec 7, 2021 37
Describing DATA.

• Characters in VS Cobol II
A-Z, a-z, 0-9 and special characters like < .
( + space $ * ) ; - / , > : ‘ = “

• Non-numeric content may contain 256


characters (2**8) e.g., x’00’ to x’FF’

• Displayable and non-displayable characters

Dec 7, 2021 38
Describing DATA.

There are basically three kinds of data used in COBOL


programs;

ŒVariables.

Literals.
ŽFigurative Constants.

Dec 7, 2021 39
Data-Names / Variables

• A variable is a named location in memory into


which a program can put data and from which it
can retrieve data.

• A data-name or identifier is the name used to


identify the area of memory reserved for the
variable.

• Variables must be described in terms of their


type and size.

• Every variable used in a COBOL program must


have a description in the DATA DIVISION.

Dec 7, 2021 40
Name Construction
• All user defined names, such as data names, paragraph
names, section names and mnemonic names, must
adhere to the following rules;
– They must contain at least one character and not
more than 30 characters.
– They must contain at least one alphabetic character
and they must not begin or end with a hyphen.
– They must be contructed from the characters A to
Z, a-z, the number 0 to 9 and the hyphen.
e.g. TotalPay, Gross-Pay, PrintReportHeadings,
Customer10-Rec
• All data-names should describe the data they contain.
• All paragraph and section names should describe the
function of the paragraph or section.
Dec 7, 2021 41
COBOL Literals

• String/Alphanumeric literals are enclosed in quotes


and may consists of alphanumeric characters
e.g. "Michael Ryan", "-123", "123.45“

• Numeric literals may consist of numerals, the decimal


point and the plus or minus sign. Numeric literals are
not enclosed in quotes.
e.g. 123, 123.45, -256, +2987

Dec 7, 2021 42
Figurative Constants
• COBOL provides its own, special constants called
Figurative Constants. It does not depend on the
length of the associated operands

SPACE
SPACEor
orSPACES
SPACES == ¨¨
ZERO
ZEROor
orZEROS
ZEROSor
orZEROS
ZEROS == 00
QUOTE
QUOTEor
orQUOTES
QUOTES == ""
HIGH-VALUE
HIGH-VALUEor
orHIGH-VALUES
HIGH-VALUES == Max
MaxValue
Value
LOW-VALUE
LOW-VALUEor orLOW-VALUES
LOW-VALUES == Min
MinValue
Value
ALLliteral
ALL literal == Fill
FillWith
WithLiteral
Literal

Dec 7, 2021 43
Figurative Constants - Examples
Figurative Constants - Examples
01
01 GrossPay
GrossPay PIC
PIC 9(5)V99
9(5)V99 VALUE
VALUE 13.5
13.5..
ZERO
ZEROS
MOVEZEROES TO GrossPay.
MOVE TO GrossPay.

GrossPay

0 0 0 1 3 5 0

01
01 StudentName
StudentName PIC
PIC X(10)
X(10) VALUE
VALUE "MIKE".
"MIKE".

MOVE
MOVE ALL
ALL "-"
"-" TO StudentName.
TOStudentName
StudentName.
M I K E 
Dec 7, 2021 44
Figurative Constants - Examples
Figurative Constants - Examples
01
01 GrossPay
GrossPay PIC
PIC 9(5)V99
9(5)V99 VALUE
VALUE 13.5.
13.5.
ZERO
ZEROS
ZEROES
MOVE
MOVE TO
TO GrossPay.
GrossPay.
GrossPay

0 0 0 0 0 .0
01
01 StudentName0 PIC
StudentName PIC X(10)
X(10) VALUE
VALUE "MIKE".
"MIKE".

MOVE
MOVE ALL
ALL "-"
"-" TO
TO StudentName.
StudentName.
StudentName
- - - - - - - - - -
Dec 7, 2021 45
COBOL Data Types

• Alphabetic
• Numeric
• Alpha-numeric

• Data type is important because it determines


the operations which are valid on the type.

Dec 7, 2021 46
Files, Records, Fields
• We use the term FIELD to describe an item of
information we are recording about an object
(e.g. StudentName, DateOfBirth, CourseCode).

• We use the term RECORD to describe the collection of


fields which record information about an object
(e.g. a StudentRecord is a collection of fields recording
information about a student).

• We use the term FILE to describe a collection of one or


more occurrences (instances) of a record type
(template).
• It is important to distinguish between the record
occurrence (i.e. the values of a record) and the record
type (i.e. the structure of the record).
Every record in a file has a different value but the same
structure.
Dec 7, 2021 47
Elementary and Group items
• The term “elementary item” is used to describe data
items which are atomic; that is, not further subdivided.

• An elementary item declaration consists of;


a level number – indicates hierarchy
a data name – identification reference
picture clause – determines the ‘type’.
An elementary item must have a picture clause.
• In COBOL the term “group item” is used to describe a
data item which has been further subdivided.
– A Group item is declared using a level number and a data name.
It cannot have a picture clause.
– Where a group item is the highest item in a data hierarchy it is
referred to as a record and uses the level number 01.
• Every group or elementary item declaration must be
Dec 7, 2021 48
followed by a full stop.
LEVEL Numbers express DATA hierarchy
• In COBOL, level numbers are used to decompose a structure
into it’s constituent parts.
• In this hierarchical structure the higher the level number,
the lower the item is in the hierarchy. At the lowest level the
data is completely atomic.
• The level numbers 01 through 49 are general level numbers
but there are also special level numbers such as 66, 77 and
88.
• In a hierarchical data description what is important is the
relationship of the level numbers to one another, not the
actual level numbers used.
01 StudentDetails. 01 StudentDetails.
01 02
StudentDetails.
StudentName. 01 05
StudentDetails.
StudentName.
02 03
StudentName.
Surname PIC X(8). 05 10
StudentName.
Surname PIC X(8).
03 Initials
03
03
Surname
Initials
PIC XX.
PIC
PIC
X(8).
XX.
= 10 Initials
10
10
Surname
Initials
PIC XX.
PIC
PIC
X(8).
XX.
02 StudentId PIC 9(7). 05 StudentId PIC 9(7).
02 CourseCode
02 StudentId PIC X(4).
PIC 9(7). 05 CourseCode
05 StudentId PIC X(4).
PIC 9(7).
02 Grant
02 CourseCode PIC 9(4).
PIC X(4). 05 Grant
05 CourseCode PIC 9(4).
PIC X(4).
02 Gender
02 Grant PIC X.
PIC 9(4). 05 Gender
05 Grant PIC X.
PIC 9(4).
02 Gender PIC X. 05 Gender PIC X.
Dec 7, 2021 49
COBOL ‘PICTURE’ Clause symbols
• To create the required ‘picture’ the programmer uses
a set of symbols.

• The following symbols are used frequently in picture


clauses;
– 9 (the digit nine) is used to indicate the occurrence
of a digit at the corresponding position in the
picture.
– X (the character X) is used to indicate the
occurrence of any character from the character set
at the corresponding position in the picture
– V (the character V) is used to indicate position of
the decimal point in a numeric value! It is often
referred to as the “assumed decimal point”
character.
– S (the character S) indicates the presence of a sign
and
Dec 7, 2021 can only appear at the beginning of a picture.
50
COBOL ‘PICTURE’ Clauses
• Some examples
– PICTURE 999 a three digit (+ve only) integer
– PICTURE S999 a three digit (+ve/-ve) integer
– PICTURE XXXX a four character text item or
string
– PICTURE 99V99 a +ve ‘real’ in the range 0 to
99.99
– PICTURE S9V9 a +ve/-ve ‘real’ in the range ?

• If you wish you can use the abbreviation PIC.

• Numeric values can have a maximum of 18 (eighteen)


digits (i.e. 9’s).

• The limit on string values is usually system-dependent.


Dec 7, 2021 51
Abbreviating recurring symbols

• Recurring symbols can be specified using a


‘repeat’ factor inside round brackets
– PIC 9(6) is equivalent to PICTURE 999999
– PIC 9(6)V99 is equivalent to PIC 999999V99
– PICTURE X(10) is equivalent to
PIC XXXXXXXXXX
– PIC S9(4)V9(4) is equivalent to PIC
S9999V9999
– PIC 9(18) is equivalent to
PIC 999999999999999999

Dec 7, 2021 52
Declaring DATA in COBOL

• In COBOL a variable declaration consists of a line


containing the following items;
A level number.
A data-name or identifier.
A PICTURE clause.

• We can give a starting value to variables by means of an


extension to the picture clause called the VALUE clause.

DATA DIVISION.
WORKING-STORAGE SECTION.
01 Num1 PIC 999 VALUE ZEROS.
DATA
01 VatRate PIC V99 VALUE 0.18.
Num1
Num1 VatRate
VatRate StudentName
StudentName 01 StudentName PIC X(10) VALUE SPACES.
000
000 .18
.18
Dec 7, 2021 53
PICTURES for Group Items

• Picture clauses are NOT specified for ‘group’


data items because the size a group item is the
sum of the sizes of its subordinate, elementary
items and its type is always assumed to be PIC X.

• The type of a group items is always assumed to


be PIC X because group items may have several
different data items and types subordinate to
them. (e.g., 1st name, middle name, surname)

• An X picture is the only one which could support


such collections.

Dec 7, 2021 54
More on PIC
PIC Size Remarks
A 1 byte Only a letter of Alphabet or space
B 1 byte one Space character is inserted
Z 1 byte Zero suppression in leading position
0 1 byte one zero character is inserted
/ 1 byte one “/” character is inserted
, 1 byte one comma character is inserted
. 1 byte Align decimal period & inserted “.”
+ 1 byte Editing sign control symbol
DB 2 bytes -do-
- 1 byte -do-
CR 2 bytes -do-
* 1 byte Cheque protection symbol in leading
Dec 7, 2021
positions 55
Editing Symbols

Edit Symbol Editing Type

,, B
B 00 // Simple
Simple Insertion
Insertion
.. Special
Special Insertion
Insertion
++ -- CR
CR DB
DB $$ Fixed
Fixed Insertion
Insertion
++ -- SS Floating
Floating Insertion
Insertion
ZZ ** Suppression
Suppression and
and
Replacement
Replacement
Dec 7, 2021 56
Simple Insertion

Sending
Sending Receiving
Receiving
Picture
Picture Data
Data Picture
Picture Result
Result
PIC
PIC999999
999999 123456
123456 PIC
PIC999,999
999,999 123,456
PIC
PIC9(6)
9(6) 000078
000078 PIC
PIC9(3),9(3)
9(3),9(3) 000,078
PIC
PIC9(6)
9(6) 000078
000078 PIC
PICZZZ,ZZZ
ZZZ,ZZZ 78
PIC ****178
PIC9(6)
9(6) 000178
000178 PIC ***,***
PIC ***,***
**2,178
PIC
PIC9(6)
9(6) 002178
002178 PIC ***,***
PIC ***,***

PIC 120183
PIC9(6)
9(6) 120183
120183 PIC
PIC99B99B99
99B99B99
PIC 12/01/83
PIC9(6)
9(6) 120183
120183 PIC
PIC99/99/99
99/99/99
PIC 120045
PIC9(6)
9(6) 001245
001245 PIC
PIC990099
990099
Dec 7, 2021 57
Special Insertion

Sending
Sending Receiving
Receiving
Picture
Picture Data
Data Picture
Picture Result
Result
PIC
PIC999V99
999V99 12345
12345 PIC
PIC999.99
999.99 123.45

023.4
PIC
PIC999V99
999V99 02345
02345 PIC
PIC999.9
999.9
12.34
PIC
PIC999V99
999V99 51234
51234 PIC
PIC99.99
99.99 456.00

PIC
PIC999
999 456
456 PIC
PIC999.99
999.99

Dec 7, 2021 58
Fixed Insertion - Plus and Minus

Sending
Sending Receiving
Receiving
Picture
Picture Data
Data Picture
Picture Result
Result
PIC
PICS999
S999 -123
-123 PIC
PIC-999
-999 -123
PIC 123-
PICS999
S999 -123
-123 PIC
PIC 999-
999-
123
PIC
PICS999
S999 +123
+123 PIC
PIC-999
-999
+12345
PIC -123
PICS9(5)
S9(5) +12345
+12345 PIC
PIC+9(5)
+9(5)
123-
PIC
PICS9(3)
S9(3) -123
-123 PIC
PIC+9(3)
+9(3)
PIC
PICS9(3)
S9(3) -123
-123 PIC
PIC999+
999+

Dec 7, 2021 59
Fixed Insertion - Credit, Debit, $

Sending
Sending Receiving
Receiving
Picture
Picture Data
Data Picture
Picture Result
Result
PIC
PICS9(4)
S9(4) +1234
+1234 PIC
PIC9(4)CR
9(4)CR 1234
PIC
PICS9(4)
S9(4) -1234
-1234 PIC
PIC9(4)CR
9(4)CR 1234CR
PIC
PICS9(4)
S9(4) +1234
+1234 PIC
PIC9(4)DB
9(4)DB 1223
PIC
PICS9(4)
S9(4) -1234
-1234 PIC
PIC9(4)DB
9(4)DB 1234DB

PIC
PIC9(4)
9(4) 1234
1234 PIC
PIC$99999
$99999 $01234
PIC $
PIC9(4)
9(4) 0000
0000 PIC
PIC$ZZZZZ
$ZZZZZ

Dec 7, 2021 60
Floating Insertion

Sending
Sending Receiving
Receiving
Picture
Picture Data
Data Picture
Picture Result
Result
PIC
PIC9(4)
9(4) 0000
0000 PIC
PIC$$,$$9.99
$$,$$9.99 $0.00
PIC
PIC9(4)
9(4) 0080
0080 PIC
PIC$$,$$9.00
$$,$$9.00 $80.00
PIC
PIC9(4)
9(4) 0128
0128 PIC
PIC$$,$$9.99
$$,$$9.99 $128.00
PIC
PIC9(5)
9(5) 57397
57397 PIC
PIC$$,$$9
$$,$$9 $7,397

PIC
PICS9(4)
S9(4) --0005
0005 PIC
PIC++++9
++++9 -5
PIC
PICS9(4)
S9(4) +0080
+0080 PIC
PIC++++9
++++9 +80
PIC
PICS9(4)
S9(4) --0080
0080 PIC
PIC-- ------ 99 -80
PIC
PICS9(5)
S9(5) +71234
+71234 PIC
PIC-- ------ 99 ž1234
Dec 7, 2021 61
Suppression and Replacement

Sending
Sending Receiving
Receiving
Picture
Picture Data
Data Picture
Picture Result
Result
PIC 12,345
PIC9(5)
9(5) 12345
12345 PIC
PICZZ,999
ZZ,999
1,234
PIC
PIC9(5)
9(5) 01234
01234 PIC ZZ,999
PIC ZZ,999 123
PIC
PIC9(5)
9(5) 00123
00123 PIC
PICZZ,999
ZZ,999 012
PIC
PIC9(5)
9(5) 00012
00012 PIC
PICZZ,999
ZZ,999 *5,678
PIC ***567
PIC9(5)
9(5) 05678
05678 PIC
PIC**,**9
**,**9
******
PIC
PIC9(5)
9(5) 00567
00567 PIC **,**9
PIC **,**9
PIC
PIC9(5)
9(5) 00000
00000 PIC
PIC**,***
**,***

Dec 7, 2021 62
The USAGE clause – why?

• The USAGE clause is used for purposes of


optimization - both speed and storage.

• The USAGE clause controls the way data


items (normally numeric) are stored in
memory.

Dec 7, 2021 63
USAGE Syntax

01 Num1 PIC 9(5)V99 USAGE IS COMP.


01 Num2 PIC 99 USAGE IS PACKED-DECIMAL.
(COMP-3)
01 IdxItem USAGE IS INDEX.
01 GroupItems COMP.
02 Item1 PIC 999.
02 Item2 PIC 9(4)V99.
Dec 7, 2021 64
02 New1 PIC S9(5) COMP SYNC.
USAGE IS DISPLAY

• The USAGE clause specifies the format of


numeric data items in the computer storage.
• When no USAGE clause is explicitly declared,
USAGE IS DISPLAY is assumed.
• When numeric items have a USAGE of DISPLAY
they are held as EBCDIC characters !!
• 0 is stored as x’F0’…………9 as x’F9’

Dec 7, 2021 65
Arithmetic when USAGE IS DISPLAY

8 4 2 1 8 4 2 1 HEX CHAR
Num1 PIC 9 VALUE 4. 1 1 1 1 0 1 0 0 F4 “4”

Num2 PIC 9 VALUE 1. 1 1 1 1 0 0 0 1 F1 "1"

Num3 PIC 9. 0 0 0 0 0 0 0 0 00 null

If a variable is not assigned any value, then the


content may be any thing!!

Dec 7, 2021 66
Arithmetic when USAGE IS COMPUTATIONAL

8 4 2 1 8 4 2 1 HEX CHAR
Num1 PIC 9 VALUE 4. 0 0 0 0 0 1 0 0 04 ?

Num2 PIC 9 VALUE 1. 0 0 0 0 0 0 0 1 01 ?

Num3 PIC 9. 0 0 0 0 0 0 0 0 0 null

Dec 7, 2021 67
Arithmetic when USAGE IS COMPUTATIONAL

8 4 2 1 8 4 2 1 HEX CHAR
Num1 PIC 9 VALUE 4. 0 0 0 0 0 1 0 0 04 ?

Num2 PIC 9 VALUE 1. 0 0 0 0 0 0 0 1 01 ?

Num3 PIC 9. 0 0 0 0 0 1 0 1 05 ?

ADD Num1,Num2 GIVING Num3. (Value = 5)

Dec 7, 2021 68
USAGE IS COMP
• COMP items are held in memory as pure binary
two's complement numbers.

Number of Digits Storage Required.


1 TO 4 HALF WORD (2 Bytes)
5 TO 9 ONE WORD (4 Bytes)
10 TO 18 1 DOUBLEWORD (8 Bytes)

01 TotalCount PIC 9(7) USAGE IS COMP. Or,


01 TotalCount PIC 9(7) USAGE IS COMPUTATIONAL.
Takes 4 bytes (1 LONGWORD) of storage.

Dec 7, 2021 69
COMP - Storage Requirements

2 Bytes can represent any 4 digit number.

32768 16384 8192 4096 2048 1024 512 256 128 64 32 16 8 4 2 1

Max. number = + or - 32767


PIC 9999 COMP

4 Bytes can represent any 9 digit number

Max. number = + or - 2, 147,483,647


PIC 999 999 999 COMP
Dec 7, 2021 70
USAGE IS PACKED-DECIMAL
• Data items declared as PACKED-DECIMAL (COMP-3) are
held in binary-coded-decimal (BCD) form.

• Instead of representing the value as one single binary


number, each digit is held in binary form in a nibble
(half a byte).

• The right-most nibble contains the sign (by definition)

PIC S9 PIC S9(2) PIC S9(3)


VALUE +5 VALUE -32 VALUE +262
5 + 0 3 2 - 2 6 2 +

Dec 7, 2021 71
Storage Requirement

• COMP-1 4 bytes (1 word)


• COMP-2 8 bytes (double-word)
• COMP-3 Half byte for each character &
mandatory half-byte (the last
half-byte) for sign

Dec 7, 2021 72
The SYNCHRONIZED Clause
• The SYNCHRONIZED clause explicitly aligns COMP
and INDEX data items along their natural WORD
boundaries.
• If there is no SYNCHRONIZED clause the data items
are aligned on byte boundaries.
• This clause is used to optimize speed of processing -
but it does so at the expense of storage.

01 ThreeBytes PIC XXX VALUE "DOG".


01 TwoBytes PIC 9(4) COMP.

D O G Number

01 NUM PIC 9(4) COMP SYNC or SYNCHRONIZED.


Dec 7, 2021 73
The SYNCHRONIZED Clause
COMP SYNC (1 TO 4 Digits) = 2 Byte boundary
COMP SYNC (5 TO 9 Digits) = 4 Byte boundary
COMP SYNC (10 TO 18 Digits)= 8 Byte boundary
INDEX = 4 Byte boundary

Note the difference between COMP and COMP SYNC.

01 ThreeBytes PIC XXX VALUE "DOG".


01 TwoBytes PIC 9(4) COMP SYNC.

D O G Number
Word1 Word2

Dec 7, 2021 74
The SYNCHRONIZED Clause

COMP SYNC (1 TO 4 Digits) = half-word boundary


COMP SYNC (5 TO 9 Digits) = word boundary
COMP SYNC (10 TO 18 Digits)= word boundary
INDEX = word boundary

01 FiveBytes PIC XXX VALUE "FROGS".


01 FourBytes PIC S9(5) COMP.

F R O G S NumberNumber
Word1 Word2 Word3

Dec 7, 2021 75
The SYNCHRONIZED Clause

COMP SYNC (1 TO 4 Digits) = 2 Byte boundary


COMP SYNC (5 TO 9 Digits) = 4 Byte boundary
COMP SYNC (10 TO 18 Digits)= 8 Byte boundary
INDEX = 4 Byte boundary
01 FiveBytes PIC XXX VALUE "FROGS".
01 FourBytes PIC S9(5) COMP SYNC. Aligns
Alignsalong
alongaa
44byte
byteboundary
boundary

FiveBytes FourBytes
F R O G S S S S NumberNumber
Word1 Word2 Word3
S : Slack Bytes (not available to the program)
unless
Dec 7, 2021
they are explicitly defined. 76
The SYNCHRONIZED Clause

• SYNC has no effect on DISPLAY or COMP-3 items


• COMP-1 (1 word) data is aligned on a word boundary
• Comp-2 (2 words) data is aligned on a word boundary

Slack Bytes (whenever required) will always be there


irrespective of whether you define them or not.
– Slack bytes within records
– Slack bytes between records
(refer pages 192-196 of IBM manual)

Dec 7, 2021 77
REDEFINES Clause
• REDEFINES clause allows you to use different data
entries to describe the same storage area.

• 05 A PIC X(4).
05 B REDEFINES A PIC 9(4).

A is Redefining Item or REDEFINES Subject


B is Redefined Item or REDEFINES Object

If the store location contains 1234, the content of A


is the character string “1234” and the content of B
is the numeric value 1234. B can participate in
Arithmetic operation but A cannot.
Dec 7, 2021 78
REDEFINES Clause
• Level-no data1 REDEFINES data2
05 A.
10 A1 PIC XX.
10 A2 PIC 9(3).
05 B REDEFINES A.
10 B1 PIC XXX.
10 B2.
15 B21 PIC 9.
15 B22 PIC 9.
Redefinition does not cause any data to be erased
or changed.
There can be as many redefinitions as required.

Dec 7, 2021 79
The Redefines Clause
Rates

1 2 .3 4 5

01 Rates.
02 10Rate PIC 99V999.
02 100Rate REDEFINES 10Rate PIC 999V99.
02 1000Rate REDEFINES 10Rate PIC 9999V9.

Dec 7, 2021 80
The Redefines Clause

Rates

1 2 3 .4 5

01 Rates.
02 10Rate PIC 99V999.
02 100Rate REDEFINES 10Rate PIC 999V99.
02 1000Rate REDEFINES 10Rate PIC 9999V9.

Dec 7, 2021 81
The Redefines Clause

Rates

1 2 3 4 .5

01 Rates.
02 10Rate PIC 99V999.
02 100Rate REDEFINES 10Rate PIC 999V99.
02 1000Rate REDEFINES 10Rate PIC 9999V9.

Dec 7, 2021 82
The Redefines Clause
EuroDate
EuroDay EuroMonth
EuroYear
HoldDate 11 06 1983
USDay USMonth USYear
USDate

01 HoldDate.
02 EuroDate.
03 EuroDay PIC 99.
03 EuroMonth PIC 99.
03 EuroYear PIC 9(4).
02 USDate REDEFINES EuroDate.
03 USMonth PIC 99.
03 USDay PIC 99.
03 USYear PIC 9(4).
Dec 7, 2021 83
The Redefines Clause

• Undefined results when


– A redefining item to moved to a redefined item
– A redefined item to moved to a redefining item
– Contradictory redefines, e.g.,
05 A PIC 9(5) COMP-3.
05 B REDEFINES A PIC 999.

Dec 7, 2021 84
One Dimension Table

01 JeansTable.

Dec 7, 2021 85
One Dimension Table

1 2 3 4

Province(1) Province(2) Province(3) Province(4)


1st occurrence 2nd occurrence 3rd occurrence 4th occurrence

01 JeansTable.
02 Province PIC X(8) OCCURS 4. or

02 Province PIC X(8) OCCURS 4 TIMES.


Dec 7, 2021 86
One Dimension Table

12346.99
1 309 2 3 4

01 JeansTable.
02 Province OCCURS 4 TIMES.
03 SalesValue PIC 9(4)V99.
03 NumSold PIC 9(2).

Province
SalesValue NumSold
Dec 7, 2021 87
Table
• 02 PROVINCE PIC X(8) OCCURS 4.

• Total occurrence is 4.

PROVINCE is a subscripted item.


The 1st occurrence of PROVINCE is denoted by
PROVINCE(1) and is referred to as PROVINCE
subscripted by 1.
Subscript may be an absolute number, or a variable
(which has to be defined explicitly) or an
expression.
PROVINCE(3) PROVINCE(K) PROVINCE(K+1)
Dec 7, 2021 88
Table
• 02 PROVINCE PIC X(8) OCCURS 4
INDEXED BY I.
• Here, I is called the index-name
Index-names are NOT to be defined. It can only be
used for referencing an occurrence of the associated
table.
SET I TO 3. PROVINCE(I) refers to 3rd occurrence.
Arithmetic operation on subscript variable
Index is manipulated by SET verb

Subscript gives the occurrence – address is


calculated from the occurrence number.
Index gives the relative displacement, hence more
efficient
Dec 7, 2021 89
Two Dimension Table

1 2 3 4

01 JeansTable.
02 Province OCCURS 4 TIMES.

Dec 7, 2021 90
Two Dimension Table
Province(1) Province(2) Province(3) Province(4)
1 2 3 4
1 2 1 2 1 2 1 2
G(1 1) 6 2 G(2,1) G(4,2)

SV(1,2) NS(1,2)

01 JeansTable.
02 Province OCCURS 4 TIMES.
03 Gender OCCURS 2 TIMES.
04 SalesValue PIC 9(4)V99.
04 NumSold PIC 9(2).

Province(3), Gender(3,1), Gender(3,1)


SV(3 1), NS(3 1), SV(3 2), NS(3 2)
Dec 7, 2021 91
Three Dimension Table

1 2 3 4

01 JeansTable.
02 Province OCCURS 4 TIMES.

Dec 7, 2021 92
Three Dimension Table

1 2 3 4
1 2 1 2 1 2 1 2

01 JeansTable.
02 Province OCCURS 4 TIMES.
03 Gender OCCURS 2 TIMES.

Dec 7, 2021 93
Three Dimension Table

1 2 3 4
1 2 1 2 1 2 1 2
1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3

01 JeansTable.
02 Province OCCURS 4 TIMES.
03 Gender OCCURS 2 TIMES.
04 Colour OCCURS 3 TIMES.

Dec 7, 2021 94
Three Dimension Table

1 2 3 4
1 2 1 2 1 2 1 2
1 12346.99 309
2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3

01 JeansTable.
02 Province OCCURS 4 TIMES.
03 Gender OCCURS 2 TIMES.
04 Colour OCCURS 3 TIMES.
05 SalesValue PIC 9(4)V99.
05 NumSold PIC 9(2).

Dec 7, 2021 Colour 95


SalesValue NumSold
Record Elements

1 2 3 4
* 1 2 * 1 2 * 1 2 * 1 2
1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3

01 JeansTable.
02 Province OCCURS 4 TIMES.
03 ProviceTotal PIC 9(8).
03 Gender OCCURS 2 TIMES.
04 Colour OCCURS 3 TIMES.
05 SalesValue PIC 9(8)V99.
Dec 7, 2021 05 NumSold PIC 9(7). 96
Tables
What is the difference between:
01 Students.
02 Subject OCCURS 4 TIMES.
03 Marks OCCURS 3 TIMES.
05 Tot PIC 9(4)V99.
05 Score PIC 9(2).
and

01 Students.
02 Subject OCCURS 4 TIMES.
05 Tot PIC 9(4)V99 OCCURS 3 TIMES.
05 Score PIC 9(2) OCCURS 3 TIMES.

OCCURS is not allowed in 01 level.


Dec 7, 2021 97
PROCEDURE DIVISION
• PROCEDURE DIVISION.
• The PROCEDURE DIVISION is where all the data
described in the DATA DIVISION is processed. It is
here that the programmer describes his algorithm.
• The PROCEDURE DIVISION is hierarchical in structure
and consists of Sections, Paragraphs, Sentences and
Statements.
• Only the Section is optional. There must be at least one
paragraph or sentence or statement in the PROCEDURE
DIVISION.
• In the PROCEDURE DIVISION paragraph and section
names are chosen by the programmer. The names used
should reflect the processing being done in the
paragraph or section.
Dec 7, 2021 98
PROCEDURE DIVISION
Statement Categories
Imperative
Conditional
Delimited scope
Compiler directing

Imperative statements
Arithmetic: ADD SUBTRACT MULTIPLY
DIVIDE COMPUTE

Data movement: ACCEPT INITILIZE INSPECT


STRING UNSTRING SET MOVE

Ordering: MERGE RELEASE RETURN SORT


Dec 7, 2021 99
PROCEDURE DIVISION
Imperative statements

I-O: ACCEPT CLOSE DELETE DISPLAY


OPEN READ WRITE REWRITE
START STOP literal

Subprogram/Linking : CALL CANCEL

Branching: PERFORM EXIT GO TO

Dec 7, 2021 100


PROCEDURE DIVISION
Conditional statements

Arithmetic: COMPUTE DIVIDE MULTIPLY SUBTRACT


ADD….[on size] [error]. Similarly, others.

Data movement: STRING/UNSTRING… [on overflow]

Decision: IF EVALUATE

Ordering: RETURN… [AT END]

I-O: READ… AT END…


READ … INVALID KEY

Dec 7, 2021 101


PROCEDURE DIVISION

Delimited Scope statements:


END-ADD END-SUBTRACT END-MULTIPLY
END-DIVIDE END-COMPUTE END-READ
END-IF END-PERFORM ………………..

Compiler Directing statements:


COPY REPLACE DELETE
EJECT INSERT SKIP1
SKIP2 SKIP3 TITLE ……

Dec 7, 2021 102


PROCEDURE DIVISION - Syntax
• The PROCEDURE DIVISION is where all the data
described in the DATA DIVISION are processed. It is
here that the programmer describes the processing
logic and algorithm of his program.

PROCEDURE DIVISION [USING…….].


[ DECLARATIVES.
……………………….]
[Section-name.]
Paragraph-name.
sentences -> statements -> verbs…
Section-name.
Paragraph-name.
sentences -> statements -> verbs… and so on…..
Dec 7, 2021 103
Full computing logic……………………..
PROCEDURE DIVISION
USING and DECLARATIVES explained later.
Some Verbs:

For transferring user data into an identifier in a program:


ACCEPT identifier-1 [FROM mnemonic-name*]
identifier-1 is a data-item with usage DISPLAY.
* names (SYSIN..) must be defined in SPECIAL-NAMES.
If FROM is omitted, default is console

For transferring system data into an identifier in a program:


ACCEPT identifier-2 FROM {DATE/ DAY/ TIME/
DAY-OF-WEEK}
DATE – YYMMDD.
DAY – YYddd (Julian date – 99001)
TIME – HHMMSShh (hh: hundredths of a sec.)
DAY-OF-WEEK – n (1:Mon, 2:Tue,…7:Sun)
Dec 7, 2021 104
PROCEDURE DIVISION

For displaying content of a program variable onto an


OUTPUT device:

DISPLAY identifier-1 (or, literal-1) [UPON mnemonic-


name*]
identifier-1 is a data-item. If required, the
content will be automatically converted to
usage DISPLAY.

* mnemonic-names (SYSOUT, SYSPUNCH etc.)


must be defined in SPECIAL-NAMES.

If UPON is omitted, default is console.


Dec 7, 2021 105
PROCEDURE DIVISION
ADD iden-1… TO iden-2 [ROUNDED]….
ADD iden-1 iden-2 GIVING iden-3 [ROUNDED].
ADD iden-1 iden-2 GIVING iden-3 ON SIZE ERROR
imperative statement

ADD A1 TO B1.
ADD A2 A3 A4 TO B2 B3.
ADD A4 A5 A6 GIVING B4.

A1 A2 A3 A4 A5 A6 B1 B2 B3 B4
Before 1 2 3 4 5 6 7 8 9 2
After 1 2 3 4 5 6 8 17 18 15
Dec 7, 2021 106
The ON SIZE ERROR option

Receiving Field Actual Result SIZE ERROR


PIC 9(3)V9. 245.96 Yes
PIC 9(3)V9. 1245.9 Yes
PIC 9(3). 124 No
PIC 9(3). 1246 Yes
PIC 9(3)V9 Not Rounded 124.45 Yes
PIC 9(3)V9 ROUNDED 124.45 No

PIC 9(3)V9 Rounded 3124.45 Yes

 A size error condition exists when, after decimal point


alignment, the result is truncated on either the left or
the right hand side.
 If an arithmetic statement has a rounded phrase then
a size error only occurs if there is truncation on the
left hand side (most significant digits).
Dec 7, 2021 107
Let us write a small Cobol Program
Q. Get two numbers from user and find their summation.
IDENTIFICATION DIVISION.
PROGRAM-ID. MyProgram.
AUTHOR. Globsyn.

DATA DIVISION.
WORKING-STORAGE SECTION.
01 Num1 PIC 9 VALUE ZEROS.
01 Num2 PIC 9 VALUE ZEROS.
01 Result PIC 99 VALUE ZEROS.

PROCEDURE DIVISION.
Calc-Result.
DISPLAY “First Operand, please”.
ACCEPT Num1.
DISPLAY “Second Operand, please”.
ACCEPT Num2.
ADD Num1 Num2 GIVING Result.
DISPLAY "Result is = ", Result.
Result
Dec 7, 2021 RUN.
STOP 108
PROCEDURE DIVISION
ADD [CORR, or CORRESPONDING] iden-1 TO iden-2.

iden-1 & iden-2 both are group items. Add operations


are performed on elementary items of the same name.

"ADD" ( "CORRESPONDING" | "CORR" ) A TO B
[ "END-ADD" ]
05 A. 02 B.
10 F1 PIC 99. 05 XYZ PIC X(8).
10 F2 PIC 99. 05 F2 PIC 9.
10 F3 PIC 99. 05 F1 PIC 9(5)

Dec 7, 2021 109


PROCEDURE DIVISION

• SUBTRACT iden-1(or, literal)…..FROM iden-2……


• SUBTRACT iden-1(or, literal)…..FROM iden-2 GIVING
iden-3….

SUBTRACT A1 A2 FROM B1 B2.


SUBTRACT A3 A4 FROM A5 GIVING B3 B4.

A1 A2 A3 A4 A5 B1 B2 B3 B4
Before 1 3 3 4 15 7 8 9 2
After 1 3 3 4 15 3 4 8 8

Dec 7, 2021 110


PROCEDURE DIVISION
SUBTRACT CORRESPONDING (or, CORR) iden-1
FROM iden-2.

iden-1 & iden-2 both are group items. Subtract


operations are performed on elementary items of
the same name.

SUBTRACT CORR A FROM B


[ END-SUBTRACT ]

05 A. 02 B.
10 F1 PIC 99. 05 XYZ PIC X(8).
10 F2 PIC 99. 05 F2 PIC 9.
10 F3 PIC 99. 05 F1 PIC 9(5)

Dec 7, 2021 111


PROCEDURE DIVISION

MULTIPLY iden-1 BY iden-2…..

MULTIPLY iden-3 BY iden-4 GIVING iden-5.

MULTIPLY A1 BY A2 A3.
MULTIPLY A4 BY A5 GIVING A6.

A1 A2 A3 A4 A5 A6
Before 2 3 4 4 5 6
After 2 6 8 4 5 20

Dec 7, 2021 112


PROCEDURE DIVISION
DIVIDE iden-1 INTO iden-2…..[ROUNDED]

DIVIDE iden-1 INTO iden-2 GIVING iden-3 …[ROUNDED].

DIVIDE iden-1 BY iden-2 GIVING iden-3 …[ROUNDED].

DIVIDE A1 INTO A2 A3.


DIVIDE A4 INTO A5 GIVING A6 A7.
DIVIDE A8 BY A9 GIVING A10 A11 ROUNDED .

A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11
Before 12 2 4 14 7 6 5 15 4 0 1
After 12 6 3 14 7 2 2 15 4 4 4

Dec 7, 2021 113


PROCEDURE DIVISION

DIVIDE iden-1 INTO id-2 GIVING id-3 REMAINDER id-4

DIVIDE iden-1 BY id-2 GIVING id-3 REMAINDER id-4

DIVIDE A1 INTO A2 GIVING A3 REMAINDER A4.


DIVIDE A5 BY A6 GIVING A7 REMAINDER A8.
DIVIDE A9 INTO A10

A1 A2 A3 A4 A5 A6 A7 A8 A9 A10
Before 13 2 4 14 8 6 5 15 9 2
After 13 2 6 1 8 6 1 2 9 4

Dec 7, 2021 114


PROCEDURE DIVISION
COMPUTE assigns the value of an arithmetic expression
to 1 or more data items.

COMPUTE iden-1 [ROUNDED] EQUAL (or, =) arithmetic


expression

Arithmetic Operators:
Addition + Subtraction - Multiplication *
Division / Exponentiation **

Parentheses (brackets) used for prioritization.


Computations are carried out from left to right order
following the the famous BEDMAS rule – bracket,
exponentiation, division, multiplication, addition &
subtraction left to right.
Dec 7, 2021 115
PROCEDURE DIVISION
Conditional Expressions
Class condition:
Identifier [IS] [NOT] NUMERIC……
NUMERIC – for usage display and Comp-3, not
applicable for group item or with PIC A
ALPHABETIC – PIC A and PIC X
ALPHABETIC-LOWER – all the characters in lower case.
ALPHABETIC-UPPER
IF NAME ALPHABETIC imperative statement

Condition-Name condition:
05 AGE PIC 99
88 TEEN-AGER VALUE 13 THRU 19.
…. Dec
IF7,TEEN-AGER
2021 imperative statement 116
PROCEDURE DIVISION
Conditional Expressions
Relation condition:
operand-1 [IS] [NOT] Relation condition operand-2
GREATER THAN or >
LESS THAN or <
EQUAL TO or =
GREATER THAN OR EQUAL TO or >=
LESS THAN OR EQUAL TO or <=

Sign condition:
operand-1 [IS] [NOT] Sign condition imperative statement
POSITIVE
NEGATIVE
ZERO
Dec 7, 2021 117
PROCEDURE DIVISION
Logical Operators
OR : The truth value is true when either
or both conditions are true
AND : The truth value is true when both
conditions are true

Combined condition
condition1 AND [OR] condition2

Complex condition
Dec 7, 2021 118
PROCEDURE DIVISION
IF cond-1 [THEN] statements
ELSE statements
END-IF

Statements: verb, NEXT SENTENCE, GO TO….

Nested If:
IF cond-1 [THEN] statements
ELSE IF cond-2 [THEN] statements
ELSE statements
END-IF
END-IF

Dec 7, 2021 119


PROCEDURE DIVISION
Transferring control

GO [ TO ] procedure-name

GO [ TO ] proc1, proc2….DEPENDING [ON]
identifier1

Procedure-name: paragraph-name or section name


Identifier1 must be a numeric data item. Control is
transferred to proc1, proc2 and so on depending on
The value of identifier1. If the value is 0, -ve or
more than the number of entries in the proc list,
then the control goes to the next statement.
Dec 7, 2021 120
PROCEDURE DIVISION
EVALUATE subject1 [ALSO subject2….
{{ WHEN object1 [ALSO object2]…imperative statement}
[ WHEN OTHER imperative statement]
END-EVALUATE

subjects are identifier/literal/expression/TRUE/FALSE


objects are {TRUE/FALSE/condition/ANY
identifier-1 THRU identifier-2}

EVALUATE MARKS
WHEN 80 THRU 100 DISPLAY “GRADE=A”
WHEN 60 THRU 79 DISPLAY “GRADE=B”
WHEN 50 THRU 59 DISPLAY “GRADE=C”
WHEN OTHER DISPLAY “GRADE=F”
Dec 7, 2021 121
END-EVALUATE
PROCEDURE DIVISION
MOVE verb for data movement
MOVE iden-1 TO iden-2 [iden-3……..].
MOVE CORR (or, CORRESPONDING) iden-1 TO iden-2.

iden-1 : sending item/area


idem-2 : receiving item/area
Format1: identifiers can be elementary or group items.
Format2: identifiers have to be group items. Data
movements for items with same name.

For alpha-numeric, data is moved from left to right.


For numeric, first decimal point is aligned then the
mantissa part is moved from right to left and the
decimal part from left to right.
Dec 7, 2021 122
PROCEDURE DIVISION
MOVE iden-1 TO iden-2 before after
ABCDE PIC X(6) XYZPQR ABCDEb
ABCD X(2) WW AB
ABCDE XX/XX AB/CD
ABCDE XBX(5) AbBCDEb
1234 99,9(3) 01,234
1234 99,B999,B000 01,b234,b000
1.234 999.99 001.23
-123.4 99.99 23.40
12.345 999.99+ 012.34+
-12.345 999.99+ 012.34-
12.345 999.99- 012.34b
-12.345 999.99+ 012.34-
Dec 7, 2021 123
PROCEDURE DIVISION immaterial
iden-1 TO iden-2 before after
12.345 +999.99 +012.34
-12.345 +999.99 -012.34
12.345 -999.99 b012.34
-12.345 -999.99 -012.34
-12.345 $999.99 $012.34
-12.345 -$999.99 -$012.34
-1 -(3),--.99 bbbb-1.00
0000.00 +++,+++.+++ bbbbbbbbbbb
1246 *,**,***.99 ***1,246.00
.123 $$$.99 bb$.12
.12 $$$9.99 bb$0.12
Dec 7, 2021 124
Procedure Division – MOVE: Simple Insertion

Sending
Sending Receiving
Receiving
Picture
Picture Data
Data Picture
Picture Result
Result
PIC
PIC999999
999999 123456
123456 PIC
PIC999,999
999,999 123,456
PIC
PIC9(6)
9(6) 000078
000078 PIC
PIC9(3),9(3)
9(3),9(3) 000,078
PIC
PIC9(6)
9(6) 000078
000078 PIC
PICZZZ,ZZZ
ZZZ,ZZZ 78
PIC
PIC9(6)
9(6) 000178
000178 PIC
PIC***,***
***,*** ****178
PIC **2,178
PIC9(6)
9(6) 002178
002178 PIC ***,***
PIC ***,***

PIC
PIC9(6)
9(6) 120183
120183 PIC
PIC99B99B99
99B99B99 120183
PIC
PIC9(6)
9(6) 120183
120183 PIC
PIC99/99/99
99/99/99
12/01/83
PIC 120045
PIC9(6)
9(6) 001245
001245 PIC
PIC990099
990099
Dec 7, 2021 125
Procedure Division – MOVE: Special Insertion

Sending
Sending Receiving
Receiving
Picture
Picture Data
Data Picture
Picture Result
Result
PIC
PIC999V99
999V99 12345
12345 PIC
PIC999.99
999.99 123.45

023.4
PIC
PIC999V99
999V99 02345
02345 PIC
PIC999.9
999.9
12.34
PIC
PIC999V99
999V99 51234
51234 PIC
PIC99.99
99.99 456.00

PIC
PIC999
999 456
456 PIC
PIC999.99
999.99

Dec 7, 2021 126


MOVE: Fixed Insertion - Plus and
Minus

Sending
Sending Receiving
Receiving
Picture
Picture Data
Data Picture
Picture Result
Result
PIC
PICS999
S999 -123
-123 PIC
PIC-999
-999 -123
PIC 123-
PICS999
S999 -123
-123 PIC
PIC 999-
999- 123
PIC
PICS999
S999 +123
+123 PIC
PIC-999
-999
+12345
PIC -123
PICS9(5)
S9(5) +12345 PIC +9(5)
+12345 PIC +9(5)
123-
PIC
PICS9(3)
S9(3) -123
-123 PIC
PIC+9(3)
+9(3)
PIC
PICS9(3)
S9(3) -123
-123 PIC
PIC999+
999+

Dec 7, 2021 127


MOVE: Fixed Insertion - Credit, Debit, $

Sending
Sending Receiving
Receiving
Picture
Picture Data
Data Picture
Picture Result
Result
PIC
PICS9(4)
S9(4) +1234
+1234 PIC
PIC9(4)CR
9(4)CR 1234
PIC
PICS9(4)
S9(4) -1234
-1234 PIC
PIC9(4)CR
9(4)CR 1234CR
PIC
PICS9(4)
S9(4) +1234
+1234 PIC
PIC9(4)DB
9(4)DB 1223
PIC
PICS9(4)
S9(4) -1234
-1234 PIC
PIC9(4)DB
9(4)DB 1234DB

PIC
PIC9(4)
9(4) 1234
1234 PIC
PIC$99999
$99999
$01234
PIC
PIC9(4)
9(4) 0000
0000 PIC
PIC$ZZZZZ
$ZZZZZ $

Dec 7, 2021 128


MOVE: Floating Insertion

Sending
Sending Receiving
Receiving
Picture
Picture Data
Data Picture
Picture Result
Result
PIC
PIC9(4)
9(4) 0000
0000 PIC
PIC$$,$$9.99
$$,$$9.99 $0.00
PIC $80.00
PIC9(4)
9(4) 0080
0080 PIC $$,$$9.00
PIC $$,$$9.00 $128.00
PIC
PIC9(4)
9(4) 0128
0128 PIC
PIC$$,$$9.99
$$,$$9.99 $7,397
PIC
PIC9(5)
9(5) 57397
57397 PIC
PIC$$,$$9
$$,$$9
-5
+80
PIC
PICS9(4)
S9(4) --0005
0005 PIC
PIC++++9
++++9 -80
PIC
PICS9(4)
S9(4) +0080
+0080 PIC
PIC++++9
++++9 ž1234
PIC
PICS9(4)
S9(4) --0080
0080 PIC
PIC-- ------ 99
PIC
PICS9(5)
S9(5) +71234
+71234 PIC
PIC-- ------ 99
Dec 7, 2021 129
MOVE: Suppression and Replacement

Sending
Sending Receiving
Receiving
Picture
Picture Data
Data Picture
Picture Result
Result
PIC
PIC9(5)
9(5) 12345
12345 PIC
PICZZ,999
ZZ,999 12,345
1,234
PIC
PIC9(5)
9(5) 01234
01234 PIC
PICZZ,999
ZZ,999 123
PIC
PIC9(5)
9(5) 00123
00123 PIC
PICZZ,999
ZZ,999 012
PIC *5,678
PIC9(5)
9(5) 00012
00012 PIC ZZ,999
PIC ZZ,999
PIC
PIC9(5)
9(5) 05678
05678 PIC
PIC**,**9
**,**9 ***567
******
PIC
PIC9(5)
9(5) 00567
00567 PIC **,**9
PIC **,**9
PIC
PIC9(5)
9(5) 00000
00000 PIC
PIC**,***
**,***

Dec 7, 2021 130


PROCEDURE DIVISION

MOVE ALL literal TO identifier


MOVE ALL “-” TO LINE1.
MOVE ZERO/ZEROS/ZEROES/SPACE/SPACES…

Dec 7, 2021 131


PROCEDURE DIVISION
INITIALIZE iden-1 [iden-2…….]
identifier may be elementary or group item.
Numeric fields are initialized with 0 and alphanumeric
fields as space.
For group items, each elementary fields initialized as
per their picture clause.

INITIALIZE iden-1 [iden-2…….] [ REPLACING


{ [NUMERIC /ALPHANUMERIC/ NUMERIC-EDITED DATA
BY literal or identifier]……….}

INITIALIZE A REPLACING NUMERIC DATA BY 50


REPLACING ALPHANUMERIC DATA BY “A”.
Dec 7, 2021 132
INITIALIZE example
01 A.
03 A1 PIC 9(3).
03 A2 PIC XX.
03 A3 PIC Z9.9.

1. INITIALIZE A REPLACING NUMERIC DATA BY 50

2. INITIALIZE A REPLACING NUMERIC DATA BY 9


REPLACING ALPHANUMERIC DATA BY “A”
REPLACING NUMERIC-EDITED BY 2.5.
1. Only A1 will be changed to 050
2. A1=009, A2=bA and A3=b2.5

Dec 7, 2021 133


PROCEDURE DIVISION

STOP RUN - halts execution permanently

STOP literal - halts temporarily and is resumed only


after operator intervention, and
continues at the next executable
statement.

Note: STOP RUN will close all open files, release the
acquired resources and terminate the execution.
STOP “OK?” – program will stop with a message OK?
and halt. It has to be manually restarted – by console
operator or display/accept statement of the program.
Dec 7, 2021 134
PROCEDURE DIVISION
SET statement is used to perform:
– Index manipulation (table/occurs)
– Incrementing/decrementing an occurrence no.
– Moving data to condition name

SET index1 [index2…] TO iden-1 or integer-1 or


index-name.
SET index-name TO 0 (or, 1, 2 etc.)
SET index-name UP BY 1.
SET index-name DOWN BY 1.

Dec 7, 2021 135


PROCEDURE DIVISION

SET condition-name TO TRUE


NOTE: you cannot SET to FALSE

01 TAX-CODE PIC 9.
88 EXEMPT VALUE 0.

SET EXEMPT TO TRUE.

This not only sets EXEMPT to TRUE, it also moves a


zero value to TAX-CODE.

Dec 7, 2021 136


PROCEDURE DIVISION

CONTINUE statement allows you to specify


one ‘no operation’ statement. It indicates that
no executable instruction is present.

Format:
CONTINUE.

Dec 7, 2021 137


PROCEDURE DIVISION
EXIT statement provides a common end point or exit
point for a series of procedures.

Paragraph-name.
EXIT.

EXIT must be the single statement in that paragraph.


It is treated as “continue” – having no affect.
If it is not the single statement in the paragraph
(even, otherwise) statements following the ‘exit’ will
be executed.
Dec 7, 2021 138
PROCEDURE DIVISION
PERFORM statement transfers control explicitly to one
or more procedures and executes. After execution,
the control is implicitly returns to the next executable
statement after the ‘perform’ statement.

PERFORM proc1 [THRU proc2] [END-PERFORM].

Proc1, proc2 must name a section or paragraph of the


program.

PERFORM para1.
PERFORM para1 THRU para5.
PERFORM proc1 [THRU proc2] int-1 (or, lit-1) TIMES.
PERFORM para1 THRU para5 10 TIMES.
Dec 7, 2021 139
PROCEDURE DIVISION
In-line PERFORM

PERFORM imperative statement(s) END-PERFORM.

PERFORM
ADD……..
……….
END-PERFORM

If ‘GO TO’ is used within the scope of perform, care


must be taken to return the control properly after
the execution of PERFORM.

Dec 7, 2021 140


PROCEDURE DIVISION
PERFORM para-1 [ THRU para-2 ] [ WITH TEST
{BEFORE|AFTER} ] UNTIL condition-1.

MOVE 0 TO SUM NUM.


PERFORM ADD-PARA UNTIL NUM = 50.
ADD-PARA.
ADD 1 TO NUM. ADD NUM TO SUM.
Test Before Test After

enter enter

True
condition--Exit execute range
False
execute range condition
Dec 7, 2021 141
PROCEDURE DIVISION

PERFORM para-1 [ THRU para-2 ] [ WITH TEST


{BEFORE|AFTER} ] VARYING KOUNT FROM 1 BY 1
UNTIL KOUNT > 30.

PERFORM UNTIL I > 30


ADD AMT(I) TO TOTAL
ADD 1 TO I
END-PERFORM

PERFORM VARYING I FROM 1 BY 1 UNTIL I > 30


ADD AMT(I) TO TOTAL
END-PERFORM
Dec 7, 2021 142
PROCEDURE DIVISION
PERFORM proc-1 [THRU proc-2] VARYING iden-1
FROM iden-2 BY iden-3 UNTIL cond-1
[ AFTER iden-4 FROM iden-5 BY iden-6 UNTIL cond-2
[AFTER iden-7 FROM iden-8 BY iden-9 UNTIL cond-3 ] ]
END-PERFORM
Note: iden is identifier or literal
PERFORM FIND-TOTAL
VARYING I FROM 1 BY 1 UNTIL I > 50
AFTER J FROM 1 BY 1 UNTIL J > 10.

The loop will be performed 500 times.


First I will be set to 1, FIND-TOTAL will be executed 10
times – with J=1, J=2, ….,J=10
Then I will be set to 2, FIND-TOTAL will be executed 10
times – with J=1, J=2, ….,J=10 and so on…
Finally,
Dec 7, I =50, J from 1 to 10.
2021 143
Record Buffers

• To process a file records are read from the file


into the computer’s memory one record at a time.

• The computer uses the programmers description


of the record (i.e. the record template) to set
aside sufficient memory to store one instance of
the record.

• Memory allocated for storing a record is usually


called a “record buffer”

• The record buffer is the only connection between


the program and the records in the file.
Dec 7, 2021 144
Record Buffers

Program
IDENTIFICATION DIVISION.
etc.
ENVIRONMENT DIVISION.
etc.
Record Instance DATA DIVISION.
DISK FILE SECTION.

STUDENTS RecordBuffer
Declaration

Logical record / physical record


Dec 7, 2021 145
Implications of ‘Buffers’
• If your program processes more than one file you
will have to describe a record buffer for each file.
• To process all the records in an INPUT file each
record instance must be copied (read) from the
file into the record buffer when required.
• To create an OUTPUT file containing data records
each record must be placed in the record buffer
and then transferred (written) to the file.
• To transfer a record from an input file to an
output file we will have to
– read the record into the input record buffer
– transfer it to the output record buffer
– write the data to the output file from the
output record buffer
Dec 7, 2021 146
Data Organization

• Storage, retrieval, updating


• Access
• MVS VSAM datasets
– ESDS
– KSDS
– RRDS

Dec 7, 2021 147


Record Description
Assume a file (called, StudentFile) contains records of
all students. One record for each student and a record
(say, StudentDetails) contains following info:
StudentDetails 01 StudentDetails.
Name – Surname 05 Name.
– Actual Name 10 Surname PIC X(20).
10 Actual Name PIC X(20).
DOB – Year
05 DOB.
– Month
– Date 10 YY PIC 99.
10 MM PIC 99.
DOJ – Date
10 DD PIC 99.
– Month
– Year 05 DOJ.
10 DD PIC X(02).
10 MM PIC X(02).
10 YY PIC X(02).
Dec 7, 2021Note the full stops. Find out an error in above example
148
PROCEDURE DIVISION
File Handling

OPEN { INPUT | OUTPUT | EXTEND | I-O }


file-1 [ file2 …]
[{ INPUT | OUTPUT | EXTEND | I-O }
file-3 [ file4 …] …]

Any file to be processed by a Cobol program, must be


OPENed in appropriate mode. The execution of OPEN
verb performs certain operations – ensure availability
of the file, header-level processing (like expiry date
etc.), allocation of buffer areas, set and initialize the
file handling control area (e.g., file pointer) etc.
Dec 7, 2021 149
PROCEDURE DIVISION
OPEN INPUT – reading only
sequential: sequential access
indexed: sequential/random access
Dynamic access
relative files: -do- -do-

OUTPUT – writing only


sequential/indexed/relative files

EXTEND – sequential files (existing)

I-O – updating purpose


indexed/relative files: random access

OPEN verb does not read or write a record.


It points to the first record.
Dec 7, 2021 150
PROCEDURE DIVISION

CLOSE file-1 [ file2 …]

Any file processed by a Cobol program, must be


CLOSEd. This ensures that the trailer-level processing
for the file is done – flushing out of the last block (even
if it is not fully occupied), check-sum info for tape files,
EOF tag etc.

If a file is not CLOSEd, it cannot be processed properly


in future.

Only OPENed files can be CLOSEd.


Dec 7, 2021 151
PROCEDURE DIVISION
START file-name [ KEY [IS] { = (or, EQUAL TO) | > (or,
GREATER [THAN]) | < (or, LESS [THAN]) }
data-1 ] [INVALID [KEY] imperative statement.

For dynamic accessing of indexed or relative files, you can


place the file record pointer at a particular position with
the help of START verb, wherefrom you can do
subsequent operations sequentially.
START does not read a record, it just puts the pointer, so
that next READ can fetch the desired record.

START emp-file KEY = 1234


INVALID KEY DISPLAY “Emp 1234 not there!”
Dec 7, 2021 152
PROCEDURE DIVISION
Reading records from a sequential file or a relative file
being processed sequentially.

READ file-1 [INTO iden-1]


[AT END imperative statement].

If INTO-phrase is omitted then the record read will be


available in the record buffer described under “FD” clause.

READ my-file AT END PERFORM END-PARA.

READ my-file INTO WS-REC-AREA


AT END PERFORM END-PARA
END-READ.
Dec 7, 2021 153
PROCEDURE DIVISION

Reading a record from an indexed file or a relative file


where record-key is given (either in record-area or in
Relative key)

READ file-1 [INTO iden-1]


[ INVALID [KEY] imperative statement ].

MOVE 50 TO REL-KEY.
READ rel-file INTO WS-REL-REC
INVALID KEY GO TO PARA-INVALID.

Dec 7, 2021 154


PROCEDURE DIVISION

When the access mode is dynamic and records are to


be read sequentially,

READ file-1 NEXT RECORD [INTO iden-1]


[ AT END imperative statement ].

READ rel-file NEXT RECORD INTO WS-REL-REC


AT END GO TO PARA-END.

Dec 7, 2021 155


PROCEDURE DIVISION
For Print Output:

WRITE record-name [FROM iden-1]


[ {BEFORE|AFTER} [ADVANCING]
{ iden-2|int-1 [LINE(S)] |PAGE}].

WRITE my-rec after 1.


WRITE header-rec after PAGE.

Write a record, but Read a file.


After a record is written, the content of the
output record buffer is indeterminate.

Dec 7, 2021 156


PROCEDURE DIVISION
For sequential files:

WRITE record-name [FROM iden-1].


WRITE my-record.
WRITE my-record FROM WS-REC.

For indexed/relative files:

WRITE record-name [FROM iden-1]


INVALID [KEY] imperative statement.
The key must be be set up (value assigned) before
you issue the WRITE command.
Dec 7, 2021 157
PROCEDURE DIVISION
Invalid key condition:
1) When an attempt is made to write beyond defined
file boundary
2) Record (with same key value) already exists
3) In output mode, the key value of the current
record is not greater than previous record

REWRITE record-name [FROM iden-1]


[ INVALID KEY imperative-statement].
Before rewrite, you must read the record.

Dec 7, 2021 158


PROCEDURE DIVISION
DELETE is used for deleting a record.

DELETE file-name [RECORD]


[ INVALID KEY imperative-statement].

Before DELETE, you must read the record.

Dec 7, 2021 159


PROCEDURE DIVISION
Inter-program communication
WORKING-STORAGE. LINKAGE SECTION.
01 PARAM-LIST. 01 LINK-INFO.
05 A PIC X(01). 02 L1 PIC X(5).
05 B PIC X(04). 02 L2 PIC 9(5).
05 C PIC 9(05). ……
……….. ………..
PROCEDURE DIVISION. PROCEDURE DIVISION
……….. USING LINK-INFO.
CALL called-prog …………
USING PARAM-LIST. EXIT PROGRAM.
(or, GOBACK).
Calling Prog Called Prog
PARAM-LIST is just passed onto LINK-INFO as a string. (sizes)
Dec 7, 2021 160
PROCEDURE DIVISION
CALL {identifier-1|literal-1}
USING { [[BY REFERENCE] identifier-2 or OMITTED]
[[ BY CONTENT ] identifier-3
or literal-2 or OMITTED ]
[[ BY VALUE ] iden-4 or lit-3 ]
}
[ RETURNING identifier-5 ]
END-CALL

literal-1 must be a program name (PROG-ID of the


Called program). Similarly, Identifier-1 must contain
the name of the program being called.
Dec 7, 2021 161
PROCEDURE DIVISION
USING – specifies arguments that are passed to the
target or called program.
BY REFERENCE (default) – iden-2 can be a data item
of any level in DATA DIVISION of calling program.
If the called program changes any value in the
LINK-INFO (in our earlier example), the change
will be reflected in the PARAM-LIST. In other
words, both programs share the data.
OMITTED means no argument is passed.
BY CONTENT – calling program is passing only the
contents of the identifier-3/literal-2 to the called
program, which cannot change any variable in the
calling program.
Dec 7, 2021 162
OMITTED means no argument is passed.
PROCEDURE DIVISION

BY VALUE – primarily intended for calling non-Cobol


programs. The value of the arguments are passed
to the called program. The called program can
modify the parameters but the changes do not
affect the arguments since the called program has
access to a temporary copy of the sending data
item. The usage of identifier-4 is binary or floating
point (comp-1 or comp-2) or single-byte
alphanumeric. Literal-5 must be numeric or SPACE
or single-byte alphanumeric.

Dec 7, 2021 163


PROCEDURE DIVISION

RETURNING – The return value of called program is


implicitly stored into identifier-5 which must be
defined in DATA DIVISION of calling program. But
the called program must specify RETURNING
phrase on its procedure division:
PROCEDURE DIVISION USING LINK-INFO
RETURNING identifier-6.
identifier-6 must be defined in the LINKAGE
SECTION of the called program as a either level
01 or 77.
Both identifiers-5 and -6 must have same PIC,
USAGE, SIGN, SYNC etc.
Dec 7, 2021 164
PROCEDURE DIVISION

EXIT PROGRAM.
specifies the end of a called program and returns
control to the calling program.

GOBACK. Similar to “EXIT PROGRAM”.

Note: STOP RUN in a called program will terminate


The run unit.

CANCEL identifier-1 or literal-1.


Identifier-1 or literal-1 must be a program name (as
used in PROG-ID clause). It cancels a called program.
It ensures that when the called program is invoked
next time, a fresh copy of the program will be loaded.
Dec 7, 2021 165
PROCEDURE DIVISION
SORT sd-file ON {ASCENDING | DESCENDING}
KEY data1 [data2…]
[ WITH DUPLICATES IN ORDER]
USING in-file1 [in-file2…]
[ INPUT PROCEDURE [IS] proc1 THRU proc2 ]
GIVING out-file
[ OUTPUT PROCEDURE [IS] proc3 THRU proc4 ] .

Input/output procedure:
para-name1 THRU para-name2 or
section-name1 THRU section-name2

Dec 7, 2021 166


PROCEDURE DIVISION
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT INPFILE ASSIGN TO INFILE.
SELECT SORTEDFILE ASSIGN TO OPFILE.
SELECT SDFILE ASSIGN TO SORTFILE.
DATA DIVISION.
FILE SECTION.
FD INPFILE…….
FD OUTFILE……….
SD SDFILE.
01 SDREC
02 ProvinceCode PIC 9.
02 SalesmanCode PIC 9(5).
02 FILLER PIC X(19).

PROCEDURE DIVISION.
Begin.
SORT SDFILE ON ASCENDING KEY ProvinceCode
DESCENDING KEY SalesmanCode
USING INPFILE
GIVING SORTEDFILE.
. 7,. 2021
Dec . . . . 167
PROCEDURE DIVISION
IN-FILE /IN-REC OUT-FILE /OUT-REC
WORK-FILE (DEFINED IN SD) /SORT-REC
ACCOUNT-STATUS AMOUNT ACCOUNT-NO

PROCEDURE DIVISION.
SORTING SECTION.
PARA-BEGIN.
SORT WORK-FILE ON ASCENDING KEY ACCOUNT-NO
USING IN-FILE INPUT PROCEDURE IS CHECK-STATUS
GIVING OUT-FILE OUTPUT PROCEDURE IS CHECK-AMOUNT.
-INPSTOP RUN.
CHECK-STATUS SECTION. PARA-
OPEN-INPUT. OPEN INPUT IN-FILE.
PARA-READ.
READ IN-FILE AT END GO TO PARA-END-INPUT.
IF ACCOUNT-STATUS = “9” MOVE “A” TO ACCOUNT-STATUS.

RELEASE SORT-REC FROM IN-REC. GO TO PARA-READ.


PARA-END-INPUT. CLOSE IN-FILE.
PARA-EXIT-INPUT. EXIT.
CHECK-AMOUNT SECTION.
PARA-OPEN-OUTPUT.
OPEN OUTPUT OUT-FILE.
CHECK-AND-RETURN.
RETURN WORK-FILE RECORD INTO OUT-REC AT END GO TO P-END.

IF OUT-STATUS = “A” MOVE “9” TO OUT-STATUS. WRITE OUT-REC.

Dec GO TO CHECK-AND-RETURN.
7, 2021 168
P-END. CLOSE OUT-FILE.
Searching Tables

Dec 7, 2021 169


Creating Pre-filled
Tables

A B C D E F G H I J K ...

01
01 LetterTable.
LetterTable.
02
02 TableValues.
TableValues.
03
03 FILLER
FILLER PIC
PIC X(13)
X(13)
VALUE
VALUE ""ABCDEFGHIJKLM".
ABCDEFGHIJKLM
ABCDEFGHIJKLM".
ABCDEFGHIJKLM
03
03 FILLER
FILLER PIC
PIC X(13)
X(13)
VALUE
VALUE ""NOPQRSTUVWXYZ".
NOPQRSTUVWXYZ
NOPQRSTUVWXYZ".
NOPQRSTUVWXYZ
02
02 FILLER
FILLER REDEFINES
REDEFINES TableValues.
TableValues.
03
03 Letter
Letter PIC
PIC XX OCCURS
OCCURS 26
26 TIMES.
TIMES.
Dec 7, 2021 170
Searching a Table

A B C D E F G H I J K L M
1 2 3 4 5 6 7 8 9 10 11 12 13

01
01 LetterTable.
LetterTable.
02
02 TableValues.
TableValues.
03
03 FILLER
FILLER PIC
PIC X(13)
X(13)
VALUE
VALUE "ABCDEFGHIJKLM".
"ABCDEFGHIJKLM".
03
03 FILLER
FILLER PIC
PIC X(13)
X(13)
VALUE
VALUE "NOPQRSTUVWXYZ".
"NOPQRSTUVWXYZ".
02
02 FILLER
FILLER REDEFINES
REDEFINES TableValues.
TableValues.
03
03 Letter
Letter PIC
PIC XX OCCURS
OCCURS 2626 TIMES.
TIMES.
ACCEPT
ACCEPT LetterIn.
LetterIn.
PERFORM
PERFORM VARYING
VARYING Idx
Idx FROM
FROM 11 BY
BY 11 UNTIL
UNTIL
LetterIn
LetterIn EQUAL
EQUAL TO
TO Letter(Idx)
Letter(Idx)
END-PERFORM.
END-PERFORM.
DISPLAY
DISPLAY LetterIn,
LetterIn, "is
"is in
in position
position ", ", Idx.
Idx.
Dec 7, 2021 171
Search Syntax

TableName OCCURS TableSize TIMES


INDEXED BY IndexName

Dec 7, 2021 172


Searching a Two Dimension Table

1 2 3 4
1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 1 2 3 4

01 TimeTable.
02 Day OCCURS 5 TIMES INDEXED BY DayIdx.
03 Hours OCCURS 8 TIMES INDEXED BY HourIdx.
04 Item PIC X(10).
04 Location PIC X(10).

SET DayIdx TO 0.
PERFORM UNTIL MeetingFound OR DayIdx > 5
SET DayIdx UP BY 1
SET HourIdx TO 1
SEARCH Hours WHEN MeetingType = Item(DayIdx, HourIdx)
SET MeetingFound TO TRUE
DISPLAY MeetingType " on " DayIdx " at " HourIdx
END-SEARCH
END-PERFORM.
Dec 7, 2021 173
Search All Syntax

TableName OCCURS TableSize TIMES [ {ASCENDING/DESCENDING}


KEY IS {ElementIdentifier}] [ INDEXED BY {IndexName}]
Dec 7, 2021 174
Using the Search All

A B C D E F G H I J K L M
1 2 3 4 5 6 7 8 9 10 11 12 13
01
01 LetterTable.
LetterTable.
02
02 TableValues.
TableValues.
03
03 FILLER
FILLER PIC
PIC X(13)
X(13)
VALUE
VALUE "ABCDEFGHIJKLM".
"ABCDEFGHIJKLM".
03
03 FILLER
FILLER PIC
PIC X(13)
X(13)
VALUE
VALUE "NOPQRSTUVWXYZ".
"NOPQRSTUVWXYZ".
02
02 FILLER
FILLER REDEFINES
REDEFINES TableValues.
TableValues.
03
03 Letter
Letter PIC
PIC XX OCCURS
OCCURS 26
26 TIMES
TIMES
ASCENDING
ASCENDING KEY
KEY IS
IS Letter
Letter
INDEXED
INDEXED BY
BY LetterIdx.
LetterIdx.
SEARCH
SEARCH ALL
ALL Letter
Letter
WHEN
WHEN Letter(LetterIdx)
Letter(LetterIdx) == LetterIn
LetterIn
DISPLAY
DISPLAY LetterIn,
LetterIn, "is
"is in
in position
position ",
", Idx
Idx
END-SEARCH.
END-SEARCH.
Dec 7, 2021 175
How the Search All works
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

Lower Upper Middle Letter(Middle)

1 26 13 = M
ALGORITHM – Searching for ‘Q’ (say)
Middle = (Lower + Upper) / 2
CASE TRUE
WHEN Letter(Middle) < "Q" THEN Lower = Middle + 1
WHEN Letter(Middle) > "Q" THEN Upper = Middle - 1
WHEN Letter(Middle) = "Q" THEN SET ItemFound TO
TRUE
WHEN Lower > Upper THEN SET ItemNotInTable TO TRUE
Dec 7, 2021 176
Search All Example
01 StateTable.
01 StateTable.
02
02 StateValues.
StateValues.
03
03 FILLER
FILLER PIC
PIC X(20)
X(20) VALUE
VALUE ??????????????
??????????????
PIN
PIN Codes
Codes and
and Names
Names
03
03 FILLER
FILLER PIC
PIC X(20)
X(20) VALUE
VALUE ??????????????
??????????????
02
02 FILLER
FILLER REDEFINES
REDEFINES StateValues.
StateValues.
03
03 States
States OCCURS
OCCURS 50
50 TIMES
TIMES
ASCENDING
ASCENDING KEY
KEY IS
IS StateName
StateName
INDEXED
INDEXED BY
BY StateIdx.
StateIdx.
04
04 PinCode
PinCode PIC
PIC X(6).
X(6).
04
04 StateName
StateName PIC
PIC X(14).
X(14).

SEARCH
SEARCH ALL
ALL States
States
AT
AT END
END DISPLAY
DISPLAY "State
"State not
not found"
found"
WHEN
WHEN StateName(StateIdx)
StateName(StateIdx) == InputName
InputName
MOVE
MOVE PinCode(StateIdx)
PinCode(StateIdx) TO
TO PrintPinCode
PrintPinCode
END-SEARCH.
END-SEARCH.
Dec 7, 2021 177
INSPECT

Dec 7, 2021 178


INSPECT Syntax - Format 1
INSPECT iden-1 TALLYING iden-2 FOR {
{ {ALL|LEADING} [CHARACTERS] {IDEN-3|lit-1} }
[ {BEFORE|AFTER} INITIAL {iden-4|lit-2} ] }.

INSPECT mystring TALLYING tally-1 FOR ALL “ABC”


BEFORE INITIAL “.” AFTER INITIAL “Z”.
Before INSPECT, tally-1 = 3 (say) and
mystring= “bbbBCADABCZPABCABCPQ.”
After INSPECT, mystring remains unchanged and TALLY-1
will be 5 as “ABC” occurs 2 times after first occurrence of Z. (3+2)
INSPECT mystring TALLYING tally-1 FOR CHARACTERS
AFTER INITIAL “Z”.
There are 10 characters after Z. So, TALLY-1 will be 3+10
Dec 7, 2021 179
How the INSPECT works
The INSPECT scans the Source String from left to right
counting and/or replacing characters under the control of
the TALLYING, REPLACING or CONVERTING phrases.

The behavior of the INSPECT is modified by using the


LEADING, FIRST, BEFORE and AFTER phrases.

An ALL LEADING, CHARACTERS, FIRST or REPLACING


phrase may only be followed by one BEFORE and one
AFTER phrase.

CHARACTERS increases the count by 1 for each character


LEADING – search starts from the leading position of

Dec 7, 2021 180


INSPECT Syntax - Format 2
INSPECT iden-1 REPLACING { CHARACTERS BY {iden-2|
lit-2 [ {BEFORE|AFTER} INITIAL {iden-3|lit-3} ] }
{{ALL|LEADING|FIRST } {iden-4|lit-4} BY { iden-5 |
lit-5} [ {BEFORE|AFTER} INITIAL {iden-6|lit-6} ] }.

1) If CHARACTERS is specified, iden-2/lit-2 must be a


single character
2) FIRST – the leftmost occurrence of iden-4 is replaced
3) The size of iden-4 and iden-5 must be equal
4) ALL, LEADING, BEFORE and AFTER phrases have
same meaning as in format-1.

Dec 7, 2021 181


INSPECT Example

INSPECT StringData REPLACING ALL "F" BY "G"


AFTER INITIAL "A" BEFORE INITIAL "Q".

Before

F F F F A F F F X F Q F F F Z

After

F F F F A G G G X G Q F F F Z

Dec 7, 2021 182


INSPECT Example

INSPECT StringData REPLACING LEADING "F" BY "G"


AFTER INITIAL "A" BEFORE INITIAL "Z".

StringData

F F F F A F F F F F Q F F F Z
initial A range of replacing initial Z
Leading F leading-effect-terminates

After

F F F F A G G G G G Q F F F Z

Dec 7, 2021 183


INSPECT Example

INSPECT StringData REPLACING ALL "F" BY "G"


AFTER INITIAL "A" BEFORE INITIAL "Z".

StringData

F F F F A F F F F F Q F F F Z

F F F F A G G G G G Q G G G Z
After

Dec 7, 2021 184


INSPECT Example

INSPECT StringData REPLACING FIRST "F" BY "G"


AFTER INITIAL "A" BEFORE INITIAL "Q".

StringData

F F F F A F F F F F Q F F F Z

After

F F F F A G F F F F Q F F F Z

Dec 7, 2021 185


INSPECT Example

INSPECT StringData REPLACING


ALL "FFFF"
FFFF BY "FROG"
FROG
AFTER INITIAL "A" BEFORE INITIAL "Q".

StringData

F F F F A F F F F F Q F F F Z

After

F F F F A F R O G F Q F F F Z
Dec 7, 2021 186
STRING

Dec 7, 2021 187


STRING Syntax

STRING {iden-1 or lit-1 [ iden|lit-2..]} DELIMITED [BY]


{iden-3|lit-3| SIZE} INTO iden-4
[ WITH POINTER iden-5 ]

77 F1 PIC X(4) VALUE “RAIN”.


STRING “MA” DELIMITED SIZE INTO F1 ==> MAIN

F1: RAIN, F2: bbbb


STRING F1 DELIMITED BY “I” INTO F2 ==> RAbb

Dec 7, 2021 188


How the STRING Works
• The STRING moves characters from the source
string into the destination string from left to right.
But no space filling occurs.

• When there are a number of source strings,


characters are moved from the leftmost source
string first.

• When a WITH POINTER phrase is used its value


determines the starting character position for
insertion into the destination string.

• The ON OVERFLOW clause executes if there are still


valid characters left in the source strings but the
destination string is full.
Dec 7, 2021 189
STRING Example 1

01 DayStr PIC XX. 5


01 MonthStr PIC X(9). J U N E
01 YearStr PIC X(4). 1 9 9 4
01 DateStr PIC X(15) VALUE ALL "-".

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

STRING DayStr DELIMITED BY SPACES


", " DELIMITED BY SIZE
MonthStr DELIMITED BY SPACES
", " DELIMITED BY SIZE
YearStr DELIMITED BY SIZE
INTO DateStr
END-STRING.
Dec 7, 2021 190
STRING Example 1

01 DayStr PIC XX. 5


01 MonthStr PIC X(9). J U N E
01 YearStr PIC X(4). 1 9 9 4
01 DateStr PIC X(15) VALUE ALL "-".

5 - - - - - - - - - - - - - -

STRING DayStr DELIMITED BY SPACES


", " DELIMITED BY SIZE
MonthStr DELIMITED BY SPACES
", " DELIMITED BY SIZE
YearStr DELIMITED BY SIZE
INTO DateStr
END-STRING.
Dec 7, 2021 191
STRING Example 1

01 DayStr PIC XX. 5


01 MonthStr PIC X(9). J U N E
01 YearStr PIC X(4). 1 9 9 4
01 DateStr PIC X(15) VALUE ALL "-".

5 , - - - - - - - - - - - - -

STRING DayStr DELIMITED BY SPACES


", " DELIMITED BY SIZE
MonthStr DELIMITED BY SPACES
", " DELIMITED BY SIZE
YearStr DELIMITED BY SIZE
INTO DateStr
END-STRING.
Dec 7, 2021 192
STRING Example 1

01 DayStr PIC XX. 5


01 MonthStr PIC X(9). J U N E
01 YearStr PIC X(4). 1 9 9 4
01 DateStr PIC X(15) VALUE ALL "-".

5 , J U N E - - - - - - - - -

STRING DayStr DELIMITED BY SPACES


", " DELIMITED BY SIZE
MonthStr DELIMITED BY SPACES
", " DELIMITED BY SIZE
YearStr DELIMITED BY SIZE
INTO DateStr
END-STRING.
Dec 7, 2021 193
STRING Example 1

01 DayStr PIC XX. 5


01 MonthStr PIC X(9). J U N E
01 YearStr PIC X(4). 1 9 9 4
01 DateStr PIC X(15) VALUE ALL "-".

5 , J U N E , - - - - - - - -

STRING DayStr DELIMITED BY SPACES


", " DELIMITED BY SIZE
MonthStr DELIMITED BY SPACES
", " DELIMITED BY SIZE
YearStr DELIMITED BY SIZE
INTO DateStr
END-STRING.
Dec 7, 2021 194
STRING Example 1

01 DayStr PIC XX. 5


01 MonthStr PIC X(9). J U N E
01 YearStr PIC X(4). 1 9 9 4
01 DateStr PIC X(15) VALUE ALL "-".

5 , J U N E , 1 9 9 4 - - - -

STRING DayStr DELIMITED BY SPACES


", " DELIMITED BY SIZE
MonthStr DELIMITED BY SPACES
", " DELIMITED BY SIZE
YearStr DELIMITED BY SIZE
INTO DateStr
END-STRING.
Dec 7, 2021 195
STRING Example 2
01 StringFields.
02 Field1 PIC X(18)
VALUE "Where does this go".
02 Field2 PIC X(30)
VALUE "This is the destination string".
02 Field3 PIC X(15) VALUE "Here is another".
01 StrPointers.
02 StrPtr PIC 99.
02 NewPtr PIC 9.
This is the destination string
STRING Field1 DELIMITED BY SIZE
INTO Field2
END-STRING.
DISPLAY Field2.
Dec 7, 2021 196
STRING Example 2
01 StringFields.
02 Field1 PIC X(18) VALUE "Where does this go".
02 Field2 PIC X(30)
VALUE "This is the destination string".
02 Field3 PIC X(15) VALUE "Here is another".
01 StrPointers.
02 StrPtr PIC 99.
02 NewPtr PIC 9.

Where does this goation string

STRING Field1 DELIMITED BY SIZE


INTO Field2
END-STRING.
DISPLAY Field2.
Dec 7, 2021 197
STRING Example 3
01 StringFields.
02 Field1 PIC X(18) VALUE "Where does this go".
02 Field2 PIC X(30)
VALUE "This is the destination string".
02 Field3 PIC X(15) VALUE "Here is another".
01 StrPointers.
02 StrPtr PIC 99.
02 NewPtr PIC 9.

MOVE 6 TO StrPtr.
STRING Field1, Field3 DELIMITED BY SPACE
INTO Field2 WITH POINTER StrPtr
ON OVERFLOW DISPLAY "String Error"
NOT ON OVERFLOW DISPLAY Field2
END-STRING.

Dec 7, 2021 198


STRING Example 3 (contd.)

THIS I S THE DESTINATION STRING


1 2 3 4 5 6 7 8 …………………..

Where does this go


space
Here is another
Start from 6th position

MOVE 6 TO StrPtr.
STRING Field1, Field3 DELIMITED BY SPACE
INTO Field2 WITH POINTER StrPtr
ON OVERFLOW DISPLAY "String Error"

This WhereHerestination string

Dec 7, 2021 199


UNSTRING

Dec 7, 2021 200


UNSTRING Syntax

UNSTRING iden-1 [ DELIMITED BY [ALL] {iden-2|lit-2}


[ ( OR [ALL] iden-3|lit-3)…] INTO
iden-4 [DELIMITER IN iden-5] [COUNT IN iden-6]
[iden-7 [DELIMITER IN iden-8] [COUNT IN iden-9]
[ WITH POINTER iden-10]
[ TALLYING IN iden-11].

How does it work?


When does it terminate?

Dec 7, 2021 201


How the UNSTRING works

The UNSTRING copies characters from the


Source String to the Destination String until a
Delimiter is encountered in the Source String or the
Destination String is full.

When either of these things happen the next


Destination String becomes the receiving area and
characters are copied into it until it too is full or
another Delimiter is encountered in the Source
String.

Characters are copied from the Source String


to the Destination Strings according to the rules for
Alphanumeric
Dec 7, 2021 moves. There is space filling. 202
UNSTRING Termination

The UNSTRING statement terminates when:-

All the characters in the Source String have been


examined
OR

All the Destination Strings have been processed

OR

Some error condition is encountered.

Dec 7, 2021 203


UNSTRING clauses

• DELIMITED BY
Specifies delimiters within the data that control the
data transfer. If “DELIMITED BY” is not used, then
“DELIMITER IN” and “COUNT IN” must not be used.

• INTO
Specifies the fields where the data is to be moved
(destination or receiving field).

• DELIMITER IN
A DELIMITER IN clause is associated with a
particular Destination String. iden-5 represents the
delimiter receiving field.
Dec 7, 2021 204
UNSTRING clauses
• ON OVERFLOW.
The ON OVERFLOW is activated if :-
• The Unstring pointer (Pointer#i) is not pointing
to a character position within the Source-String
when the UNSTRING executes.
• All the Destination Strings have been processed
but there are still valid unexamined characters
in the Source String.
• COUNT IN
The COUNT IN clause is associated with a
particular Destination String and holds a count of the
number of characters passed to the Destination
String.
• TALLYING IN
Only one TALLYING clause can be used with each
UNSTRING. It holds a count of the number of
Destination Strings affected by the UNSTRING
operation.
Dec 7, 2021 205
The UNSTRING clauses

• WITH POINTER
The value of the pointer field behaves as if it
were increased by 1 for each examined character
in the sending field. After the execution, the
pointer contains a value equal to its initial value
plus the number of characters examined in the
sending field.

• ALL
When the ALL phrase is used, contiguous
delimiters are treated as if only one delimiter had
been encountered.

Dec 7, 2021 206


UNSTRING Example 1

01 DayStr PIC XX.

01 MonthStr PIC XX.

01 YearStr PIC XX.

01 DateStr PIC X(8). 1 9 - 0 5 - 8 0

ACCEPT DateStr.
UNSTRING DateStr
INTO DayStr, MonthStr, YearStr
ON OVERFLOW DISPLAY "Chars Left"
END-UNSTRING.
display device

Dec 7, 2021 207


UNSTRING Example 1

01 DayStr PIC XX. 1 9


01 MonthStr PIC XX.

01 YearStr PIC XX.

01 DateStr PIC X(8). 1 9 - 0 5 - 8 0

ACCEPT DateStr.
UNSTRING DateStr
INTO DayStr, MonthStr, YearStr
ON OVERFLOW DISPLAY "Chars Left"
END-UNSTRING.

Dec 7, 2021 208


UNSTRING Example 1

01 DayStr PIC XX. 1 9


01 MonthStr PIC XX. - 0
01 YearStr PIC XX.

01 DateStr PIC X(8). 1 9 - 0 5 - 8 0

ACCEPT DateStr.
UNSTRING DateStr
INTO DayStr, MonthStr, YearStr
ON OVERFLOW DISPLAY "Chars Left"
END-UNSTRING.

Dec 7, 2021 209


UNSTRING Example 1

01 DayStr PIC XX. 1 9


01 MonthStr PIC XX. - 0
01 YearStr PIC XX. 5 -
01 DateStr PIC X(8). 1 9 - 0 5 - 8 0

ACCEPT DateStr.
UNSTRING DateStr
INTO DayStr, MonthStr, YearStr
ON OVERFLOW DISPLAY "Chars Left"
END-UNSTRING.

Dec 7, 2021 210


UNSTRING Example 1

01 DayStr PIC XX. 1 9


01 MonthStr PIC XX. - 0
01 YearStr PIC XX. 5 -
01 DateStr PIC X(8). 1 9 - 0 5 - 8 0

ACCEPT DateStr.
UNSTRING DateStr
INTO DayStr, MonthStr, YearStr
ON OVERFLOW DISPLAY "Chars Left"
END-UNSTRING.
Chars
Chars Left
Left

Dec 7, 2021 211


UNSTRING Example

01 DayStr PIC XX. (1) 19

01 MonthStr PIC XX. (2) 05

01 YearStr PIC XX. (3) 80


01 DateStr PIC X(8).

1 9 s t o p 0 5 s t o p 8 0
No overflow

ACCEPT DateStr.
UNSTRING DateStr DELIMITED BY "stop"
INTO DayStr, MonthStr, YearStr
ON OVERFLOW DISPLAY "Chars Left"
END-UNSTRING.

Dec 7, 2021 212


UNSTRING Example

01 DayStr PIC XX. (1) 19

01 MonthStr PIC XX. (2) 05

01 YearStr PIC XX. (3) 80

01 DateStr PIC X(8). 1 9 - 0 5 / 8 0


(4) 19b05b80
(5) –b/
ACCEPT DateStr.
UNSTRING DateStr
DELIMITED BY "/" OR "-"
INTO DayStr DELIMITER IN Hold1
MonthStr DELIMITER IN Hold2
YearStr
END-UNSTRING.
DISPLAY DayStr SPACE MonthStr SPACE YearStr.
DISPLAY Hold1 SPACE Hold2
Dec 7, 2021 213
UNSTRING Example

77 F4 PIC X(15) VALUE “ABCDEFGCCHIJKCL”.


77 F1 PIC X(5) ABbbb ABbbb
77 F2 PIC X(5) DEFGb DEFGb
77 F3 PIC X(5). Bbbbb HIJKb

Q1. What’s wrong in above codes?


Q2. UNSTRING F4 DELIMITED BY “C"
INTO F1 F2 F3.
Q3. UNSTRING F4 DELIMITED BY ALL “C"
INTO F1 F2 F3.

Ans2. The first of the two C’s will terminate


in F2 (DEFGb). The second “C” will cause
F3 to be space-filled.

Dec 7, 2021 214


UNSTRING Example
77 F4 PIC X(12) VALUE “12/345/678/9”.
77 F1 PIC X(3) 12b
77 F2 PIC 9(4) 0345 since it is numeric
77 F3 PIC X(3). 678b
K1, K2, K3 are numeric fields containing 0.
D1, D2, D3 are PIC X.

Q. UNSTRING F4 DELIMITED BY “/"


INTO F1 DELIMITER IN D1 COUNT IN K1
F2 DELIMITER IN D2 COUNT IN K2
F3 DELIMITER IN D3 COUNT IN K3

D1, D2 & D3 will contain “/”


K1=2, K2=3 & K4=3 [no.of characters moved

Dec 7, 2021 215


UNSTRING Example
77 F5 X(26) VALUE “THEREbbMAY-BE-SOMEbbERRORb”
77 F1 X(6) THEREb D1=b C1=5
77 F2 X(6) MAYbbb D2=- C2=3
77 F3 X(6) BEbbbb D3=- C3=2
77 F4 X(6) SOMEbb D4=b C4=4
C1, C2, C3, C4, T are PIC 9, value 0.
D1, D2, D3, D4 are PIC X.
Q. UNSTRING F4 DELIMITED BY “-” OR ALL “b”
INTO F1 DELIMITER IN D1 COUNT IN C1
F2 DELIMITER IN D2 COUNT IN C2
F3 DELIMITER IN D3 COUNT IN C3
F4 DELIMITER IN D4 COUNT IN C4
TALLYING T
ON OVERFLOW PERFORM ERROR-ROUTINE.

T is set to 4 [no. of data receiving areas


acted upon : 1 for each activated field
Since there some characters in F5, overflow
occurs and ERROR-ROUTINE will be performed
Dec 7, 2021 216
COMPILER DIRECTING STATEMENTS
COPY literal-1 [ {OF|IN} library-name]
REPLACING iden-1 by iden-2 [iden-3 BY iden4..]
copy-library. Compiler copies the text from the
library onto the body of your source program.

EJECT. For printing the next source line at the top of


next page (compiler listing). This must be the
only statement on the line.

SKIP1/2/3. Number of blank lines to be printed in the


compiler listing.

TITLE literal. Title to be printed on top of every page


of the compiler listing.
Dec 7, 2021 217
RESERVED WORDS

Some words (with specific spelling) have been kept


reserved for specific purpose and they cannot be used
for any other purpose.
e.g., ADD, MOVE, COPY etc. etc.

Note:
ADD is a reserved word. But ADD1 or ADD-1 is not.

Dec 7, 2021 218


SPECIAL REGISTERS
Special registers are reserved storage areas (for
Specific purposes) provided by the compiler. Register
names are reserved words. You should not define them
in your program. They are already available to your
program.

DEBUG-ITEM a group item (consisting of elementary


items DEBUG-LINE, DEBUG-NAME etc.)

LENGTH OF contains no. of bytes in an identifier


MOVE LENGTH OF A TO B.

SORT-RETURN contains 0, if sorting is successful


Dec 7, 2021
otherwise 16. 219
SPECIAL REGISTERS
TALLY an elementary item, PIC 9(5) COMP.
This can be used for any purpose.

WHEN-COMPILED contains date and time


when compilation started.
MM/DD/YYhh.mm.ss - X(16)

Dec 7, 2021 220


Intrinsic Functions
Format to use: FUNCTION fn-name [arguments]
Example:
COMPUTE RSLT = FUNCTION COS(N1)
DISPLAY FUNCTION MAX(F1 F2 F3…F9)
COMPUTE MAXVAL = FUNCTION MAX(MYTAB(ALL ALL))

Some useful functions are:


CURRENT-DATE LENGTH LOG LOWER-CASE
MAX MEAN MIN REM (remainder)
UPPER-CASE SUM COS ACOS
SQRT ASIN SIN FACTORIAL
Etc. etc.
Dec 7, 2021 221
COMPILER OPTIONS

While compiling a program, you can specify your


options through parameters
1) COMPILE/NOCOMPILE (C/NOC)
2) OBJECT/NOOBJECT (OBJ/NOOBJ)
3) ADV/NOADV (def. ADV). If NOADV, print control
characters are to be manipulated by
the program.
4) DATA(24)/DATA(31) (def> 31)
5) OPTIMIZE/NOOPTIMIZE (OPT/NOOPT)
6) LIST/NOLIST for m/c level codes
7) MAP/NOMAP
8) SOURCE/NOSOURCE (S/NOS) – source listing
Dec 7, 2021 222
COMPILER OPTIONS

9) SSRANGE/NOSSRANGE (SSR/NOSSR) for


checking range of subscripted fields
10) NUMBER/NONUMBER sequence check (cc.1-6)
11) SEQ/NOSEQ - for generating source seq. numbers
12) XREF/NOXREF for cross-reference list
13) QUOTE/APOST
14) LIB/NOLIB copy library
Etc. etc..

Dec 7, 2021 223


Program Development

Source
Program List
Copy
Compiler
Libraries

Object Module
LE Output
Object
Link editor
Libraries

Load Module
Appln. O/P
Appln.
Dec 7, 2021
Data Application Program 224
The End
Thank You

and

Best of Luck

Dec 7, 2021 225

You might also like