0% found this document useful (0 votes)
218 views

Cobol Complete Reference

COBOL is one of the oldest computer languages in use. As a result it has some idiosyncrasies which programmers may find irritating. Some implementations require the program text to adhere to certain, archaic, formatting restrictions.

Uploaded by

John Felix
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 PPS, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
218 views

Cobol Complete Reference

COBOL is one of the oldest computer languages in use. As a result it has some idiosyncrasies which programmers may find irritating. Some implementations require the program text to adhere to certain, archaic, formatting restrictions.

Uploaded by

John Felix
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 PPS, PDF, TXT or read online on Scribd
You are on page 1/ 635

IBMMAINFRAMES.

com
With

DEXTRA University
Presents

COBOL – Complete Reference

1
Introductio
n to
COBOL

2
COBOL
 COBOL is an acronym which stands for
Common Business Oriented Language.
 The name indicates the target area of COBOL applications.
 COBOL is used for developing business, typically file-oriented,
applications.
 It is not designed for writing systems programs. You would not
develop an operating system or a compiler using COBOL.
 COBOL is one of the oldest computer languages in use (it was
developed around the end of the 1950s). As a result it has some
idiosyncrasies which programmers may find irritating.

3
COBOL idiosyncrasies
 One of the design goals was to make the language as
English-like as possible. As a consequence
– the COBOL reserved word list is quite extensive and contains
hundreds of entries.
– COBOL uses structural concepts normally associated with English
prose such as section, paragraph, sentence and so on.
As a result COBOL programs tend to be verbose.
 Some implementations require the program text to adhere to
certain, archaic, formatting restrictions.
 Although modern COBOL has introduced many of the
constructs required to write well structured programs it also
still retains elements which, if used, make it difficult, and in
some cases impossible, to write good programs.
4
Notation
 Words in uppercase are reserved words.
– When underlined they must be present when the operation of which
they are a part is used.
– When they are not underlined the used for readability only and are
optional. If used they must be spelt correctly.
 Words in mixed case represent names which will be devised
by the programmer.
 When material is enclosed in braces { } a choice must be
made from the options within the braces.
 Material is enclosed in square brackets [ ] indicates that the
material is an option which may be included or omitted as
required.
 The ellipsis symbol ‘...’ indicates that the preceding syntax
element may be repeated at the programmer’s discretion.

5
Structure of COBOL programs.

Program
Program
Divisions

Section(s)

Paragraph(s)

Sentence(s)

Statement(s)
6
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.
7
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.

8
COBOL Program Text Structure
IDENTIFICATION DIVISION.
Program Details
NNOTE
OTE
The
Thekeyword
DATA DIVISION. DIVISION
keyword
DIVISIONand andaa
‘full-stop’
‘full-stop’isisused
usedinin
Data Descriptions every
everycase.
case.

PROCEDURE DIVISION.
Algorithm Description

9
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.

10
The IDENTIFICATION DIVISION Syntax.
 The IDENTIFICATION DIVISION has the following
structure
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.

11
The IDENTIFICATION DIVISION Syntax.
 The IDENTIFICATION DIVISION has the following
structure
IDENTIFICATION DIVISION.
PROGRAM-ID. NameOfProgram.
[AUTHOR. YourName.]

$$ SET
SET SOURCEFORMAT"FREE"
SOURCEFORMAT"FREE"
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID.
PROGRAM-ID. SequenceProgram.
SequenceProgram.
AUTHOR.
AUTHOR. Michael
Michael Coughlan.
Coughlan.
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.

12
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.
 The WORKING-STORAGE SECTION is used to
describe the general variables used in the program.

13
DATA DIVISION Syntax
 The DATA DIVISION has the following
structure
DATA DIVISION.
FILE SECTION. 
 
 File Se ction entr ies.
 WORKING -STORAGE SECTION.
 
 WS entr ies. 

$$ SET
SET SOURCEFORMAT"FREE"
SOURCEFORMAT"FREE"
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID. Sequence-Program.
PROGRAM-ID. Sequence-Program.
AUTHOR.
AUTHOR. Michael
Michael Coughlan.
Coughlan.
DATA
DATA DIVISION.
DIVISION.
WORKING-STORAGE
WORKING-STORAGE SECTION.
SECTION.
01 Num1
01 Num1 PIC
PIC 99 VALUE
VALUE ZEROS.
ZEROS.
01
01 Num2
Num2 PIC
PIC 99 VALUE
VALUE ZEROS.
ZEROS.
01 Result
01 Result PIC 99 VALUE ZEROS.
PIC 99 VALUE ZEROS.14
DIVISION.
 The PROCEDURE DIVISION is where all the data described
in the DATA DIVISION is processed and produced. 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, sentence and 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.

15
Section
s
 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.
– SelectUlsterRecords SECTION.
– FILE SECTION.
16
s
 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.
17
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 .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
18
A Full COBOL program.
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID.
PROGRAM-ID. SequenceProgram.
SequenceProgram.
AUTHOR.
AUTHOR. Michael Coughlan.
Michael Coughlan.
DATA
DATA DIVISION.
DIVISION.
WORKING-STORAGE
WORKING-STORAGE SECTION.
SECTION.
01 Num1
01 Num1 PIC
PIC 99 VALUE
VALUE ZEROS.
ZEROS.
01
01 Num2
Num2 PIC
PIC 99 VALUE
VALUE ZEROS.
ZEROS.
01
01 Result
Result PIC
PIC 99
99 VALUE
VALUE ZEROS.
ZEROS.
PROCEDURE
PROCEDURE DIVISION.
DIVISION.
CalculateResult.
CalculateResult.
ACCEPT
ACCEPT Num1.
Num1.
ACCEPT
ACCEPT Num2.
Num2.
MULTIPLY
MULTIPLY Num1
Num1 BY
BY Num2
Num2 GIVING
GIVING
Result.
Result.
DISPLAY
DISPLAY "Result
"Result isis == ",
", Result.
Result.
STOP
STOP RUN.
RUN.
19
The minimum COBOL program.

IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID.
PROGRAM-ID. SmallestProgram.
SmallestProgram.
PROCEDURE
PROCEDURE DIVISION.
DIVISION.
DisplayPrompt.
DisplayPrompt.
DISPLAY
DISPLAY "I
"I did
did it".
it".
STOP
STOP RUN.
RUN.

20
COBOL
Basics 1

21
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.
 In Microfocus COBOL the compiler directive
$ SET SOURCEFORMAT"FREE" frees us from all formatting
restrictions.

22
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.
 In Microfocus COBOL the compiler directive
$ SET SOURCEFORMAT"FREE" frees us from all formatting
restrictions.
$$ SET
SET SOURCEFORMAT"FREE"
SOURCEFORMAT"FREE"
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 23
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, 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.

24
Describing DATA.
There are basically three kinds of data used in COBOL
programs;

ŒVariables.
Literals.
ŽFigurative Constants.

Unlike other programming languages, COBOL does not support user


defined constants.

25
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.

26
Using Variables
01 StudentName PIC X(6) VALUE SPACES.
MOVE "JOHN" TO StudentName.
DISPLAY "My name is ", StudentName.

StudentName

27
Variables
01 StudentName PIC X(6) VALUE SPACES.
MOVE "JOHN" TO StudentName.
DISPLAY "My name is ", StudentName.

StudentName

J O H N

28
Variables
01 StudentName PIC X(6) VALUE SPACES.
MOVE "JOHN" TO StudentName.
DISPLAY "My name is ", StudentName.

StudentName
J O H N My name is JOHN

29
COBOL Data Types
 COBOL is not a “typed” language and the distinction
between some of the data types available in the language is a
little blurred.
 For the time being we will focus on just two data types,
– numeric
– text or string

 Data type is important because it determines the operations


which are valid on the type.
 COBOL is not as rigorous in the application of typing rules as
other languages.
For example, some COBOL “numeric” data items may, from time to
time, have values which are not “numeric”!
30
Quick Review of “Data Typing”
 In “typed” languages simply specifying the type of a data item
provides quite a lot of information about it.
 The type usually determines the range of values the data item
can store.
– For instance a CARDINAL item can store values between 0..65,535
and an INTEGER between -32,768..32,767

 From the type of the item the compiler can establish how
much memory to set aside for storing its values.
 If the type is “REAL” the number of decimal places is
allowed to vary dynamically with each calculation but the
amount of the memory used to store a real number is fixed.

31
COBOL data description.

 Because COBOL is not typed it employs a different


mechanism for describing the characteristics of the data
items in the program.
 COBOL uses what could be described as a “declaration by
example” strategy.
 In effect, the programmer provides the system with an
example, or template, or PICTURE of what the data item
looks like.
 From the “picture” the system derives the information
necessary to allocate it.

32
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 can
only appear at the beginning of a picture.
33
COBOL ‘PICTURE’
Clauses
 Some examples
– PICTURE 999 a three digit (+ive only) integer
– PICTURE S999 a three digit (+ive/-ive) integer
– PICTURE XXXX a four character text item or string
– PICTURE 99V99 a +ive ‘real’ in the range 0 to 99.99
– PICTURE S9V9 a +ive/-ive ‘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.

34
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

35
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.
01 VatRate PIC V99 VALUE .18.
01 StudentName PIC X(10)VALUE SPACES.
DATA
Num1
Num1 VatRate
VatRate StudentName
StudentName
000 .18 36
000 .18
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
37
Figurative
Constants
 COBOL provides its own, special constants
called Figurative Constants.
SPACE
SPACEororSPACES
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
ALL
ALLliteral
literal == Fill
FillWith
WithLiteral
Literal

38
Figurative Constants - Examples
01
01 GrossPay
GrossPay PICPIC 9(5)V99
9(5)V99 VALUE
VALUE 13.5.
13.5.
ZERO
MOVE
MOVE ZEROS TO
TO GrossPay.
GrossPay.
ZEROES

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
TO StudentName.
StudentName.

StudentName
M I K E 
39
Figurative Constants - Examples
01
01 GrossPay
GrossPay PICPIC 9(5)V99
9(5)V99 VALUE
VALUE 13.5.
13.5.
ZERO
MOVE
MOVE ZEROS TO
TO GrossPay.
GrossPay.
ZEROES

GrossPay

0 0 0 0 0 0
0

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

MOVE
MOVE ALL
ALL "-"
"-" TO
TO StudentName.
StudentName.

StudentName
- - - - - - - - - - 40
Editing, Checking, Compiling,
Running

41
PROCO Menus
PROCO 1 - Menu ALT key PROCO 2 - Alt Menu
PROCO 1 - Menu PROCO 2 - Alt Menu
F1=help F2=edit F3=check F4=animate F1=help F2=screens F7=link F10=CoWriter
F1=help F2=edit F3=check F4=animate F1=help F2=screens F7=link F10=CoWriter
F5=compile F6=run F7=library F8=build
F5=compile F6=run F7=library F8=build
F10=directory CTRL key PROCO 3 - Ctrl Menu
F10=directory PROCO 3 - Ctrl Menu
F1=help F3=update-menu F4=UseUpdatedMenu
F1=help F3=update-menu F4=UseUpdatedMenu
F5=batch-files F7=OS-command F8=config
F5=batch-files F7=OS-command F8=config
F10=user-menu
F10=user-menu

EDIT 1 -Menu ALT key EDIT 2 - Alt Menu


EDIT 1 -Menu EDIT 2 - Alt Menu
F1=help F2=COBOL F3=InsertLine F1=help F2=library F3=load-file F4=save-
F1=help F2=COBOL F3=InsertLine F1=help F2=library F3=load-file F4=save-
F4=DeleteLine F5=RepeatLine F6=RestoreLine file F5=split-line F6=join-line F7=print
F4=DeleteLine F5=RepeatLine F6=RestoreLine file F5=split-line F6=join-line F7=print
F7=RetypeChar F8=RestoreChar F8=calculate F9=untype-word-left
F7=RetypeChar F8=RestoreChar F8=calculate F9=untype-word-left
F9=WordLeft F10=WordRight F10=DeleteWord
F9=WordLeft F10=WordRight F10=DeleteWord
CTRL key EDIT 3 - Ctrl Menu
EDIT 3 - Ctrl Menu
F1=help F2=find F3=block F4=clear
F1=help F2=find F3=block F4=clear
F5=margins F6=draw/forms F7=tags
COBOL menu F5=margins F6=draw/forms F7=tags
COBOL menu F8=WordWrap F9=window F10=scroll
F1=help F2=check/animate F3=cmd-file F8=WordWrap
<-/-> (move in window) F9=window F10=scroll
Home/End (of text) PgUp/PgDn
F1=help F2=check/animate F3=cmd-file <-/-> (move in window) Home/End (of text) PgUp/PgDn
F7=locate-previous F8=locate-next
F7=locate-previous F8=locate-next
F9=locate-current
F9=locate-current
Animate-Menu
Animate-Menu
F1=help F2=view F3=align F4=exchange
F1=help F2=view F3=align F4=exchange
Checker Menu F5=where F6=look-up F9/F10=word-</>
Checker Menu F5=where
Escape F6=look-up
Animate Step Wch Go ZoomF9/F10=word-</>
nx-If Prfm Rst Brk Env
F1=help F2=check/anim F3=pause Escape AnimateQury
Step Find
Wch Locate
Go Zoom
Txtnx-If
Do Prfm Rst Brk Env
F1=help F2=check/anim F3=pause Qury Find Locate Txt Do
F4=list F6=lang F7=ref F9/F10=directives 42
F4=list F6=lang F7=ref F9/F10=directives
COBOL
Basics
2

43
Items/Records
WORKING-STORAGE
WORKING-STORAGE SECTION.
SECTION.
01
01 StudentDetails
StudentDetails PIC
PIC X(26).
X(26).

StudentDetails
H E N N E S S Y R M 9 2 3 0 1 6 5 L M 5 1 0 5 5 0 F

44
Group Items/Records
WORKING-STORAGE
WORKING-STORAGE SECTION.
SECTION.
01
01 StudentDetails.
StudentDetails.
02
02 StudentName
StudentName PIC
PIC X(10).
X(10).
02
02 StudentId
StudentId PIC
PIC 9(7).
9(7).
02 CourseCode
02 CourseCode PIC X(4).
PIC X(4).
02 Grant
02 Grant PIC
PIC 9(4).
9(4).
02
02 Gender
Gender PIC
PIC X.
X.

StudentDetails
H EN N E S S Y RM 9 2 3 0 1 6 5 L M 5 1 0 5 5 0 F
StudentName StudentId CourseCode Grant Gender

45
Group Items/Records
WORKING-STORAGE
WORKING-STORAGE SECTION.
SECTION.
01
01 StudentDetails.
StudentDetails.
02
02 StudentName.
StudentName.
03
03 Surname
Surname PIC
PIC X(8).
X(8).
03 Initials
03 Initials PIC XX.
PIC XX.
02 StudentId
02 StudentId PIC
PIC 9(7).
9(7).
02
02 CourseCode
CourseCode PIC
PIC X(4).
X(4).
02 Grant
02 Grant PIC 9(4).
PIC 9(4).
02
02 Gender
Gender PIC
PIC X.
X.

StudentDetails
H EN N E S S Y RM 9 2 3 0 1 6 5 L M 5 1 0 5 5 0 F
StudentName StudentId CourseCode Grant Gender
Surname Initials

46
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.

47
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 01
01 StudentDetails.
01 StudentDetails.
StudentDetails. StudentDetails.
05
02
02 StudentName.
StudentName. 05 StudentName.
StudentName.
10
10 Surname PIC
03
03 Surname
03 Surname
Initials
PIC
PIC X(8).
PIC X(8).
XX. 10 Surname
Initials PIC X(8).
PIC X(8).
XX.
02 03 Initials
StudentId
02 CourseCode
StudentId
PIC
PIC XX.
9(7).
PIC X(4).
9(7). = 05 10 Initials
StudentId
05 CourseCode
StudentId
PIC
PIC XX.
9(7).
PIC X(4).
9(7).
02 PIC 05 PIC
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.48
Group and elementary items.
 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.

 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,
 a data name
 picture clause.
An elementary item must have a picture clause.
 Every group or elementary item declaration must be followed by a full
stop.
49
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.
 An X picture is the only one which could support such
collections.

50
Assignment in COBOL
 In “strongly typed” languages like Modula-2, Pascal or ADA
the assignment operation is simple because assignment is
only allowed between data items with compatible types.
 The simplicity of assignment in these languages is achieved
at the “cost” of having a large number of data types.
 In COBOL there are basically only three data types,
 Alphabetic (PIC A)
 Alphanumeric (PIC X)
 Numeric (PIC 9)

 But this simplicity is achieved only at the cost of having a


very complex assignment statement.
 In COBOL assignment is achieved using the MOVE verb.
51
The MOVE Verb
 Identifier
MOVE   TO { Identifier} ...
 Literal 

 The MOVE copies data from the source identifier or literal to one or
more destination identifiers.
 The source and destination identifiers can be group or elementary data
items.
 When the destination item is alphanumeric or alphabetic (PIC X or A)
data is copied into the destination area from left to right with space
filling or truncation on the right.
 When data is MOVEd into an item the contents of the item are
completely replaced. If the source data is too small to fill the destination
item entirely the remaining area is zero or space filled.

52
MOVE-ing
Data

MOVE
MOVE “RYAN”
“RYAN” TO
TO Surname.
Surname.
MOVE
MOVE “FITZPATRICK”
“FITZPATRICK” TOTO Surname.
Surname.

01 Surname PIC X(8).

C O U G H L A N

53
MOVEing
Data

MOVE
MOVE “RYAN”
“RYAN” TO
TO Surname.
Surname.
MOVE
MOVE “FITZPATRICK”
“FITZPATRICK” TOTO Surname.
Surname.

01 Surname PIC X(8).

R Y A N

54
MOVEing Data

MOVE
MOVE “RYAN”
“RYAN” TO
TO Surname.
Surname.
MOVE
MOVE “FITZPATRICK”
“FITZPATRICK” TOTO Surname.
Surname.

01 Surname PIC X(8).

F I T Z P A T R I C K

55
MOVEing to a numeric item.
 When the destination item is numeric, or edited numeric, then data is
aligned along the decimal point with zero filling or truncation as
necessary.

 When the decimal point is not explicitly specified in either the source
or destination items, the item is treated as if it had an assumed
decimal point immediately after its rightmost character.

56
01 GrossPay PIC 9(4)V99.

GrossPay
MOVE ZEROS TO GrossPay. 0 0 0 0 0 0


GrossPay
MOVE 12.4 TO GrossPay. 0 0 1 2 4 0


GrossPay
MOVE 123.456 TO GrossPay. 0 1 2 3 4 5 6


GrossPay
MOVE 12345.757 TO GrossPay. 1 2 3 4 5 7 5 7

57
01 CountyPop PIC 999.
01 Price PIC 999V99.
CountyPop
MOVE 1234 TO CountyPop. 1 2 3 4


CountyPop
MOVE 12.4 TO CountyPop.
0 1 2 4


Price
MOVE 154 TO Price. 1 5 4 0 0


Price
MOVE 3552.75 TO Price. 3 5 5 2 7 5

58
Legal MOVEs
Certain combinations of sending and receiving
data types are not permitted (even by COBOL).

59
The DISPLAY Verb
 Identifier    Identifier  
DISPLAY      ...
 Literal    Literal  
[ UPON Mnemonic - Name] [ WITH NO ADVANCING]

 From time to time it may be useful to display messages and


data values on the screen.
 A simple DISPLAY statement can be used to achieve this.
 A single DISPLAY can be used to display several data items
or literals or any combination of these.
 The WITH NO ADVANCING clause suppresses the
carriage return/line feed.

60
The ACCEPT
verb
Format 1. ACCEPT Identifier [ FROM Mnemonic - name]
 DATE 
 DAY 
Format 2. ACCEPT Identifier FROM  
 DAY - OF - WEEK 
 TIME 

01
01 CurrentDate
CurrentDate PIC
PIC 9(6).
9(6).
* YYMMDD
* YYMMDD
01
01 DayOfYear
DayOfYear PIC
PIC 9(5).
9(5).
* YYDDD
* YYDDD
01
01 Day0fWeek
Day0fWeek PIC
PIC 9.
9.
* D (1=Monday)
* D (1=Monday)
01
01 CurrentTime
CurrentTime PIC
PIC 9(8).
9(8).
* HHMMSSss
* HHMMSSss s = S/100
s = S/100

61
$ SET SOURCEFORMAT"FREE"
$ SET SOURCEFORMAT"FREE"
IDENTIFICATION DIVISION.
IDENTIFICATION DIVISION.
PROGRAM-ID. AcceptAndDisplay.
PROGRAM-ID. AcceptAndDisplay.
AUTHOR. Michael Coughlan.
AUTHOR. Michael Coughlan.
Run of Accept and Display program DATA DIVISION.
DATA DIVISION. SECTION.
WORKING-STORAGE
Enter student details using template below WORKING-STORAGE SECTION.
Enter student details using template below 01 StudentDetails.
NNNNNNNNNNSSSSSSSCCCCGGGGS 0102
StudentDetails.
StudentName.
NNNNNNNNNNSSSSSSSCCCCGGGGS 02 03StudentName.
COUGHLANMS9476532LM511245M Surname PIC X(8).
COUGHLANMS9476532LM511245M 03Initials
03 Surname PICXX.
PIC X(8).
Name is MS COUGHLAN 03 Initials
02 StudentId PIC9(7).
PIC XX.
Name is MS COUGHLAN 02 CourseCode
StudentId PICX(4).
9(7).
Date is 24 01 94 02 PIC
Date is 24 01 94 02 Grant
02 CourseCode PIC9(4).
PIC X(4).
Today is day 024 of the year 02 Grant
02 Gender PIC 9(4).
PIC X.
Today is day 024 of the year 02 Gender PIC X.
The time is 22:23
The time is 22:23 01 CurrentDate.
0102
CurrentDate.
CurrentYear PIC 99.
02 CurrentMonth
02 CurrentYear PIC99.
PIC 99.
02 CurrentMonth
02 CurrentDay PIC 99.
PIC 99.
02 CurrentDay PIC 99.
01 DayOfYear.
0102
DayOfYear.
FILLER PIC 99.
02 YearDay
02 FILLER PIC9(3).
PIC 99.
02 YearDay PIC 9(3).
01 CurrentTime.
0102
CurrentTime.
CurrentHour PIC 99.
02 CurrentMinute
02 CurrentHour PIC99.
PIC 99.
02 CurrentMinute
02 FILLER PIC 99.
PIC 9(4).
PROCEDURE DIVISION. 02 FILLER PIC 9(4).
PROCEDURE DIVISION.
Begin.
Begin.
DISPLAY "Enter student details using template below".
DISPLAY"NNNNNNNNNNSSSSSSSCCCCGGGGS
DISPLAY "Enter student details using template below". ".
DISPLAY "NNNNNNNNNNSSSSSSSCCCCGGGGS
ACCEPT StudentDetails. ".
ACCEPT StudentDetails.
ACCEPT CurrentDate FROM DATE.
ACCEPT DayOfYear
ACCEPT CurrentDateFROMFROM
DAY.DATE.
ACCEPT DayOfYear FROM
ACCEPT CurrentTime FROM TIME.DAY.
ACCEPT "Name
DISPLAY CurrentTime FROM TIME.
is ", Initials SPACE Surname.
DISPLAY"Date
DISPLAY "Nameisis"", Initials SPACE
CurrentDay SPACE Surname.
CurrentMonth SPACE CurrentYear.
DISPLAY "Today is day " YearDaySPACE
DISPLAY "Date is " CurrentDay " of CurrentMonth
the year". SPACE CurrentYear.
DISPLAY "Today is day " YearDay " of the year".
DISPLAY "The time is " CurrentHour ":" CurrentMinute.
DISPLAY
STOP RUN."The time is " CurrentHour ":" CurrentMinute.
STOP RUN. 62
ALGORIT
HMS

63
IDENTIFICATION DIVISION.
PROGRAM-ID. FragmentA.
FragmentA DATA
AUTHOR. Michael Coughlan. Num1
Num1 Num2
Num2 Result
Result
00 00 00
00
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.
Calc-Result
ACCEPT Num1.
MULTIPLY Num1 BY Num2 GIVING Result.
ACCEPT Num2.
DISPLAY "Result is = ", Result.
STOP RUN.

64
IDENTIFICATION DIVISION.
PROGRAM-ID. FragmentA. DATA
AUTHOR. Michael Coughlan. Num1
Num1 Num2
Num2 Result
Result
99 00 00
00
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.
ACCEPT Num1.
Num1
MULTIPLY Num1 BY Num2 GIVING Result.
ACCEPT Num2.
DISPLAY "Result is = ", Result.
STOP RUN.

65
IDENTIFICATION DIVISION.
DATA
PROGRAM-ID. FragmentA.
Num1
Num1 Num2
Num2 Result
AUTHOR. Michael Coughlan. Result
99 00 00
00
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.
ACCEPT Num1.
MULTIPLY Num1 BY Num2 GIVING Result.
Result
ACCEPT Num2.
DISPLAY "Result is = ", Result.
STOP RUN.

66
IDENTIFICATION DIVISION.
PROGRAM-ID. FragmentA. DATA
AUTHOR. Michael Coughlan. Num1
Num1 Num2
Num2 Result
Result
00 55 00
00
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.
ACCEPT Num1.
MULTIPLY Num1 BY Num2 GIVING Result.
ACCEPT Num2.
Num2
DISPLAY "Result is = ", Result.
STOP RUN.

67
IDENTIFICATION DIVISION.
PROGRAM-ID. FragmentA.
DATA
AUTHOR. Michael Coughlan.
Num1
Num1 Num2
Num2 Result
Result
DATA DIVISION. 99 55 00
00
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.
ACCEPT Num1.
MULTIPLY Num1 BY Num2 GIVING Result.
ACCEPT Num2.
DISPLAY "Result is = ", Result.
Result
STOP RUN.

68
Programs are written using three
main programming constructs.
constructs

 Sequence.

 Selection.

 Iteration.

69
IDENTIFICATION DIVISION. DATA
PROGRAM-ID. Selection-Program.
Selection-Program
Num1
Num1 Num2
Num2 Result
Result Operator
Operator
AUTHOR. Michael Coughlan.
00 00 00
00 __
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Num1 PIC 9 VALUE ZEROS.
01 Num2 PIC 9 VALUE ZEROS.
01 Result PIC 99 VALUE ZEROS.
01 Operator PIC X VALUE SPACE.

PROCEDURE DIVISION.
Calculator.
Calculator
ACCEPT Num1.
ACCEPT Num2.
ACCEPT Operator
IF Operator = "+" THEN
ADD Num1, Num2 GIVING Result
END-IF
IF Operator = "*" THEN
MULTIPLY Num1 BY Num2 GIVING Result
END-IF.
DISPLAY "Result is = ", Result.
STOP RUN.
70
IDENTIFICATION DIVISION. DATA
PROGRAM-ID. Selection-Program.
Num1
Num1 Num2
Num2 Result
Result Operator
Operator
AUTHOR. Michael Coughlan.
77 00 00
00 __
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Num1 PIC 9 VALUE ZEROS.
01 Num2 PIC 9 VALUE ZEROS.
01 Result PIC 99 VALUE ZEROS.
01 Operator PIC X VALUE SPACE.

PROCEDURE DIVISION.
Calculator.
ACCEPT Num1.
Num1
ACCEPT Num2.
ACCEPT Operator
IF Operator = "+" THEN
ADD Num1, Num2 GIVING Result
END-IF
IF Operator = "*" THEN
MULTIPLY Num1 BY Num2 GIVING Result
END-IF.
DISPLAY "Result is = ", Result.
STOP RUN.
71
IDENTIFICATION DIVISION. DATA
PROGRAM-ID. Selection-Program.
Num1
Num1 Num2
Num2 Result
Result Operator
Operator
AUTHOR. Michael Coughlan.
77 33 00
00 __
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Num1 PIC 9 VALUE ZEROS.
01 Num2 PIC 9 VALUE ZEROS.
01 Result PIC 99 VALUE ZEROS.
01 Operator PIC X VALUE SPACE.

PROCEDURE DIVISION.
Calculator.
ACCEPT Num1.
ACCEPT Num2.
Num2
ACCEPT Operator
IF Operator = "+" THEN
ADD Num1, Num2 GIVING Result
END-IF
IF Operator = "*" THEN
MULTIPLY Num1 BY Num2 GIVING Result
END-IF.
DISPLAY "Result is = ", Result.
STOP RUN.
72
IDENTIFICATION DIVISION.
DATA
PROGRAM-ID. Selection-Program.
AUTHOR. Michael Coughlan. Num1
Num1 Num2
Num2 Result
Result Operator
Operator
77 33 00
00 ++
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Num1 PIC 9 VALUE ZEROS.
01 Num2 PIC 9 VALUE ZEROS.
01 Result PIC 99 VALUE ZEROS.
01 Operator PIC X VALUE SPACE.

PROCEDURE DIVISION.
Calculator.
ACCEPT Num1.
ACCEPT Num2.
ACCEPT Operator
IF Operator = "+" THEN
ADD Num1, Num2 GIVING Result
END-IF
IF Operator = "*" THEN
MULTIPLY Num1 BY Num2 GIVING Result
END-IF.
DISPLAY "Result is = ", Result.
STOP RUN.
73
IDENTIFICATION DIVISION.
DATA
PROGRAM-ID. Selection-Program.
AUTHOR. Michael Coughlan. Num1
Num1 Num2
Num2 Result
Result Operator
Operator
77 33 00
00 ++
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Num1 PIC 9 VALUE ZEROS.
01 Num2 PIC 9 VALUE ZEROS.
01 Result PIC 99 VALUE ZEROS.
01 Operator PIC X VALUE SPACE.

PROCEDURE DIVISION.
Calculator.
ACCEPT Num1.
ACCEPT Num2.
ACCEPT Operator
IF Operator = "+" THEN
ADD Num1, Num2 GIVING Result
END-IF
IF Operator = "*" THEN
MULTIPLY Num1 BY Num2 GIVING Result
END-IF.
DISPLAY "Result is = ", Result.
STOP RUN.
74
IDENTIFICATION DIVISION.
DATA
PROGRAM-ID. Selection-Program.
AUTHOR. Michael Coughlan. Num1
Num1 Num2
Num2 Result
Result Operator
Operator
77 33 10
10 ++
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Num1 PIC 9 VALUE ZEROS.
01 Num2 PIC 9 VALUE ZEROS.
01 Result PIC 99 VALUE ZEROS.
01 Operator PIC X VALUE SPACE.

PROCEDURE DIVISION.
Calculator.
ACCEPT Num1.
ACCEPT Num2.
ACCEPT Operator
IF Operator = "+" THEN
ADD Num1, Num2 GIVING Result
END-IF
IF Operator = "*" THEN
MULTIPLY Num1 BY Num2 GIVING Result
END-IF.
DISPLAY "Result is = ", Result.
STOP RUN.
75
IDENTIFICATION DIVISION.
DATA
PROGRAM-ID. Selection-Program.
AUTHOR. Michael Coughlan. Num1
Num1 Num2
Num2 Result
Result Operator
Operator
77 33 10
10 ++
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Num1 PIC 9 VALUE ZEROS.
01 Num2 PIC 9 VALUE ZEROS.
01 Result PIC 99 VALUE ZEROS.
01 Operator PIC X VALUE SPACE.

PROCEDURE DIVISION.
Calculator.
ACCEPT Num1.
ACCEPT Num2.
ACCEPT Operator
IF Operator = "+" THEN
ADD Num1, Num2 GIVING Result
END-IF
IF Operator = "*" THEN
MULTIPLY Num1 BY Num2 GIVING Result
END-IF.
END-IF
DISPLAY "Result is = ", Result.
STOP RUN.
76
IDENTIFICATION DIVISION. DATA
PROGRAM-ID. Selection-Program.
Num1
Num1 Num2
Num2 Result
Result Operator
Operator
AUTHOR. Michael Coughlan.
77 33 10
10 ++
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Num1 PIC 9 VALUE ZEROS.
01 Num2 PIC 9 VALUE ZEROS.
01 Result PIC 99 VALUE ZEROS.
01 Operator PIC X VALUE SPACE.

PROCEDURE DIVISION.
Calculator.
ACCEPT Num1.
ACCEPT Num2.
ACCEPT Operator
IF Operator = "+" THEN
ADD Num1, Num2 GIVING Result
END-IF
IF Operator = "*" THEN
MULTIPLY Num1 BY Num2 GIVING Result
END-IF.
DISPLAY "Result is = ", Result.
Result
STOP RUN.
77
Ex2: ITERATION PROGRAM
DATA
IDENTIFICATION DIVISION. Num1
Num1 Num2 Result
DATA
Num2 Result Operator
Operator
PROGRAM-ID. Iteration-Program.
Iteration-Program 00 00 00
00 __
AUTHOR. Michael Coughlan.

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

PROCEDURE DIVISION.
Calculator.
PERFORM 5 TIMES
ACCEPT Num1
ACCEPT Num2
ACCEPT Operator
IF Operator = "+" THEN
ADD Num1, Num2 GIVING Result
END-IF
IF Operator = "*" THEN
MULTIPLY Num1 BY Num2 GIVING Result
END-IF
DISPLAY "Result is = ", Result
END-PERFORM. 78
STOP RUN.
IDENTIFICATION DIVISION.
PROGRAM-ID. Iteration-Program. DATA
AUTHOR. Michael Coughlan. Num1
Num1 Num2 Result
DATA
Num2 Result Operator
Operator
00 00 00
00 __
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Num1 PIC 9 VALUE ZEROS.
01 Num2 PIC 9 VALUE ZEROS.
01 Result PIC 99 VALUE ZEROS.
01 Operator PIC X VALUE SPACE.

PROCEDURE DIVISION.
Calculator.
PERFORM 5 TIMES
ACCEPT Num1
ACCEPT Num2
ACCEPT Operator
IF Operator = "+" THEN
ADD Num1, Num2 GIVING Result
END-IF
IF Operator = "*" THEN
MULTIPLY Num1 BY Num2 GIVING Result
END-IF
DISPLAY "Result is = ", Result
END-PERFORM.
END-PERFORM
STOP RUN.
79
IDENTIFICATION DIVISION.
PROGRAM-ID. Iteration-Program. DATA
AUTHOR. Michael Coughlan. Num1
Num1 Num2 Result
DATA
Num2 Result Operator
Operator
55 00 00
00 __
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Num1 PIC 9 VALUE ZEROS.
01 Num2 PIC 9 VALUE ZEROS.
01 Result PIC 99 VALUE ZEROS.
01 Operator PIC X VALUE SPACE.

PROCEDURE DIVISION.
Calculator.
PERFORM 5 TIMES
ACCEPT Num1
ACCEPT Num2
ACCEPT Operator
IF Operator = "+" THEN
ADD Num1, Num2 GIVING Result
END-IF
IF Operator = "*" THEN
MULTIPLY Num1 BY Num2 GIVING Result
END-IF
DISPLAY "Result is = ", Result
END-PERFORM.
STOP RUN.
80
IDENTIFICATION DIVISION.
PROGRAM-ID. Iteration-Program. DATA
AUTHOR. Michael Coughlan. Num1
Num1 Num2 Result
DATA
Num2 Result Operator
Operator
55 33 00
00 __
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Num1 PIC 9 VALUE ZEROS.
01 Num2 PIC 9 VALUE ZEROS.
01 Result PIC 99 VALUE ZEROS.
01 Operator PIC X VALUE SPACE.

PROCEDURE DIVISION.
Calculator.
PERFORM 5 TIMES
ACCEPT Num1
ACCEPT Num2
ACCEPT Operator
IF Operator = "+" THEN
ADD Num1, Num2 GIVING Result
END-IF
IF Operator = "*" THEN
MULTIPLY Num1 BY Num2 GIVING Result
END-IF
DISPLAY "Result is = ", Result
END-PERFORM.
STOP RUN.
81
IDENTIFICATION DIVISION.
PROGRAM-ID. Iteration-Program. DATA
AUTHOR. Michael Coughlan. Num1
Num1 Num2 Result
DATA
Num2 Result Operator
Operator
55 33 00
DATA DIVISION. 00 **
WORKING-STORAGE SECTION.
01 Num1 PIC 9 VALUE ZEROS.
01 Num2 PIC 9 VALUE ZEROS.
01 Result PIC 99 VALUE ZEROS.
01 Operator PIC X VALUE SPACE.

PROCEDURE DIVISION.
Calculator.
PERFORM 5 TIMES
ACCEPT Num1
ACCEPT Num2
ACCEPT Operator
IF Operator = "+" THEN
ADD Num1, Num2 GIVING Result
END-IF
IF Operator = "*" THEN
MULTIPLY Num1 BY Num2 GIVING Result
END-IF
DISPLAY "Result is = ", Result
END-PERFORM.
STOP RUN.
82
IDENTIFICATION DIVISION.
PROGRAM-ID. Iteration-Program. DATA
AUTHOR. Michael Coughlan. Num1
Num1 Num2 Result
DATA
Num2 Result Operator
Operator
55 33 00
DATA DIVISION. 00 **
WORKING-STORAGE SECTION.
01 Num1 PIC 9 VALUE ZEROS.
01 Num2 PIC 9 VALUE ZEROS.
01 Result PIC 99 VALUE ZEROS.
01 Operator PIC X VALUE SPACE.

PROCEDURE DIVISION.
Calculator.
PERFORM 5 TIMES
ACCEPT Num1
ACCEPT Num2
ACCEPT Operator
IF Operator = "+" THEN
ADD Num1, Num2 GIVING Result
END-IF
IF Operator = "*" THEN
MULTIPLY Num1 BY Num2 GIVING Result
END-IF
DISPLAY "Result is = ", Result
END-PERFORM.
STOP RUN.
83
IDENTIFICATION DIVISION.
PROGRAM-ID. Iteration-Program. DATA
AUTHOR. Michael Coughlan. Num1
Num1 Num2 Result
DATA
Num2 Result Operator
Operator
55 33 00
00 **
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Num1 PIC 9 VALUE ZEROS.
01 Num2 PIC 9 VALUE ZEROS.
01 Result PIC 99 VALUE ZEROS.
01 Operator PIC X VALUE SPACE.

PROCEDURE DIVISION.
Calculator.
PERFORM 5 TIMES
ACCEPT Num1
ACCEPT Num2
ACCEPT Operator
IF Operator = "+" THEN
ADD Num1, Num2 GIVING Result
END-IF
IF Operator = "*" THEN
MULTIPLY Num1 BY Num2 GIVING Result
END-IF
DISPLAY "Result is = ", Result
END-PERFORM.
STOP RUN.
84
IDENTIFICATION DIVISION.
PROGRAM-ID. Iteration-Program. DATA
AUTHOR. Michael Coughlan. Num1
Num1 Num2 Result
DATA
Num2 Result Operator
Operator
55 33 15
15 **
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Num1 PIC 9 VALUE ZEROS.
01 Num2 PIC 9 VALUE ZEROS.
01 Result PIC 99 VALUE ZEROS.
01 Operator PIC X VALUE SPACE.

PROCEDURE DIVISION.
Calculator.
PERFORM 5 TIMES
ACCEPT Num1
ACCEPT Num2
ACCEPT Operator
IF Operator = "+" THEN
ADD Num1, Num2 GIVING Result
END-IF
IF Operator = "*" THEN
MULTIPLY Num1 BY Num2 GIVING Result
END-IF
DISPLAY "Result is = ", Result
END-PERFORM.
STOP RUN.
85
IDENTIFICATION DIVISION. DATA
PROGRAM-ID. Iteration-Program. Num1
Num1 Num2 Result
DATA
Num2 Result Operator
Operator
AUTHOR. Michael Coughlan.
55 33 15
15 **
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Num1 PIC 9 VALUE ZEROS.
01 Num2 PIC 9 VALUE ZEROS.
01 Result PIC 99 VALUE ZEROS.
01 Operator PIC X VALUE SPACE.

PROCEDURE DIVISION.
Calculator.
PERFORM 5 TIMES
ACCEPT Num1
ACCEPT Num2
ACCEPT Operator
IF Operator = "+" THEN
ADD Num1, Num2 GIVING Result
END-IF
IF Operator = "*" THEN
MULTIPLY Num1 BY Num2 GIVING Result
END-IF
DISPLAY "Result is = ", Result
END-PERFORM.
STOP RUN. 86
IDENTIFICATION DIVISION. DATA
PROGRAM-ID. Iteration-Program. Num1
Num1 Num2 Result
DATA
Num2 Result Operator
Operator
AUTHOR. Michael Coughlan. 33 15
99 15 **
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Num1 PIC 9 VALUE ZEROS.
01 Num2 PIC 9 VALUE ZEROS.
01 Result PIC 99 VALUE ZEROS.
01 Operator PIC X VALUE SPACE.

PROCEDURE DIVISION.
Calculator.
PERFORM 5 TIMES
ACCEPT Num1
ACCEPT Num2
ACCEPT Operator
IF Operator = "+" THEN
ADD Num1, Num2 GIVING Result
END-IF
IF Operator = "*" THEN
MULTIPLY Num1 BY Num2 GIVING Result
END-IF
DISPLAY "Result is = ", Result
END-PERFORM.
STOP RUN. 87
IDENTIFICATION DIVISION. DATA
PROGRAM-ID. Iteration-Program.
Num1
Num1 Num2 Result
DATA Operator
AUTHOR. Michael Coughlan. Num2 Result Operator
99 33 15
15 **
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Num1 PIC 9 VALUE ZEROS.
01 Num2 PIC 9 VALUE ZEROS.
01 Result PIC 99 VALUE ZEROS.
01 Operator PIC X VALUE SPACE.

PROCEDURE DIVISION.
Calculator.
PERFORM 5 TIMES
ACCEPT Num1
ACCEPT Num2
ACCEPT Operator
IF Operator = "+" THEN
ADD Num1, Num2 GIVING Result
END-IF
IF Operator = "*" THEN
MULTIPLY Num1 BY Num2 GIVING Result
END-IF
DISPLAY "Result is = ", Result
END-PERFORM.
STOP RUN.
88
General
Introduction
Algorithms

89
Let’s write a program
 A program is a collection of statements written in a language the
computer understands.
 A computer executes program statements one after another in
sequence until it reaches the end of the program unless some
statement in the program alters the order of execution.
 Let’s write a program to accept two numbers from the user, multiply
them together and display the result on the screen.
 We’ll write the program in COBOL.
 What COBOL program statements will we need to do the job?

90
Program Statements
 We need a statement to take in the first number and store it in
a named memory location.
– ACCEPT Num1.

 We need a statement to take in the second number and store it


in a named memory location.
– ACCEPT Num2.

 We need a statement to multiply the two numbers together


and store the result in a named location.
– MULTIPLY Num1 BY Num2 GIVING Result.

 We need a statement to display the result on the screen.


– DISPLAY "Result is = ", Result.
91
IDENTIFICATION DIVISION.
PROGRAM-ID. FragmentA.
FragmentA DATA
AUTHOR. Michael Coughlan. Num1
Num1 Num2
Num2 Result
Result
00 00 00
00
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.
Calc-Result
ACCEPT Num1.
MULTIPLY Num1 BY Num2 GIVING Result.
ACCEPT Num2.
DISPLAY "Result is = ", Result.
STOP RUN.

92
IDENTIFICATION DIVISION.
PROGRAM-ID. FragmentA. DATA
AUTHOR. Michael Coughlan. Num1
Num1 Num2
Num2 Result
Result
99 00 00
00
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.
ACCEPT Num1.
Num1
MULTIPLY Num1 BY Num2 GIVING Result.
ACCEPT Num2.
DISPLAY "Result is = ", Result.
STOP RUN.

93
IDENTIFICATION DIVISION.
PROGRAM-ID. FragmentA. DATA
AUTHOR. Michael Coughlan. Num1
Num1 Num2
Num2 Result
Result
99 00 00
00
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.
ACCEPT Num1.
MULTIPLY Num1 BY Num2 GIVING Result.
Result
ACCEPT Num2.
DISPLAY "Result is = ", Result.
STOP RUN.

94
IDENTIFICATION DIVISION.
DATA
PROGRAM-ID. FragmentA.
Num1
Num1 Num2
Num2 Result
AUTHOR. Michael Coughlan. Result
00 55 00
00
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.
ACCEPT Num1.
MULTIPLY Num1 BY Num2 GIVING Result.
ACCEPT Num2.
Num2
DISPLAY "Result is = ", Result.
STOP RUN.

95
IDENTIFICATION DIVISION.
PROGRAM-ID. FragmentA. DATA
AUTHOR. Michael Coughlan. Num1
Num1 Num2
Num2 Result
Result
99 55 00
00
DATA DIVISION.
WORKING-STORAGE SECTION. Oh No!!
01 Num1 PIC 9 VALUE ZEROS. We got the
01 Num2 PIC 9 VALUE ZEROS. wrong
01 Result PIC 99 VALUE ZEROS. answer.
Let’s try
again.
PROCEDURE DIVISION.
Calc-Result.
ACCEPT Num1.
MULTIPLY Num1 BY Num2 GIVING Result.
ACCEPT Num2.
DISPLAY "Result is = ", Result.
Result
STOP RUN.

96
IDENTIFICATION DIVISION.
DATA
PROGRAM-ID. FragmentB.
FragmentB
Num1
Num1 Num2
Num2 Result
Result
AUTHOR. Michael Coughlan.
00 00 00
00
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.
Calc-Result
ACCEPT Num1.
ACCEPT Num2.
DISPLAY "Result is = ", Result.
MULTIPLY Num1 BY Num2 GIVING Result.
STOP RUN.

97
IDENTIFICATION DIVISION.
PROGRAM-ID. FragmentB. DATA
AUTHOR. Michael Coughlan. Num1
Num1 Num2
Num2 Result
Result
99 00 00
00
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.
ACCEPT Num1.
ACCEPT Num2.
DISPLAY "Result is = ", Result.
MULTIPLY Num1 BY Num2 GIVING Result.
STOP RUN.

98
IDENTIFICATION DIVISION.
DATA
PROGRAM-ID. FragmentB.
Num1
Num1 Num2
Num2 Result
AUTHOR. Michael Coughlan. Result
99 55 00
00
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.
ACCEPT Num1.
ACCEPT Num2.
Num2
DISPLAY "Result is = ", Result.
MULTIPLY Num1 BY Num2 GIVING Result.
STOP RUN.

99
IDENTIFICATION DIVISION.
PROGRAM-ID. FragmentB. DATA
AUTHOR. Michael Coughlan. Num1
Num1 Num2
Num2 Result
Result
99 55 00
00
DATA DIVISION.
WORKING-STORAGE SECTION. Oh No!!
01 Num1 PIC 9 VALUE ZEROS. We got the
01 Num2 PIC 9 VALUE ZEROS. wrong answer
01 Result PIC 99 VALUE ZEROS. again.
Let’s have one
more try.
PROCEDURE DIVISION.
Calc-Result.
ACCEPT Num1.
ACCEPT Num2.
DISPLAY "Result is = ", Result.
Result
MULTIPLY Num1 BY Num2 GIVING Result.
STOP RUN.

100
IDENTIFICATION DIVISION.
PROGRAM-ID. FragmentB. DATA
AUTHOR. Michael Coughlan. Num1
Num1 Num2
Num2 Result
Result
99 55 45
45
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.
ACCEPT Num1.
ACCEPT Num2.
DISPLAY "Result is = ", Result.
MULTIPLY Num1 BY Num2 GIVING Result.
Result
STOP RUN.

101
IDENTIFICATION DIVISION.
PROGRAM-ID. Sequence-Program.
Sequence-Program DATA
AUTHOR. Michael Coughlan. Num1
Num1 Num2
Num2 Result
Result
00 00 00
00
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.
Calc-Result
ACCEPT Num1.
ACCEPT Num2.
MULTIPLY Num1 BY Num2 GIVING Result.
DISPLAY "Result is = ", Result.
STOP RUN.

102
IDENTIFICATION DIVISION.
PROGRAM-ID. Sequence-Program. DATA
AUTHOR. Michael Coughlan. Num1 Num2 Result

9 0 00
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.
ACCEPT Num1.
Num1
ACCEPT Num2.
MULTIPLY Num1 BY Num2 GIVING Result.
DISPLAY "Result is = ", Result.
STOP RUN.

103
IDENTIFICATION DIVISION.
PROGRAM-ID. Sequence-Program. DATA
AUTHOR. Michael Coughlan. Num1 Num2 Result

9 5 00
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.
ACCEPT Num1.
ACCEPT Num2.
Num2
MULTIPLY Num1 BY Num2 GIVING Result.
DISPLAY "Result is = ", Result.
STOP RUN.

104
IDENTIFICATION DIVISION.
PROGRAM-ID. Sequence-Program. DATA
AUTHOR. Michael Coughlan. Num1 Num2 Result

9 5 45
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.
ACCEPT Num1.
ACCEPT Num2.
MULTIPLY Num1 BY Num2 GIVING Result.
Result
DISPLAY "Result is = ", Result.
STOP RUN.

105
IDENTIFICATION DIVISION.
PROGRAM-ID. Sequence-Program. DATA
AUTHOR. Michael Coughlan. Num1 Num2 Result

9 5 45
DATA DIVISION.
WORKING-STORAGE SECTION. Right .. At last!!
01 Num1 PIC 9 VALUE ZEROS.
01 Num2 PIC 9 VALUE ZEROS. It’s not enough to
01 Result PIC 99 VALUE ZEROS. know what
statements we need.
PROCEDURE DIVISION. We must make sure
Calc-Result. the computer
executes them in the
ACCEPT Num1.
right order.
ACCEPT Num2.
MULTIPLY Num1 BY Num2 GIVING Result.
DISPLAY "Result is = ", Result.
Result
STOP RUN.

106
Programs are written using three
main programming constructs.
constructs

 Sequence.

 Selection.

 Iteration.

107
IDENTIFICATION DIVISION. DATA
PROGRAM-ID. Selection-Program.
Selection-Program Num1
Num1 Num2
Num2 Result
Result Operator
Operator
AUTHOR. Michael Coughlan.
00 00 00
00 __
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Num1 PIC 9 VALUE ZEROS.
01 Num2 PIC 9 VALUE ZEROS.
01 Result PIC 99 VALUE ZEROS.
01 Operator PIC X VALUE SPACE.

PROCEDURE DIVISION.
Calculator.
Calculator
ACCEPT Num1.
ACCEPT Num2.
ACCEPT Operator
IF Operator = "+" THEN
ADD Num1, Num2 GIVING Result
END-IF
IF Operator = "*" THEN
MULTIPLY Num1 BY Num2 GIVING Result
END-IF.
DISPLAY "Result is = ", Result.
STOP RUN.
108
IDENTIFICATION DIVISION. DATA
PROGRAM-ID. Selection-Program. Num1
Num1 Num2
Num2 Result
Result Operator
Operator
AUTHOR. Michael Coughlan.
77 00 00
00 __
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Num1 PIC 9 VALUE ZEROS.
01 Num2 PIC 9 VALUE ZEROS.
01 Result PIC 99 VALUE ZEROS.
01 Operator PIC X VALUE SPACE.

PROCEDURE DIVISION.
Calculator.
ACCEPT Num1.
Num1
ACCEPT Num2.
ACCEPT Operator
IF Operator = "+" THEN
ADD Num1, Num2 GIVING Result
END-IF
IF Operator = "*" THEN
MULTIPLY Num1 BY Num2 GIVING Result
END-IF.
DISPLAY "Result is = ", Result.
STOP RUN.
109
IDENTIFICATION DIVISION. DATA
PROGRAM-ID. Selection-Program. Num1
Num1 Num2
Num2 Result
Result Operator
Operator
AUTHOR. Michael Coughlan.
77 33 00
00 __
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Num1 PIC 9 VALUE ZEROS.
01 Num2 PIC 9 VALUE ZEROS.
01 Result PIC 99 VALUE ZEROS.
01 Operator PIC X VALUE SPACE.

PROCEDURE DIVISION.
Calculator.
ACCEPT Num1.
ACCEPT Num2.
Num2
ACCEPT Operator
IF Operator = "+" THEN
ADD Num1, Num2 GIVING Result
END-IF
IF Operator = "*" THEN
MULTIPLY Num1 BY Num2 GIVING Result
END-IF.
DISPLAY "Result is = ", Result.
STOP RUN.
110
IDENTIFICATION DIVISION. DATA
PROGRAM-ID. Selection-Program. Num1
Num1 Num2
Num2 Result
Result Operator
Operator
AUTHOR. Michael Coughlan.
77 33 00
00 ++
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Num1 PIC 9 VALUE ZEROS.
01 Num2 PIC 9 VALUE ZEROS.
01 Result PIC 99 VALUE ZEROS.
01 Operator PIC X VALUE SPACE.

PROCEDURE DIVISION.
Calculator.
ACCEPT Num1.
ACCEPT Num2.
ACCEPT Operator
IF Operator = "+" THEN
ADD Num1, Num2 GIVING Result
END-IF
IF Operator = "*" THEN
MULTIPLY Num1 BY Num2 GIVING Result
END-IF.
DISPLAY "Result is = ", Result.
STOP RUN.
111
IDENTIFICATION DIVISION. DATA
PROGRAM-ID. Selection-Program. Num1
Num1 Num2
Num2 Result
Result Operator
Operator
AUTHOR. Michael Coughlan.
77 33 00
00 ++
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Num1 PIC 9 VALUE ZEROS.
01 Num2 PIC 9 VALUE ZEROS.
01 Result PIC 99 VALUE ZEROS.
01 Operator PIC X VALUE SPACE.

PROCEDURE DIVISION.
Calculator.
ACCEPT Num1.
ACCEPT Num2.
ACCEPT Operator
IF Operator = "+" THEN
ADD Num1, Num2 GIVING Result
END-IF
IF Operator = "*" THEN
MULTIPLY Num1 BY Num2 GIVING Result
END-IF.
DISPLAY "Result is = ", Result.
STOP RUN.
112
IDENTIFICATION DIVISION. DATA
PROGRAM-ID. Selection-Program. Num1
Num1 Num2
Num2 Result
Result Operator
Operator
AUTHOR. Michael Coughlan. 77 33 ++
10
10
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Num1 PIC 9 VALUE ZEROS.
01 Num2 PIC 9 VALUE ZEROS.
01 Result PIC 99 VALUE ZEROS.
01 Operator PIC X VALUE SPACE.

PROCEDURE DIVISION.
Calculator.
ACCEPT Num1.
ACCEPT Num2.
ACCEPT Operator
IF Operator = "+" THEN
ADD Num1, Num2 GIVING Result
END-IF
IF Operator = "*" THEN
MULTIPLY Num1 BY Num2 GIVING Result
END-IF.
DISPLAY "Result is = ", Result.
STOP RUN.
113
IDENTIFICATION DIVISION. DATA
PROGRAM-ID. Selection-Program. Num1
Num1 Num2
Num2 Result
Result Operator
Operator
AUTHOR. Michael Coughlan.
77 33 10
10 ++
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Num1 PIC 9 VALUE ZEROS.
01 Num2 PIC 9 VALUE ZEROS.
01 Result PIC 99 VALUE ZEROS.
01 Operator PIC X VALUE SPACE.

PROCEDURE DIVISION.
Calculator.
ACCEPT Num1.
ACCEPT Num2.
ACCEPT Operator
IF Operator = "+" THEN
ADD Num1, Num2 GIVING Result
END-IF
IF Operator = "*" THEN
MULTIPLY Num1 BY Num2 GIVING Result
END-IF.
END-IF
DISPLAY "Result is = ", Result.
STOP RUN.
114
IDENTIFICATION DIVISION. DATA
PROGRAM-ID. Selection-Program.
Num1
Num1 Num2
Num2 Result
Result Operator
Operator
AUTHOR. Michael Coughlan.
77 33 10
10 ++
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Num1 PIC 9 VALUE ZEROS.
01 Num2 PIC 9 VALUE ZEROS.
01 Result PIC 99 VALUE ZEROS.
01 Operator PIC X VALUE SPACE.

PROCEDURE DIVISION.
Calculator.
ACCEPT Num1.
ACCEPT Num2.
ACCEPT Operator
IF Operator = "+" THEN
ADD Num1, Num2 GIVING Result
END-IF
IF Operator = "*" THEN
MULTIPLY Num1 BY Num2 GIVING Result
END-IF.
DISPLAY "Result is = ", Result.
Result
STOP RUN.
115
IDENTIFICATION DIVISION. DATA
PROGRAM-ID. Iteration-Program.
Iteration-Program
Num1
Num1 Num2 Result
DATA Operator
AUTHOR. Michael Coughlan. Num2 Result Operator
00 00 00
00 __
DATA DIVISION.
DIVISION
WORKING-STORAGE SECTION.
01 Num1 PIC 9 VALUE ZEROS.
01 Num2 PIC 9 VALUE ZEROS.
01 Result PIC 99 VALUE ZEROS.
01 Operator PIC X VALUE SPACE.

PROCEDURE DIVISION.
Calculator.
PERFORM 5 TIMES
ACCEPT Num1
ACCEPT Num2
ACCEPT Operator
IF Operator = "+" THEN
ADD Num1, Num2 GIVING Result
END-IF
IF Operator = "*" THEN
MULTIPLY Num1 BY Num2 GIVING Result
END-IF
DISPLAY "Result is = ", Result
END-PERFORM.
STOP RUN.
116
IDENTIFICATION DIVISION. DATA
PROGRAM-ID. Iteration-Program.
Num1
Num1 Num2 Result
DATA Operator
AUTHOR. Michael Coughlan. Num2 Result Operator
00 00 00
00 __
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Num1 PIC 9 VALUE ZEROS.
01 Num2 PIC 9 VALUE ZEROS.
01 Result PIC 99 VALUE ZEROS.
01 Operator PIC X VALUE SPACE.

PROCEDURE DIVISION.
Calculator.
PERFORM 5 TIMES
ACCEPT Num1
ACCEPT Num2
ACCEPT Operator
IF Operator = "+" THEN
ADD Num1, Num2 GIVING Result
END-IF
IF Operator = "*" THEN
MULTIPLY Num1 BY Num2 GIVING Result
END-IF
DISPLAY "Result is = ", Result
END-PERFORM.
END-PERFORM
STOP RUN.
117
IDENTIFICATION DIVISION. DATA
PROGRAM-ID. Iteration-Program.
Num1
Num1 Num2 Result
DATA Operator
AUTHOR. Michael Coughlan. Num2 Result Operator
55 00 00
00 __
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Num1 PIC 9 VALUE ZEROS.
01 Num2 PIC 9 VALUE ZEROS.
01 Result PIC 99 VALUE ZEROS.
01 Operator PIC X VALUE SPACE.

PROCEDURE DIVISION.
Calculator.
PERFORM 5 TIMES
ACCEPT Num1
ACCEPT Num2
ACCEPT Operator
IF Operator = "+" THEN
ADD Num1, Num2 GIVING Result
END-IF
IF Operator = "*" THEN
MULTIPLY Num1 BY Num2 GIVING Result
END-IF
DISPLAY "Result is = ", Result
END-PERFORM.
STOP RUN.
118
IDENTIFICATION DIVISION. DATA
PROGRAM-ID. Iteration-Program.
Num1
Num1 Num2 Result
DATA Operator
AUTHOR. Michael Coughlan. Num2 Result Operator
55 33 00
00 __
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Num1 PIC 9 VALUE ZEROS.
01 Num2 PIC 9 VALUE ZEROS.
01 Result PIC 99 VALUE ZEROS.
01 Operator PIC X VALUE SPACE.

PROCEDURE DIVISION.
Calculator.
PERFORM 5 TIMES
ACCEPT Num1
ACCEPT Num2
ACCEPT Operator
IF Operator = "+" THEN
ADD Num1, Num2 GIVING Result
END-IF
IF Operator = "*" THEN
MULTIPLY Num1 BY Num2 GIVING Result
END-IF
DISPLAY "Result is = ", Result
END-PERFORM.
STOP RUN.
119
IDENTIFICATION DIVISION. DATA
PROGRAM-ID. Iteration-Program. Num1
Num1 Num2 Result
DATA
Num2 Result Operator
Operator
AUTHOR. Michael Coughlan.
55 33 00
DATA DIVISION.
00 **
WORKING-STORAGE SECTION.
01 Num1 PIC 9 VALUE ZEROS.
01 Num2 PIC 9 VALUE ZEROS.
01 Result PIC 99 VALUE ZEROS.
01 Operator PIC X VALUE SPACE.

PROCEDURE DIVISION.
Calculator.
PERFORM 5 TIMES
ACCEPT Num1
ACCEPT Num2
ACCEPT Operator
IF Operator = "+" THEN
ADD Num1, Num2 GIVING Result
END-IF
IF Operator = "*" THEN
MULTIPLY Num1 BY Num2 GIVING Result
END-IF
DISPLAY "Result is = ", Result
END-PERFORM.
STOP RUN. 120
IDENTIFICATION DIVISION. DATA
PROGRAM-ID. Iteration-Program.
Num1
Num1 Num2 Result
DATA Operator
AUTHOR. Michael Coughlan. Num2 Result Operator
55 33 00
DATA DIVISION.
00 **
WORKING-STORAGE SECTION.
01 Num1 PIC 9 VALUE ZEROS.
01 Num2 PIC 9 VALUE ZEROS.
01 Result PIC 99 VALUE ZEROS.
01 Operator PIC X VALUE SPACE.

PROCEDURE DIVISION.
Calculator.
PERFORM 5 TIMES
ACCEPT Num1
ACCEPT Num2
ACCEPT Operator
IF Operator = "+" THEN
ADD Num1, Num2 GIVING Result
END-IF
IF Operator = "*" THEN
MULTIPLY Num1 BY Num2 GIVING Result
END-IF
DISPLAY "Result is = ", Result
END-PERFORM.
STOP RUN.
121
IDENTIFICATION DIVISION. DATA
PROGRAM-ID. Iteration-Program.
Num1
Num1 Num2 Result
DATA Operator
AUTHOR. Michael Coughlan. Num2 Result Operator
55 33 00
00 **
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Num1 PIC 9 VALUE ZEROS.
01 Num2 PIC 9 VALUE ZEROS.
01 Result PIC 99 VALUE ZEROS.
01 Operator PIC X VALUE SPACE.

PROCEDURE DIVISION.
Calculator.
PERFORM 5 TIMES
ACCEPT Num1
ACCEPT Num2
ACCEPT Operator
IF Operator = "+" THEN
ADD Num1, Num2 GIVING Result
END-IF
IF Operator = "*" THEN
MULTIPLY Num1 BY Num2 GIVING Result
END-IF
DISPLAY "Result is = ", Result
END-PERFORM.
STOP RUN.
122
IDENTIFICATION DIVISION. DATA
PROGRAM-ID. Iteration-Program.
Num1
Num1 Num2 Result
DATA Operator
AUTHOR. Michael Coughlan. Num2 Result Operator
55 33 15
15 **
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Num1 PIC 9 VALUE ZEROS.
01 Num2 PIC 9 VALUE ZEROS.
01 Result PIC 99 VALUE ZEROS.
01 Operator PIC X VALUE SPACE.

PROCEDURE DIVISION.
Calculator.
PERFORM 5 TIMES
ACCEPT Num1
ACCEPT Num2
ACCEPT Operator
IF Operator = "+" THEN
ADD Num1, Num2 GIVING Result
END-IF
IF Operator = "*" THEN
MULTIPLY Num1 BY Num2 GIVING Result
END-IF
DISPLAY "Result is = ", Result
END-PERFORM.
STOP RUN.
123
IDENTIFICATION DIVISION. DATA
PROGRAM-ID. Iteration-Program.
Num1
Num1 Num2 Result
DATA Operator
AUTHOR. Michael Coughlan. Num2 Result Operator
55 33 15
15 **
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Num1 PIC 9 VALUE ZEROS.
01 Num2 PIC 9 VALUE ZEROS.
01 Result PIC 99 VALUE ZEROS.
01 Operator PIC X VALUE SPACE.

PROCEDURE DIVISION.
Calculator.
PERFORM 5 TIMES
ACCEPT Num1
ACCEPT Num2
ACCEPT Operator
IF Operator = "+" THEN
ADD Num1, Num2 GIVING Result
END-IF
IF Operator = "*" THEN
MULTIPLY Num1 BY Num2 GIVING Result
END-IF
DISPLAY "Result is = ", Result
END-PERFORM.
STOP RUN.
124
IDENTIFICATION DIVISION. DATA
PROGRAM-ID. Iteration-Program. Num1
Num1 Num2 Result
DATA
Num2 Result Operator
Operator
AUTHOR. Michael Coughlan. 33 15
99 15 **
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Num1 PIC 9 VALUE ZEROS.
01 Num2 PIC 9 VALUE ZEROS.
01 Result PIC 99 VALUE ZEROS.
01 Operator PIC X VALUE SPACE.

PROCEDURE DIVISION.
Calculator.
PERFORM 5 TIMES
ACCEPT Num1
ACCEPT Num2
ACCEPT Operator
IF Operator = "+" THEN
ADD Num1, Num2 GIVING Result
END-IF
IF Operator = "*" THEN
MULTIPLY Num1 BY Num2 GIVING Result
END-IF
DISPLAY "Result is = ", Result
END-PERFORM.
STOP RUN. 125
IDENTIFICATION DIVISION. DATA
PROGRAM-ID. Iteration-Program.
Num1
Num1 Num2 Result
DATA Operator
AUTHOR. Michael Coughlan. Num2 Result Operator
99 33 15
15 **
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Num1 PIC 9 VALUE ZEROS.
01 Num2 PIC 9 VALUE ZEROS.
01 Result PIC 99 VALUE ZEROS.
01 Operator PIC X VALUE SPACE.

PROCEDURE DIVISION.
Calculator.
PERFORM 5 TIMES
ACCEPT Num1
ACCEPT Num2
ACCEPT Operator
IF Operator = "+" THEN
ADD Num1, Num2 GIVING Result
END-IF
IF Operator = "*" THEN
MULTIPLY Num1 BY Num2 GIVING Result
END-IF
DISPLAY "Result is = ", Result
END-PERFORM.
STOP RUN.
126
Arithmetic
and
Edited
Pictures

127
Template
TO 
 Identifier  
FROM 
  Identifier  
VERB     [ ROUNDED ]
Literal  BY   Identifier GIVING I dentifier  

INTO 

[ ON SIZE ER ROR State mentBlock END - VERB ]

 Most COBOL arithmetic verbs conform to the template above. For


example;
ADD Takings TO CashTotal.
ADD Males TO Females GIVING TotalStudents.
SUBTRACT Tax FROM GrossPay.
SUBTRACT Tax FROM GrossPay GIVING NetPay.
DIVIDE Total BY Members GIVING MemberAverage.
DIVIDE Members INTO Total GIVING MemberAverage.
MULTIPLY 10 BY Magnitude.
MULTIPLY Members BY Subs GIVING TotalSubs.

 The exceptions are the COMPUTE and the DIVIDE with


REMAINDER.

128
The ROUNDED option

Receiving Field Actual Result Truncated Result Rounded Result


123.2 123.3
PIC 9(3)V9. 123.25
123 123
PIC 9(3). 123.25

 The ROUNDED option takes effect when, after decimal


point alignment, the result calculated must be truncated on
the right hand side.
 The option adds 1 to the receiving item when the leftmost
truncated digit has an absolute value of 5 or greater.

129
The ON SIZE ERROR
option

Receiving Field Actual Result SIZE ERROR


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

PIC 9(3)V9 Rounded 124.45


PIC 9(3)V9 Rounded 3124.45

 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
130
(most significant digits).
ADD Examples
ADD
ADD Cash
Cash TO
TO Total.
Total.
Before
Before 33 1000
1000
After
After 3 1003

ADD
ADD Cash,
Cash, 20
20 TO
TO Total,
Total, Wage.
Wage.
Before
Before 333 10231000
1000
123 100
100
After
After

ADD
ADD Cash,
Cash,
3 Total
TotalGIVING
1000 1003 Result.
GIVING Result.
Before
Before 33 1000
1000 0015
0015
After
After
1500 0625 2125
ADD
ADDMales
MalesTO
TOFemales
FemalesGIVING
GIVING TotalStudents.
TotalStudents.
Before
Before 1500
1500 0625
0625 1234
1234
After
After

131
SUBTRACT Examples
SUBTRACT
SUBTRACT Tax
Tax FROM
FROMGrossPay,
GrossPay,Total.
Total.
Before
Before 120
120 4000
4000 9120
9120
After
After 120 3880 9000

SUBTRACT
SUBTRACT Tax,
Tax,80
80FROM
FROMTotal.
Total.
Before
Before 100
100 480
480
After
After 100 300

SUBTRACT
SUBTRACT Tax
Tax FROM
FROMGrossPay
GrossPayGIVING
GIVINGNetPay.
NetPay.
Before
Before 750
750 1000
1000 0012
0012
After
After 750 1000 0250

132
Examples
MULTIPLY
MULTIPLY Subs
SubsBY
BYMembers
MembersGIVING
GIVINGTotalSubs
TotalSubs
ON
ONSIZE
SIZEERROR
ERRORDISPLAY
DISPLAY"TotalSubs
"TotalSubstoo
toosmall"
small"
END-MULTIPLY.
END-MULTIPLY.
Subs
Subs Members
Members TotalSubs
TotalSubs
Before
Before 15.50
15.50 100
100 0123.45
0123.45
After
After
15.50 100 1550.00

3550 1250
MULTIPLY
MULTIPLY10
10BY
BYMagnitude,
Magnitude, Size.
Size.
Before
Before 355
355 125
125
After
After
9234.55 100 92.35

DIVIDE
DIVIDE Total
Total BY
BY Members
MembersGIVING
GIVINGAverage
Average ROUNDED.
ROUNDED.
Before
Before 9234.55
9234.55 100
100 1234.56
1234.56
After
After

133
The Divide Exception
 Identifier   Identifier 
DIVIDE   INTO   GIVING { Identifier [ ROUNDED ]} REMAINDER Identifier
 Literal   Literal 
  ON SIZE ERROR  
   StatementBlock END - DIVIDE 
  NOT ON SIZE ERROR  

 Identifier   Identifier 
DIVIDE   BY   GIVING { Identifier [ ROUNDED ]} REMAINDER Identifier
 Literal   Literal 
  ON SIZE ERROR  
   StatementBlock END - DIVIDE 
  NOT ON SIZE ERROR  

DIVIDE
DIVIDE201
201BY
BY10
10GIVING
GIVINGQuotient
Quotient REMAINDER
REMAINDERRemain.
Remain.
Before
Before 209
209 424
424
After
After 020 001

134
The COMPUTE
COMPUTE { Identifier [ ROUNDED ]} ... = ArithmeticExpression
  ON SIZE ERROR  
  StatementBlock END - COMPUTE 
  NOT ON SIZE ERROR  

Precedence
Precedence Rules.
Rules.
1.
1. **** == POWER
POWER NNNN
2.
2. ** == MULTIPLY
MULTIPLY xx
// == DIVIDE
DIVIDE ÷÷
3.
3. ++ == ADD
ADD ++
-- == SUBTRACT
SUBTRACT --

Compute
ComputeIrishPrice
IrishPrice==SterlingPrice
SterlingPrice//Rate
Rate ** 100.
100.
Before
Before 1000.50
1000.50 156.25
156.25 87
87
After 179.59 156.25 87
After
135
Edited Pictures.
 Edited Pictures are PICTURE clauses which format data
intended for output to screen or printer.
 To enable the data items to be formatted in a particular style
COBOL provides additional picture symbols supplementing the
basic 9, X, A, V and S symbols.
 The additional symbols are referred to as “Edit Symbols” and
PICTURE clauses which include edit symbols are called “Edited
Pictures”.
 The term edit is used because the edit symbols have the effect of
changing, or editing, the data inserted into the edited item.
 Edited items can not be used as operands in a computation but
they may be used as the result or destination of a computation
(i.e. to the right of the word GIVING).
136
Editing Types
 COBOL provides two basic types of editing
Œ Insertion Editing - which modifies a value by including
additional items.
 Suppression and Replacement Editing -
which suppresses and replaces leading zeros.
 Each type has sub-categories
Insertion editing
Simple Insertion
Special Insertion
Fixed Insertion
Floating Insertion
 Suppression and Replacement
Zero suppression and replacement with spaces
Zero suppression and replacement with asterisks

137
Editing Symbols

Edit Symbol Editing Type


,, BB 00 // Simple
SimpleInsertion
Insertion
.. Special
Special Insertion
Insertion
++ -- CR
CR DB
DB $$ Fixed
Fixed Insertion
Insertion
++ -- SS Floating
Floating Insertion
Insertion
ZZ ** Suppression
Suppressionand
andReplacement
Replacement

138
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 000,078
PIC9(6)
9(6) 000078
000078 PIC 9(3),9(3)
PIC 9(3),9(3) 78
PIC
PIC9(6)
9(6) 000078
000078 PIC ZZZ,ZZZ
PIC ZZZ,ZZZ ****178
PIC
PIC9(6)
9(6) 000178
000178 PIC
PIC***,***
***,*** **2,178
PIC
PIC9(6)
9(6) 002178
002178 PIC
PIC***,***
***,*** 120183
12/01/83
PIC
PIC9(6)
9(6) 120183
120183 PIC
PIC99B99B99
99B99B99 120045
PIC
PIC9(6)
9(6) 120183
120183 PIC
PIC99/99/99
99/99/99
PIC
PIC9(6)
9(6) 001245
001245 PIC
PIC990099
990099

139
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

140
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+

141
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 1223
PICS9(4)
S9(4) +1234
+1234 PIC
PIC9(4)DB
9(4)DB
1234DB
PIC
PICS9(4)
S9(4) -1234
-1234 PIC 9(4)DB
PIC 9(4)DB
$01234
PIC $
PIC9(4)
9(4) 1234
1234 PIC
PIC$99999
$99999
PIC
PIC9(4)
9(4) 0000
0000 PIC
PIC$ZZZZZ
$ZZZZZ

142
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
$128.00
PIC
PIC9(4)
9(4) 0128
0128 PIC $$,$$9.99
PIC $$,$$9.99 $7,397
PIC
PIC9(5)
9(5) 57397
57397PIC
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
143
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
PIC
PIC9(5)
9(5) 01234
01234 PIC
PICZZ,999
ZZ,999 1,234
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
PIC9(5)
9(5) 05678
05678 PIC
PIC**,**9
**,**9 ***567
******
PIC
PIC9(5)
9(5) 00567
00567 PIC
PIC**,**9
**,**9
PIC
PIC9(5)
9(5) 00000
00000 PIC
PIC**,***
**,***

144
The
USA
GE
claus
e

145
USAGE IS DISPLAY
SYSTEM CHAR HEX DEC 8 4 2 1 8 4 2 1
ASCII "A" 41 65 0 1 0 0 0 0 0 1

EBCDIC "A" C1 193 1 1 0 0 0 0 0 1

 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 ASCII
characters !!

146
Arithmetic when USAGE IS
DISPLAY

8 4 2 1 8 4 2 1 HEX CHAR
Num1 PIC 9 VALUE 4. 0 0 1 1 0 1 0 0 41 "4"

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

Num3 PIC 9. 0 0 0 0 0 0 0 0 0 nul

ADD Num1,Num2 GIVING Num3.

147
Arithmetic when USAGE IS
DISPLAY

8 4 2 1 8 4 2 1 HEX CHAR
Num1 PIC 9 VALUE 4. 0 0 1 1 0 1 0 0 41 "4"

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

Num3 PIC 9. 0 1 1 0 0 1 0 1 65 "e"

ADD Num1,Num2 GIVING Num3.

148
Why use the USAGE
clause?

 TheUSAGE clause is used for purposes of


optimisation - both speed and storage.
 TheUSAGE clause controls the way data
items (normally numeric) are stored in
memory.

149
USAGE Syntax

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


01 Num2 PIC 99 USAGE IS PACKED-DECIMAL.
01 IdxItem USAGE IS INDEX.
01 GroupItems COMP.
02 Item1 PIC 999.
02 Item2 PIC 9(4)V99.
02 New1 PIC S9(5) COMP SYNC. 150
USAGE IS COMP
 COMP items are held in memory as pure binary two's complement
numbers.

Number of Digits Storage Required.


1 TO 4 1 WORD (2 Bytes)
5 TO 9 1 LONGWORD (4 Bytes)
10 TO 18 1 QUADWORD (8 Bytes)

01 TotalCount PIC 9(7) USAGE IS COMP.

Takes 4 bytes (1 LONGWORD) of storage.

151
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

4 Bytes can represent any 9 digit number

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


PIC 999 999 999

152
USAGE IS PACKED-
DECIMAL

 Data items declared as PACKED-DECIMAL 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).
PIC S9 PIC S9(2) PIC S9(3)
VALUE +5 VALUE -32 VALUE +262
5 + 0 3 2 - 2 6 2 +

153
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 optimise 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
Word1 Word2 Word3

154
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 ThreeBytes PIC XXX VALUE "DOG".


01 TwoBytes PIC 9(4) COMP SYNC.

D O G Number
Word1 Word2 Word3

155
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.

F R O G S NumberNumber
Word1 Word2 Word3 Word4 Word5 Word6

156
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". Aligns


Alignsalong
alongaa
01 FourBytes PIC S9(5) COMP SYNC. 44byte
byteboundary
boundary

F R O G S NumberNumber
Word1 Word2 Word3 Word4 Word5 Word6

157
Conditio
ns.

158
Syntax.
StatementBlock 
IF Condition THEN  
 NEXT SENTENCE 
StatementBlock 
ELSE   [ END - IF]
 NEXT SENTENCE 

CONDITION TYPES

Simple
 Simple Conditions
Conditions
–– Relation
Relation Conditions
Conditions
–– Class
Class Conditions
Conditions
–– Sign
Sign Conditions
Conditions
Complex
 Complex Conditions
Conditions
Condition
 Condition Names
159
Names
Relation Conditions

[ NOT] GREATER THAN 


 
[ NOT] > 
 

[ NOT] LESS THAN

[ NOT] < 
 Identifier     Identifier 
  [ NOT] EQUAL TO   
 Literal  IS    Literal 
 ArithmeticExpression  [ NOT] =   ArithmeticExpression 
     
 GREATER THAN OR EQUAL TO 
 >= 
 
 LESS THAN OR EQUAL TO 
 <= 

160
Conditions.
 NUMERIC 
 ALPHABETIC 
 
Identifier IS [NOT]  ALPHABETIC - LOWER 
 ALPHABETIC - UPPER 
 
 UserDefinedClassName 

 Although COBOL data items are not ‘typed’ they do fall into some broad
categories, or classes, such a numeric or alphanumeric, etc.

 A Class Condition determines whether the value of data item is a member of


one these classes.

161
Sign
Conditions
 POSITIVE 
 
ArithExp IS [NOT]  NEGATIVE 
 ZERO 
 

 The sign condition determines whether or not the value of


an arithmetic expression is less than, greater than or equal to
zero.
 Sign conditions are just another way of writing some of the
Relational conditions.

162
Complex conditions.
  AND  
Condition    Condition  
 OR  
 Programs often require conditions which are more complex
than single value testing or determining a data class.
 Like all other programming languages COBOL allows simple
conditions to be combined using OR and AND to form
composite conditions.
 Like other conditions, a complex condition evaluates to true or
false.
 A complex condition is an expression which is evaluated from
left to right unless the order of evaluation is changed by the
precedence rules or bracketing.
163
Complex conditions have precedence rules
too.
Precedence
Precedence Rules.
Rules.
1.
1. NOT
NOT == ****
2.
2. AND
AND == **oror//
3.
3. OR
OR == ++or
or--

 Just like arithmetic expressions, complex conditions


are evaluated using precedence rules and the order of
evaluation may be changed by bracketing.
 Examples
IF Row
( > 0) AND
( Row
) < 26 THEN
DISPLAY “On Screen”
END-IF
( ) ( ) ( )
IF VarA > VarC OR VarC = VarD OR VarA NOT = VarF
DISPLAY “Done”
END-IF 164
Subjects.
 When a data item is involved in a relation condition with each
of a number of other items it can be tedious to have to repeat the
data item for each condition. For example,
IF TotalAmt > 10000 AND TotalAmt < 50000 THEN
IF Grade = “A” OR Grade = “B+” OR GRADE = “B” THEN
IF VarA > VarB AND VarA > VarC AND VarA > VarD
DISPLAY “VarA is the Greatest”
END-IF
 In these situations COBOL provides an abbreviation mechanism
called implied subjects.
 The statements above may be re-written using implied subjects
as;
IF TotalAmt > 10000 AND < 50000 THEN
Implied
ImpliedSubjects
Subjects
IF Grade=“A” OR “B+” OR “B” THEN
TotalAmt
TotalAmt
IF VarA > VarB AND VarC AND VarD
Grade
Grade==
DISPLAY “VarA is the Greatest” VarA
END-IF VarA>>
165
Nested IFs
IF
IF (( VarA
VarA << 10
10 )) AND
AND (( VarB
VarB NOT
NOT >> VarC
VarC )) THEN
THEN
IF
IF VarG
VarG == 14
14 THEN
THEN
DISPLAY
DISPLAY “First”
“First”
ELSE
ELSE
DISPLAY
DISPLAY “Second”
“Second”
END-IF
END-IF
ELSE
ELSE
DISPLAY
DISPLAY “Third”
“Third”
END-IF
END-IF

VarA
VarA VarB
VarB VarC
VarC VarG
VarG DISPLAY
DISPLAY
33 44 15
15 14
14
33 44 15
15 15
15
33 44 33 14
14
13
13 44 15
15 14
14
166
Condition Names.
 Wherever a condition can occur, such as in an IF statement or an
EVALUATE or a PERFORM..UNTIL, a CONDITION NAME (Level 88)
may be used.
 A Condition Name is essentially a BOOLEAN variable which is either
TRUE or FALSE.
 Example.
IF StudentRecord = HIGH-VALUES THEN Action
The statement above may be replaced by the one below. The condition name
EndOfStudentFile may be used instead of the condition StudentRecord = HIGH-
VALUES.
IF EndOfStudentFile THEN Action

167
Names.
 Literal 
 VALUE   
88 ConditionName    THROUGH  
 VALUES   LowValue   HighValue 
  THRU  

 Condition Names are defined in the DATA DIVISION using the special
level number 88.
 They are always associated with a data item and are defined immediately
after the definition of the data item.
 A condition name takes the value TRUE or FALSE depending on the
value in its associated data item.
 A Condition Name may be associated with ANY data item whether it is a
group or an elementary item.
 The VALUE clause is used to identify the values which make the
Condition Name TRUE.
168
01
01 CityCode
CityCode PIC
PIC 99 VALUE
VALUE 5.
5.
88
88 Dublin
Dublin VALUE
VALUE 1.
1.
88
88 Limerick
Limerick VALUE
VALUE 2.
2.
88
88 Cork
Cork VALUE
VALUE 3.
3.
88
88 Galway
Galway VALUE
VALUE 4.
4.
88
88 Sligo
Sligo VALUE
VALUE 5.
5.
88
88 Waterford
Waterford VALUE
VALUE 6.
6.
88
88 UniversityCity
UniversityCity VALUE
VALUE 11 THRU
THRU 4.
4.

IF
IF Limerick
Limerick City Code
DISPLAY
DISPLAY "Hey,
"Hey, we're
we're home."
home."
END-IF 5
END-IF
IF
IF UniversityCity
UniversityCity Dublin FALSE
PERFORM
PERFORM CalcRentSurcharge
CalcRentSurcharge Limerick FALSE
END-IF
END-IF Cork FALSE
Galway FALSE
Sligo TRUE
Waterford FALSE
UniversityCity FALSE
169
01
01 CityCode
CityCode PIC
PIC 99 VALUE
VALUE 5.
5.
88
88 Dublin
Dublin VALUE
VALUE 1.
1.
88
88 Limerick
Limerick VALUE
VALUE 2.
2.
88
88 Cork
Cork VALUE
VALUE 3.
3.
88
88 Galway
Galway VALUE
VALUE 4.
4.
88
88 Sligo
Sligo VALUE
VALUE 5.
5.
88
88 Waterford
Waterford VALUE
VALUE 6.
6.
88
88 UniversityCity
UniversityCity VALUE
VALUE 11 THRU
THRU 4.
4.

IF
IF Limerick
Limerick City Code
DISPLAY
DISPLAY "Hey,
"Hey, we're
we're home."
home."
END-IF 2
END-IF
IF
IF UniversityCity
UniversityCity Dublin FALSE
PERFORM
PERFORM CalcRentSurcharge
CalcRentSurcharge Limerick TRUE
END-IF
END-IF Cork FALSE
Galway FALSE
Sligo FALSE
Waterford FALSE
UniversityCity TRUE
170
01
01 CityCode
CityCode PIC
PIC 99 VALUE
VALUE 5.
5.
88
88 Dublin
Dublin VALUE
VALUE 1.
1.
88
88 Limerick
Limerick VALUE
VALUE 2.
2.
88
88 Cork
Cork VALUE
VALUE 3.
3.
88
88 Galway
Galway VALUE
VALUE 4.
4.
88
88 Sligo
Sligo VALUE
VALUE 5.
5.
88
88 Waterford
Waterford VALUE
VALUE 6.
6.
88
88 UniversityCity
UniversityCity VALUE
VALUE 11 THRU
THRU 4.
4.

IF
IF Limerick
Limerick City Code
DISPLAY
DISPLAY "Hey,
"Hey, we're
we're home."
home."
END-IF 6
END-IF
IF
IF UniversityCity
UniversityCity Dublin FALSE
PERFORM
PERFORM CalcRentSurcharge
CalcRentSurcharge Limerick FALSE
END-IF
END-IF Cork FALSE
Galway FALSE
Sligo FALSE
Waterford TRUE
UniversityCity FALSE
171
01
01 InputChar
InputChar PIC
PIC X.
X.
88
88 Vowel
Vowel VALUE
VALUE "A","E","I","O","U".
"A","E","I","O","U".
88
88 Consonant
Consonant VALUE
VALUE "B"
"B" THRU
THRU "D",
"D", "F","G","H"
"F","G","H"
"J"
"J" THRU
THRU "N",
"N", "P"
"P" THRU
THRU "T"
"T"
"V"
"V" THRU
THRU "Z".
"Z".
88
88 Digit
Digit VALUE
VALUE "0"
"0" THRU
THRU "9".
"9".
88
88 LowerCase
LowerCase VALUE
VALUE "a"
"a" THRU
THRU "z".
"z".
88
88 ValidChar
ValidChar VALUE
VALUE "A"
"A" THRU
THRU "Z","0"
"Z","0" THRU
THRU "9".
"9".

IF
IF ValidChar
ValidChar Input Char
DISPLAY
DISPLAY "Input
"Input OK."
OK."
END-IF E
END-IF
IF
IF LowerCase
LowerCase Vowel TRUE
DISPLAY
DISPLAY "Not
"Not Upper
Upper Case"
Case" Consonant FALSE
END-IF Digit FALSE
END-IF
IF LowerCase FALSE
IF Vowel
Vowel ValidChar TRUE
Display
Display "Vowel
"Vowel entered."
entered."
END-IF
END-IF
172
01
01 InputChar
InputChar PIC
PIC X.
X.
88
88 Vowel
Vowel VALUE
VALUE "A","E","I","O","U".
"A","E","I","O","U".
88
88 Consonant
Consonant VALUE
VALUE "B"
"B" THRU
THRU "D",
"D", "F","G","H"
"F","G","H"
"J"
"J" THRU
THRU "N",
"N", "P"
"P" THRU
THRU "T"
"T"
"V"
"V" THRU
THRU "Z".
"Z".
88
88 Digit
Digit VALUE
VALUE "0"
"0" THRU
THRU "9".
"9".
88
88 LowerCase
LowerCase VALUE
VALUE "a"
"a" THRU
THRU "z".
"z".
88
88 ValidChar
ValidChar VALUE
VALUE "A"
"A" THRU
THRU "Z","0"
"Z","0" THRU
THRU "9".
"9".

IF
IF ValidChar
ValidChar Input Char
DISPLAY
DISPLAY "Input
"Input OK."
OK."
END-IF 4
END-IF
IF
IF LowerCase
LowerCase Vowel FALSE
DISPLAY
DISPLAY "Not
"Not Upper
Upper Case"
Case" Consonant FALSE
END-IF Digit TRUE
END-IF
IF LowerCase FALSE
IF Vowel
Vowel ValidChar TRUE
Display
Display "Vowel
"Vowel entered."
entered."
END-IF
END-IF
173
01
01 InputChar
InputChar PIC
PIC X.
X.
88
88 Vowel
Vowel VALUE
VALUE "A","E","I","O","U".
"A","E","I","O","U".
88
88 Consonant
Consonant VALUE
VALUE "B"
"B" THRU
THRU "D",
"D", "F","G","H"
"F","G","H"
"J"
"J" THRU
THRU "N",
"N", "P"
"P" THRU
THRU "T"
"T"
"V"
"V" THRU
THRU "Z".
"Z".
88
88 Digit
Digit VALUE
VALUE "0"
"0" THRU
THRU "9".
"9".
88
88 LowerCase
LowerCase VALUE
VALUE "a"
"a" THRU
THRU "z".
"z".
88
88 ValidChar
ValidChar VALUE
VALUE "A"
"A" THRU
THRU "Z","0"
"Z","0" THRU
THRU "9".
"9".

IF
IF ValidChar
ValidChar Input Char
DISPLAY
DISPLAY "Input
"Input OK."
OK."
END-IF g
END-IF
IF
IF LowerCase
LowerCase Vowel FALSE
DISPLAY
DISPLAY "Not
"Not Upper
Upper Case"
Case" Consonant FALSE
END-IF Digit FALSE
END-IF
IF LowerCase TRUE
IF Vowel
Vowel ValidChar FALSE
Display
Display "Vowel
"Vowel entered."
entered."
END-IF
END-IF
174
01
01 EndOfFileFlag
EndOfFileFlag PIC
PIC 99 VALUE
VALUE 0.
0. EndOfFileFlag
88
88 EndOfFile
EndOfFile VALUE
VALUE 1.
1.
0
EndOfFile

READ
READ InFile
InFile
AT
AT END
END MOVE
MOVE 11 TO
TO EndOfFileFlag
EndOfFileFlag
END-READ
END-READ
PERFORM
PERFORM UNTIL
UNTIL EndOfFile
EndOfFile
Statements
Statements
READ
READ InFile
InFile
AT
AT END
END MOVE
MOVE 11 TO
TO EndOfFileFlag
EndOfFileFlag
END-READ
END-READ
END-PERFORM
END-PERFORM
175
01
01 EndOfFileFlag
EndOfFileFlag PIC
PIC 99 VALUE
VALUE 0.
0. EndOfFileFlag
88
88 EndOfFile
EndOfFile VALUE
VALUE 1.
1.
1
EndOfFile

READ
READ InFile
InFile
AT
AT END
END MOVE
MOVE 11 TO
TO EndOfFileFlag
EndOfFileFlag
END-READ
END-READ
PERFORM
PERFORM UNTIL
UNTIL EndOfFile
EndOfFile
Statements
Statements
READ
READ InFile
InFile
AT
AT END
END MOVE
MOVE 11 TO
TO EndOfFileFlag
EndOfFileFlag
END-READ
END-READ
END-PERFORM
END-PERFORM
176
Using the SET
verb.
FILLER
01
01 FILLER
FILLER PIC
PIC 99 VALUE
VALUE 0.
0.
88 0
88 EndOfFile
EndOfFile VALUE
VALUE 1.
1.
88
88 NotEndOfFile
NotEndOfFile VALUE
VALUE 0.
0. EndOfFile 1
NotEndOfFile 0

READ
READ InFile
InFile
AT
AT END
END SET
SET EndOfFile
EndOfFile TO
TO TRUE
TRUE
END-READ
END-READ
PERFORM
PERFORM UNTIL
UNTIL EndOfFile
EndOfFile
Statements
Statements
READ
READ InFile
InFile
AT
AT END
END SET
SET EndOfFile
EndOfFile TOTO TRUE
TRUE
END-READ
END-READ
END-PERFORM
END-PERFORM
Set
Set NotEndOfFile
NotEndOfFile TO TO TRUE.
TRUE. 177
Using the SET
verb.
FILLER
01
01 FILLER
FILLER PIC
PIC 99 VALUE
VALUE 0.
0.
88 1
88 EndOfFile
EndOfFile VALUE
VALUE 1.
1.
88
88 NotEndOfFile
NotEndOfFile VALUE
VALUE 0.
0. EndOfFile 1
NotEndOfFile 0

READ
READ InFile
InFile
AT
AT END
END SET
SET EndOfFile
EndOfFile TO
TO TRUE
TRUE
END-READ
END-READ
PERFORM
PERFORM UNTIL
UNTIL EndOfFile
EndOfFile
Statements
Statements
READ
READ InFile
InFile
AT
AT END
END SET
SET EndOfFile
EndOfFile TOTO TRUE
TRUE
END-READ
END-READ
END-PERFORM
END-PERFORM
Set
Set NotEndOfFile
NotEndOfFile TO TO TRUE.
TRUE. 178
verb.
FILLER
01
01 FILLER
FILLER PIC
PIC 99 VALUE
VALUE 0.
0.
88 0
88 EndOfFile
EndOfFile VALUE
VALUE 1.
1.
88
88 NotEndOfFile
NotEndOfFile VALUE
VALUE 0.
0. EndOfFile 1
NotEndOfFile 0

READ
READ InFile
InFile
AT
AT END
END SET
SET EndOfFile
EndOfFile TO
TO TRUE
TRUE
END-READ
END-READ
PERFORM
PERFORM UNTIL
UNTIL EndOfFile
EndOfFile
Statements
Statements
READ
READ InFile
InFile
AT
AT END
END SET
SET EndOfFile
EndOfFile TOTO TRUE
TRUE
END-READ
END-READ
END-PERFORM
END-PERFORM
Set
Set NotEndOfFile
NotEndOfFile TO TO TRUE.
TRUE. 179
FD
FD StudentFile.
StudentFile.
01 StudentDetails.
01 StudentDetails.
88
88 EndOfFile
EndOfFile VALUE
VALUE HIGH-VALUES.
HIGH-VALUES.
02 StudentId
02 StudentId PIC
PIC 9(7).
9(7).
02 StudentName.
02 StudentName.
03
03 Surname
Surname PIC
PIC X(8).
X(8).
03 Initials
03 Initials PIC XX.
PIC XX.
02 DateOfBirth.
02 DateOfBirth.
03
03 YOBirth
YOBirth PIC
PIC 9(2).
9(2).
03 MOBirth
03 MOBirth PIC 9(2).
PIC 9(2).
03 DOBirth
03 DOBirth PIC
PIC 9(2).
9(2).
02 CourseCode
02 CourseCode PIC X(4).
PIC X(4).
02 Grant
02 Grant PIC
PIC 9(4).
9(4).
02 Gender
02 Gender PIC X.
PIC X.

PROCEDURE
PROCEDURE DIVISION.
DIVISION.
Begin.
Begin.
OPEN
OPEN INPUT
INPUT StudentFile
StudentFile
READ StudentFile
READ StudentFile
AT
AT END
END SET
SET EndOfFile
EndOfFile TO
TO TRUE
TRUE
END-READ
END-READ
PERFORM
PERFORM UNTIL
UNTIL EndOfFile
EndOfFile
DISPLAY
DISPLAY StudentId SPACE
StudentId SPACE StudentName
StudentName SPACE
SPACE CourseCode
CourseCode
READ StudentFile
READ StudentFile
AT
AT END
END SET
SET EndOfFile
EndOfFile TO
TO TRUE
TRUE
END-READ
END-READ
END-PERFORM
END-PERFORM
CLOSE
CLOSE StudentFile
StudentFile
STOP RUN.
STOP RUN. 180
The
Evaluate
 Identifier 
 Literal 
 
 CondExpression 
EVALUATE  
 ArithExpression 
 TRUE 
 
 FALSE 
    
    
    
    
   ANY   
   Condition   
    
 WHEN   TRUE   StatementBlock 
   FALSE   
    
   Identifier   Identifier   
      THRU     
  [ NOT]  Literal    THROUGH 
  Literal   
    ArithExpression    ArithExpression     
   

[ WHEN OTHER StatementBlock]


END - EVALUATE

181
1 2 3 4 5 6 7 8 9 10
W I L L I A M S

EVALUATE TRUE Position


WHEN L-Arrow 2 THRU 10 PERFORM MoveLeft
WHEN R-Arrow 1 THRU 9 PERFORM MoveRight
WHEN L-Arrow 1 MOVE 10 TO Position
WHEN R-Arrow 10 MOVE 1 TO Position
WHEN DeleteKey 1 PERFORM CantDelete
WHEN Character ANY PERFORM InsertChar
WHEN OTHER PERFORM DisplayErrorMessage
END-EVALUATE

182
Decision Table
Implementation.
Gender M F M F M F M F
Age <20 <20 20-40 20-40 40> 40> 20-40 20-40 etc
Service Any Any <10 <10 <10 <10 10-20 10-20 etc
% Bonus 5 10 12 13 20 15 14 23

EVALUATE Gender TRUE TRUE


WHEN "M" Age<20 ANY MOVE 5 TO Bonus
WHEN "F" Age<20 ANY MOVE 10 TO Bonus
WHEN "M" Age>19 AND <41 Service<10 MOVE 12 TO Bonus
WHEN "F" Age>19 AND <41 Service<10 MOVE 13 TO Bonus
WHEN "M" Age>40 Service<10 MOVE 20 TO Bonus
WHEN "F" Age>40 Service<10 MOVE 15 TO Bonus
: : : : :
: : : : :
WHEN "F" ANY Service>20 MOVE 25 TO Bonus
END-EVALUATE

183
Design
ing
Progra
ms

184
COBOL

 COBOL is an acronym standing for Common Business Oriented Language.

 COBOL programs are (mostly) written for the vertical market.

 COBOL programs tend to be long lived.

 Because of this longevity ease of program maintenance is an important


consideration.

 Why is program maintenance important?

185
life.
Testing
Coding 15%
7%

Analysis
and
Design 9%

Zelkowitz
ACM 1978
p202

Maintenance
67%

Maintenance Costs are only as low as this because many systems


become so unmaintainable early in their lives that they have to be
SCRAPPED !! :- B. Boehm 186
Program
Maintenance.
 Program maintenance is an umbrella term that covers;
Œ Changing the program to fix bugs that appear in
the system.
Changing the program to reflect changes in the
environment.
ŽChanging the program to reflect changes in the
users perception of the requirements.
Changing the program to include extensions to
the user requirements (i.e. new requirements).
 What do these all have in common?

CHANGING THE PROGRAM.

187
How should write your
programs?

 You should write your programs with the expectation that they will
have to be changed.

 This means that you should;


 write programs that are easy to read.
write programs that are easy to understand.
write programs that are easy to change.

 You should write your programs as you would like them written if you
had to maintain them.

188
Efficiency vs
Clarity.
 Many programmers are overly concerned about making their
programs as efficient as possible (in terms of the speed of
execution or the amount of memory used).
 But the proper concern of a programmer, and particularly a
COBOL programmer, is not this kind of efficiency, it is clarity.
 As a rule 70% of the work of the program will be done in 10%
of the code.
 It is therefore a pointless exercise to try to optimize the whole
program, especially if this has to be done at the expense of
clarity.
 Write your program as clearly as possible and then, if its too
slow, identify the 10% of the code where the work is being
done and optimize it.
189
programs?
 We shouldn’t design our programs, when we want to create
programs that do not work.
 We shouldn’t design when we want to produce programs that do
not solve the problem specified.
 When we want to create programs that;
get the wrong inputs,
or perform the wrong transformations on them
or produce the wrong outputs
then we shouldn’t bother to design our programs.
 But if we want to create programs that work, we
cannot avoid design.
 The only question is;
will it be a good design or a bad design 190
Design.

 The first step to producing a good design is to design


consciously.
 Subconscious design means that design is done while
constructing the program. This never leads to good results.
 Conscious design starts by separating the design task from the
task of program construction.
 Design, consists of devising a solution to the problem specified.
 Construction, consists of taking the design and encoding the
solution using a particular programming language.

191
construction?
 Separating program design from program construction makes both
tasks easier.
 Designing before construction, allows us to plan our solution to the
problem - instead of stumbling from one incorrect solution to
another.
 Good program structure results from planing and design. It is
unlikely to result from ad hoc tinkering.
 Designing helps us to get an overview of the problem and to think
about the solution without getting bogged down by the details of
construction.
 It helps us to iron out problems with the specification and to discover
any bugs in our solution before we commit it to code (see next slide).
 Design allows us to develop portable solutions

192
Relative cost of fixing a bug.

In Production
x82

In
Construction
x20

193
Design Notations.
 A number of notations have been suggested to assist the
programmer with the task of program design.
 Some notations are textual and others graphical.
 Some notations can actually assist in the design process.
 While others merely articulate the design.

194
Flowcharts as design tools.

195
Structured Flowcharts as design
tools.

196
Structured English.
For
Foreach
eachtransaction
transactionrecord
recorddodothe
thefollowing
following
IF
IFthe
therecord
recordisisaareceipt
receiptthen
then
add
add11totothe
theReceiptsCount
ReceiptsCount
add
addthe
theAmount
Amountto tothe
theBalance
Balance
otherwise
otherwise
add
add11totothe
thePaymentsCount
PaymentsCount
subtract
subtractthe
theAmount
Amountfrom fromthe
theBalance
Balance
EndIF
EndIF
add
add11totothe
theRecordCount
RecordCount
Write
Writethe
theBalance
Balanceto tothe
theCustomerFile
CustomerFile

When
Whenthe
thefile
filehas
hasbeen
beenprocessed
processed
Output
Output the
theReceiptsCount
ReceiptsCount
the
thePaymentsCount
PaymentsCount
and
andthe
theRecordCount
RecordCount
197
The Jackson Method.

198
Warnier-Orr
Diagrams.

 OpenFiles
 ProcessRecords

   ProcessReceipt
  
  RecordType ? ⊕
UpdateCustomerBalance    ProcessPayment
  
  WriteNewBalance

 PrintTotals
 CloseFiles

199
Introduction
to
Diagrammatic
Stepwise
Refinement

200
DIAGRAMMATIC STEPWISE REFINEMENT (DSR).

an approach to program design based on

 The Program Structure Diagrams used in the Jackson


Method (JSP)
 Wirth's Stepwise Refinement approach to program
design.

201
Steps in the DSR
approach
1. Define the problem completely.
2. Work out what needs to be done to solve the problem.
3. Using Stepwise Refinement, design a Program Structure
Diagram (PSD) to represent your solution to the problem.
4. Write out the Executable Operations needed to produce the
output from the input.
5. Assign the Executable Operations to the appropriate places in the
PSD.
6. Insert the Iteration and Selection conditions.
7. Test your solution using test data.
8. Translate the populated PSD into code.

202
Stepwise Refinement

Is an approach to program design which involves


breaking a task into sub-tasks.
Each sub-task is in turn broken into further sub-tasks.
This process continues until the sub-tasks are so simple
that their implementation is straight forward.

203
Diagrams
Program Structure Diagrams (PSDs) are used to
represent the hierarchy of tasks and sub-tasks
created by Stepwise Refinement.
They are drawn using the three classic constructs
of Structured Programming.

 Sequence

 Selection

 Iteration

204
Sequence PSD

PRINT
REPORT

PRINT PRINT PRINT


REPORT REPORT REPORT
HEADINGS BODY FOOTING

205
Selection PSD

COUNT
STUDENT

ADD TO ADD TO
MALES FEMALES

206
Selection with Null part

COUNT
STUDENT

ADD TO ADD TO
LM51 COUNT LM60 COUNT

207
Iteration PSD

PROCESS
ACCOUNTS

PROCESS
ACCOUNT

208
Iteration PSD - Explicit Repeat
Loop

PROCESS
ACCOUNTS

PROCESS PROCESS
FIRST REMAINING
ACCOUNT ACCOUNTS

PROCESS
ACCOUNT
209
Iteration PSD
PRINT
COUNTRY
BODY

INITIALIZE PROCESS PRINT


COUNTY COUNTY COUNTY
TOTALS RECORD TOTALS

Print-Country-Body is an iteration of three components.


This is equivalent to ;
an iteration of one component which is in turn a sequence
of three. 210
Iteration PSD
PRINT
COUNTRY
BODY

*
PRINT
COUNTY
REPORT

INITIALIZE PROCESS PRINT


COUNTY COUNTY COUNTY
TOTALS RECORD TOTALS

211
Payroll Proof Totals Program
Specification
Write a program to produce proof totals for a weekly payroll. The
payroll file consists of records with the following format:-
COL 1 Record-Type PIC 9.
1 = Regular
2 = Overtime
3 = Bonus
COLS 2-6 Employee-Number PIC 9(5).
COLS 7-11 Earnings PIC 9(3)V99.
(in pounds and pence)
The print layout should be as follows:

PAYROLL
PAYROLLPROOF
PROOFTOTALS
TOTALS
Regular
RegularEarnings
Earnings:: 25
25 $2,111.23
$2,111.23
Overtime
OvertimeEarnings
Earnings:: 22 $21.50
$21.50
Bonus
BonusEarnings
Earnings:: 66 $123.45
$123.45
212
Applying DSR to the Payroll Proof Totals Program

1. Define the problem completely


2. Work out what needs to be done to solve the problem.
3. Using Stepwise Refinement design a Program
Structure Diagram (PSD) to represent your solution to
the problem.

213
Print
Proof Totals
Report

214
Print
Proof Totals
Report

Process Print
Payroll Proof
Records Totals

215
Print
Proof Totals
Report

Process Print
Payroll Proof
Records Totals

*
Process A
Payroll
Record

216
Print
Proof Totals
Report

Process Print
Payroll Proof
Records Totals

*
Process A
Payroll
Record
o

Add To Add To Add To


Regular Overtime Bonus

217
Print
Proof Totals
Report

Process Print
Payroll Proof
Records Totals

*
Process A Print Print Print Print
Payroll Report Regular Overtime Bonus
Record Headings Totals Totals Totals
o

Add To Add To Add To


Regular Overtime Bonus

218
4. Write out the Executable Operations needed to
produce the output from the input.
1.1. OPEN
OPENOUTPUT
OUTPUTPrint-File.
Print-File.
2.2. CLOSE Print-File.
CLOSE Print-File.
3.3. WRITE
WRITEPrint-Line
Print-LineFROM
FROMHeading-Line
Heading-LineAFTER
AFTERADVANCING
ADVANCINGPAGE.
PAGE.
4.4. WRITE
WRITE Print-Line FROM Regular-Line AFTER ADVANCING 1LINE.
Print-Line FROM Regular-Line AFTER ADVANCING 1 LINE.
5.5. WRITE
WRITE Print-Line FROM Overtime-Line AFTER ADVANCING 1LINE.
Print-Line FROM Overtime-Line AFTER ADVANCING 1 LINE.
6.6. WRITE Print-Line FROM Bonus-Line AFTER ADVANCING
WRITE Print-Line FROM Bonus-Line AFTER ADVANCING 1 LINE. 1 LINE.
7.7. MOVE
MOVERegular-Total
Regular-TotalTO TOPrint-Reg-Total.
Print-Reg-Total.
8.8. MOVE
MOVE Overtime-Total TOPrint-Overtime-Total.
Overtime-Total TO Print-Overtime-Total.
9.9. MOVE Bonus-Total TO Print-Bonus-Total.
MOVE Bonus-Total TO Print-Bonus-Total.
10.
10. MOVE
MOVERegular-Count
Regular-CountTO TOPrint-Reg-Count.
Print-Reg-Count.
11.
11. MOVE
MOVE Overtime-Count TOPrint-Over-Count.
Overtime-Count TO Print-Over-Count.
12.
12. MOVE Bonus-Count TO Print-Bonus-Count.
MOVE Bonus-Count TO Print-Bonus-Count.
13.
13. ADD
ADDEarnings
EarningsTOTORegular-Total.
Regular-Total.
14.
14. ADD Earnings TO Overtime-Total.
ADD Earnings TO Overtime-Total.
15.
15. ADD
ADDEarnings
EarningsTOTOBonus-Total.
Bonus-Total.
16.
16. ADD
ADD11TO
TORegular-Count.
Regular-Count.
17.
17. ADD 1 TO Overtime-Count.
ADD 1 TO Overtime-Count.
18.
18. ADD
ADD11TO
TOBonus-Count.
Bonus-Count.
19.
19. READ
READPayroll-File
Payroll-File
AT
AT ENDSET
END SETEnd-of-File
End-of-FileTO TOTRUE
TRUE
END-READ.
END-READ.
20.
20. OPEN
OPENINPUT
INPUTPayroll-File.
Payroll-File.
21. CLOSE Payroll-File.
21. CLOSE Payroll-File.
219
5. Assign the Executable Operations to the
appropriate places in the PSD.

Algorithm
For all Executable Operations.
– Get an Executable Operation.
– Ask "To what component/components must I attach this
operation to get the program to work?".
– If there are already operations attached to a target component
then a further question must be asked ; "Where, in relation to the
existing operations, does this operation go?".

220
Print
Proof Totals
Report

Process Print
Payroll Proof
Records Totals

*
Process A Print Print Print Print
Payroll Report Regular Overtime Bonus
Record Headings Totals Totals Totals
o

1. OPEN OUTPUT Print-File.


Add To Add To Add To 2. CLOSE Print-File.
Regular Overtime Bonus

221
Print
Proof Totals
Report

1 Process Print 2
Payroll Proof
Records Totals

*
Process A Print Print Print Print
Payroll Report Regular Overtime Bonus
Record Headings Totals Totals Totals
o

1. OPEN OUTPUT Print-File.


Add To Add To Add To 2. CLOSE Print-File.
Regular Overtime Bonus
3. WRITE Print-Line FROM Heading-Line ...
4. WRITE Print-Line FROM Regular-Line ...
5. WRITE Print-Line FROM Overtime-Line ...
6. WRITE Print-Line FROM Bonus-Line ...

222
Print
Proof Totals
Report

1 Process Print 2
Payroll Proof
Records Totals

*
Process A Print Print Print Print
Payroll Report Regular Overtime Bonus
Record Headings Totals Totals Totals
o
3 4 5 6

3. WRITE Print-Line FROM Heading-Line ...


Add To Add To Add To 4. WRITE Print-Line FROM Regular-Line ...
Regular Overtime Bonus 5. WRITE Print-Line FROM Overtime-Line ...
6. WRITE Print-Line FROM Bonus-Line ...
7. MOVE Regular-Total TO Print-Reg-Total.
8. MOVE Overtime-Total TO Print-Overtime-Total.
9. MOVE Bonus-Total TO Print-Bonus-Total.
223
Print
Proof Totals
Report

1 Process Print 2
Payroll Proof
Records Totals

*
Process A Print Print Print Print
Payroll Report Regular Overtime Bonus
Record Headings Totals Totals Totals
o
3 7,4 8,5 9,6

7. MOVE Regular-Total TO Print-Reg-Total.


Add To Add To Add To 8. MOVE Overtime-Total TO Print-Overtime-Total.
Regular Overtime Bonus 9. MOVE Bonus-Total TO Print-Bonus-Total.
10. MOVE Regular-Count TO Print-Reg-Count.
11. MOVE Overtime-Count TO Print-Over-Count.
12. MOVE Bonus-Count TO Print-Bonus-Count.

224
Print
Proof Totals
Report

1 Process Print 2
Payroll Proof
Records Totals

*
Process A Print Print Print Print
Payroll Report Regular Overtime Bonus
Record Headings Totals Totals Totals
o
3 7,10,4
10 11,8,5
11 12,9,6
12

10. MOVE Regular-Count TO Print-Reg-Count.


Add To Add To Add To 11. MOVE Overtime-Count TO Print-Over-Count.
Regular Overtime Bonus 12. MOVE Bonus-Count TO Print-Bonus-Count.
13. ADD Earnings TO Regular-Total.
14. ADD Earnings TO Overtime-Total.
15. ADD Earnings TO Bonus-Total.
16. ADD 1 TO Regular-Count.
17. ADD 1 TO Overtime-Count. 225
18. ADD 1 TO Bonus-Count.
Print
Proof Totals
Report

1 Process Print 2
Payroll Proof
Records Totals

*
Process A Print Print Print Print
Payroll Report Regular Overtime Bonus
Record Headings Totals Totals Totals
o
3 7,10,4 11,8,5 12,9,6

13. ADD Earnings TO Regular-Total.


Add To Add To Add To 14. ADD Earnings TO Overtime-Total.
Regular Overtime Bonus 15. ADD Earnings TO Bonus-Total.
16. ADD 1 TO Regular-Count.
17. ADD 1 TO Overtime-Count.
18. ADD 1 TO Bonus-Count.
14,17 15,18 19. READ Payroll-File
AT END SET End-of-File TO TRUE
226
END-READ.
Print
Proof Totals
Report

1,19 Process Print 2


Payroll Proof
Records Totals

*
Process A Print Print Print Print
Payroll Report Regular Overtime Bonus
Record Headings Totals Totals Totals
o
3 7,10,4 11,8,5 12,9,6

19. READ Payroll-File


Add To Add To Add To AT END SET End-of-File TO TRUE
Regular Overtime Bonus END-READ.

13,16 14,17 15,18


227
Print
Proof Totals
Report

1,19 Process Print 2


Payroll Proof
Records Totals

*
Process A 19 Print Print Print Print
Payroll Report Regular Overtime Bonus
Record Headings Totals Totals Totals
o
3 7,10,4 11,8,5 12,9,6

19. READ Payroll-File


Add To Add To Add To AT END SET End-of-File TO TRUE
Regular Overtime Bonus END-READ.
20. OPEN INPUT Payroll-File.
21. CLOSE Payroll-File.
13,16 14,17 15,18
228
Print
Proof Totals
Report

1,20,19
20 Process Print 2,21
Payroll Proof
Records Totals

*
Process A 19 Print Print Print Print
Payroll Report Regular Overtime Bonus
Record Headings Totals Totals Totals
o
3 7,10,4 11,8,5 12,9,6

20. OPEN INPUT Payroll-File.


Add To Add To Add To 21. CLOSE Payroll-File.
Regular Overtime Bonus

13,16 14,17 15,18


229
6. Insert the Iteration and Selection
conditions.

 Go to each iteration component and ask;


"What iteration statement must I use here to get the program
to work correctly?".
Write the Iteration statement, give it a number and insert its
number into the diagram.

 Go to each selection component and ask;


" What selection statement must I use here to get the program
to work correctly?".
Write the Selection statement, give it a number and insert its
number into the diagram.

230
Print
Proof Totals
Report

1,20,19 Process Print 2,21


Payroll Proof
Records Totals
1
*
Process A 19 Print Print Print Print
Payroll Report Regular Overtime Bonus
Record Headings Totals Totals Totals
o
3 7,10,4 11,8,5 12,9,6

Add To Add To Add To


Regular Overtime Bonus 1. PERFORM Process-Payroll-Records
UNTIL End-of-File.

13,16 14,17 15,18


231
Print Using IF...ELSE
Proof Totals
Report

1,20,19 Process Print 2,21


Payroll Proof
Records Totals
1
*
Process A 19 Print Print Print Print
Payroll Report Regular Overtime Bonus
Record Headings Totals Totals Totals
o 2
3 7,10,4 11,8,5 12,9,6

Add To Add To Add To


Regular Overtime Bonus 1. PERFORM Process-Payroll-Records
UNTIL End-of-File.
2. IF Regular-Rec PERFORM Add-to-Regular
ELSE
13,16 14,17 15,18 IF Overtime-Rec PERFORM Add-to-Overtime
ELSE PERFORM Add-to-Bonus
END-IF 232
END-IF.
Print Using the Evaluate
Proof Totals
Report

1,20,19 Process Print 2,21


Payroll Proof
Records Totals
1
*
Process A 19 Print Print Print Print
Payroll Report Regular Overtime Bonus
Record Headings Totals Totals Totals
o 2
3 7,10,4 11,8,5 12,9,6

Add To Add To Add To


Regular Overtime Bonus 1. PERFORM Process-Payroll-Records
UNTIL End-of-File.
2. EVALUATE TRUE
WHEN Regular-Rec PERFORM Add-to-Regular
13,16 14,17 15,18 WHEN Overtime-Rec PERFORM Add-to-
Overtime
WHEN Bonus-Rec PERFORM Add-to-Bonus
233
END-EVALUATE.
data.
Print Type Emp-No Earnings
Proof Totals 1 1234 050.25
Report 2 1234 025.50
1 2345 120.25
3 1234 010.50

1,20,19 Process Print 2,21


Payroll Proof
Records Totals
1
*
Process A 19 Print Print Print Print
Payroll Report Regular Overtime Bonus
Record Headings Totals Totals Totals
o 2
3 7,10,4 11,8,5 12,9,6

Add To Add To Add To 000.00 000


Regular Overtime Bonus 000.00 000
Employee-Rec 000.00
000.00 000
000
Type Emp-No Earnings

13,16 14,17 15,18 11 1234 050.25 000.00 234 000


1234 050.25 000.00 000
data.
Print Type Emp-No Earnings
Proof Totals 1 1234 050.25
Report 2 1234 025.50
1 2345 120.25
3 1234 010.50

1,20,19 Process Print 2,21


Payroll Proof
Records Totals
1
*
Process A 19 Print Print Print Print
Payroll Report Regular Overtime Bonus
Record Headings Totals Totals Totals
o 2
3 7,10,4 11,8,5 12,9,6

Add To Add To Add To 050.25 001


Regular Overtime Bonus 050.25 001
Employee-Rec 000.00
000.00 000
000
Type Emp-No Earnings

13,16 14,17 15,18 11 1234 050.25 000.00 235 000


1234 050.25 000.00 000
data.
Print Type Emp-No Earnings
Proof Totals 1 1234 050.25
Report 2 1234 025.50
1 2345 120.25
3 1234 010.50

1,20,19 Process Print 2,21


Payroll Proof
Records Totals
1
*
Process A 19 Print Print Print Print
Payroll Report Regular Overtime Bonus
Record Headings Totals Totals Totals
o 2
3 7,10,4 11,8,5 12,9,6

Add To Add To Add To 050.25 001


Regular Overtime Bonus 050.25 001
Employee-Rec 000.00
000.00 000
000
Type Emp-No Earnings

13,16 14,17 15,18 22 1234 025.50 000.00 236 000


1234 025.50 000.00 000
data.
Print Type Emp-No Earnings
Proof Totals 1 1234 050.25
Report 2 1234 025.50
1 2345 120.25
3 1234 010.50

1,20,19 Process Print 2,21


Payroll Proof
Records Totals
1
*
Process A 19 Print Print Print Print
Payroll Report Regular Overtime Bonus
Record Headings Totals Totals Totals
o 2
3 7,10,4 11,8,5 12,9,6

Add To Add To Add To 050.25 001


Regular Overtime Bonus 050.25 001
Employee-Rec 025.50
025.50 001
001
Type Emp-No Earnings

13,16 14,17 15,18 22 1234 025.50 000.00 237 000


1234 025.50 000.00 000
data.
Print Type Emp-No Earnings
Proof Totals 1 1234 050.25
Report 2 1234 025.50
1 2345 120.25
3 1234 010.50

1,20,19 Process Print 2,21


Payroll Proof
Records Totals
1
*
Process A 19 Print Print Print Print
Payroll Report Regular Overtime Bonus
Record Headings Totals Totals Totals
o 2
3 7,10,4 11,8,5 12,9,6

Add To Add To Add To 050.25 001


Regular Overtime Bonus 050.25 001
Employee-Rec 025.50
025.50 001
001
Type Emp-No Earnings

13,16 14,17 15,18 11 2345 120.25 000.00 238 000


2345 120.25 000.00 000
data.
Print Type Emp-No Earnings
Proof Totals 1 1234 050.25
Report 2 1234 025.50
1 2345 120.25
3 1234 010.50

1,20,19 Process Print 2,21


Payroll Proof
Records Totals
1
*
Process A 19 Print Print Print Print
Payroll Report Regular Overtime Bonus
Record Headings Totals Totals Totals
o 2
3 7,10,4 11,8,5 12,9,6

Add To Add To Add To 170.50 002


Regular Overtime Bonus 170.50 002
Employee-Rec 025.50
025.50 001
001
Type Emp-No Earnings

13,16 14,17 15,18 11 2345 120.25 000.00 239 000


2345 120.25 000.00 000
data.
Print Type Emp-No Earnings
Proof Totals 1 1234 050.25
Report 2 1234 025.50
1 2345 120.25
3 1234 010.50

1,20,19 Process Print 2,21


Payroll Proof
Records Totals
1
*
Process A 19 Print Print Print Print
Payroll Report Regular Overtime Bonus
Record Headings Totals Totals Totals
o 2
3 7,10,4 11,8,5 12,9,6

Add To Add To Add To 170.50 002


Regular Overtime Bonus 170.50 002
Employee-Rec 025.50
025.50 001
001
Type Emp-No Earnings

13,16 14,17 15,18 33 1234 010.50 000.00 240 000


1234 010.50 000.00 000
data.
Print Type Emp-No Earnings
Proof Totals 1 1234 050.25
Report 2 1234 025.50
1 2345 120.25
3 1234 010.50

1,20,19 Process Print 2,21


Payroll Proof
Records Totals
1
*
Process A 19 Print Print Print Print
Payroll Report Regular Overtime Bonus
Record Headings Totals Totals Totals
o 2
3 7,10,4 11,8,5 12,9,6

Add To Add To Add To 170.50 002


Regular Overtime Bonus 170.50 002
Employee-Rec 025.50
025.50 001
001
Type Emp-No Earnings

13,16 14,17 15,18 33 1234 010.50 010.50 241 001


1234 010.50 010.50 001
7. Test the program using test
data.
Print Type Emp-No Earnings
Proof Totals 1 1234 050.25
Report 2 1234 025.50
1 2345 120.25
3 1234 010.50

1,20,19 Process Print 2,21


Payroll Proof
Records Totals
1
*
Process A 19 Print Print Print Print
Payroll Report Regular Overtime Bonus
Record Headings Totals Totals Totals
o 2
3 7,10,4 11,8,5 12,9,6

Add To Add To Add To 170.50 002


Regular Overtime Bonus 170.50 002
Employee-Rec 025.50
025.50 001
001
Type Emp-No Earnings

13,16 14,17 15,18 HIGH-VALUES 010.50 242 001


HIGH-VALUES 010.50 001
7. Test the program using test
data.
Print Type Emp-No Earnings
Proof Totals 1 1234 050.25
Report 2 1234 025.50
1 2345 120.25
3 1234 010.50

1,20,19 Process Print 2,21


Payroll Proof
Records Totals
1
*
Process A 19 Print Print Print Print
Payroll Report Regular Overtime Bonus
Record Headings Totals Totals Totals
o 2
3 7,10,4 11,8,5 12,9,6

Add To Add To Add To 170.50 002


Regular Overtime Bonus 170.50 002
Employee-Rec 025.50
025.50 001
001
Type Emp-No Earnings

13,16 14,17 15,18 HIGH-VALUES 010.50 243 001


HIGH-VALUES 010.50 001
data.
Print Type Emp-No Earnings
Proof Totals 1 1234 050.25
Report 2 1234 025.50
1 2345 120.25
3 1234 010.50

1,20,19 Process Print 2,21


Payroll Proof
Records Totals
1
*
Process A 19 Print Print Print Print
Payroll Report Regular Overtime Bonus
Record Headings Totals Totals Totals
o 2
3 7,10,4 11,8,5 12,9,6

Add To Add To Add To 170.50 002


Regular Overtime Bonus 170.50 002
Employee-Rec 025.50
025.50 001
001
Type Emp-No Earnings

13,16 14,17 15,18 HIGH-VALUES 010.50 244 001


HIGH-VALUES 010.50 001
8. Translate the populated PSD into COBOL code

 Start at the top of the diagram.


 At each parent component write the sequence of
executable operations, child components and iteration
and selection conditions as statements in a paragraph.
 Replace child components with PERFORMs of the
component name.
 At the top component, use the name as the name of
the first paragraph and preceed it with the
PROCEDURE DIVISION header.
End the sequence with the STOP RUN statement.

245
Print
Proof Totals
Report

1,20,19 Process Print 2,21


Payroll Proof
Records Totals
1
*
Process A 19 Print Print Print Print
Payroll Report Regular Overtime Bonus
Record Headings Totals Totals Totals
o 2
3 7,10,4 11,8,5 12,9,6

Add To Add To Add To


Regular Overtime Bonus

13,16 14,17 15,18


246
Print
Proof Totals
Report

1,20,19 Process Print 2,21


Payroll Proof
Records Totals
1
*
Process A 19 Print Print Print Print
Payroll Report Regular Overtime Bonus
Record Headings Totals Totals Totals
o 2
3 7,10,4 11,8,5 12,9,6
PROCEDURE DIVISION.
Add To Add To Add To Print-Proof-Totals-Report.
Regular Overtime Bonus OPEN INPUT Payroll-File.
OPEN Output Print-File.
Read Payroll-File ....
PERFORM Process-Payroll-Records
UNTIL End-Of-File.
13,16 14,17 15,18 PERFORM Print-Proof-Totals.
CLOSE Print-File.
CLOSE Payroll-File. 247
STOP RUN.
Print
Proof Totals
Report

1,20,19 Process Print 2,21


Payroll Proof
Records Totals
1
*
Process A 19 Print Print Print Print
Payroll Report Regular Overtime Bonus
Record Headings Totals Totals Totals
o 2
3 7,10,4 11,8,5 12,9,6
Process-Payroll-Records.
Add To Add To Add To EVALUATE TRUE
Regular Overtime Bonus WHEN Regular-Rec PERFORM Add-to-Regular
WHEN Overtime-Rec PERFORM Add-to-Overtime
WHEN Bonus-Rec PERFORM Add-to-Bonus
END-EVALUATE.
READ Payroll-File
13,16 14,17 15,18 AT END SET End-Of-File TO TRUE
END-READ.
248
Tables
and
PERFORM..VARYING

249
TaxTotal
Variable = Named location in memory

PAYENum CountyNum TaxPaid

The program
to calculate the
PROCEDURE DIVISION.
Begin. total taxes paid
OPEN INPUT TaxFile for the country
READ TaxFile
AT END SET EndOfTaxFile TO TRUE is easy to
END-READ write.
PERFORM UNTIL EndOfTaxFile
ADD TaxPaid TO TaxTotal
READ TaxFile
BUT.
AT END SET EndOfTaxFile TO TRUE
END-READ What do we do
END-PERFORM. if we want to
DISPLAY "Total taxes are ", TaxTotal calculate the
CLOSE TaxFile
STOP RUN. taxes paid in
each county?
County1 County2 County3 County4 County5
TaxTotal TaxTotal TaxTotal TaxTotal TaxTotal

PROCEDURE DIVISION.
Begin.
OPEN INPUT TaxFile
READ TaxFile
AT END SET EndOfTaxFile TO TRUE
END-READ
PERFORM SumCountyTaxes UNTIL EndOfTaxFile
DISPLAY "County 1 total is ", County1TaxTotal
: : : 24 Statements : : :
DISPLAY "County 26 total is ", County26TaxTotal
CLOSE TaxFile
STOP RUN.
SumCountyTaxes.
IF CountyNum = 1 ADD TaxPaid TO County1TaxTotal
END-IF
: : : 24 Statements : : :
IF CountyNum = 26 ADD TaxPaid TO County26TaxTotal
END-IF
READ TaxFile
AT END SET EndOfTaxFile TO TRUE
END-READ
s
AAtable
tableis
isaacontiguous
contiguoussequence
sequenceofofmemory
memorylocations
locations
called
calledelements
elements, ,which
whichall
allhave
havethe
thesame
samename,
name and
name
name, andare
are
uniquely
uniquelyidentified
identifiedby
bythat
thatname
nameand
andby
bytheir
theirposition
positionin
in
the
thesequence.
sequence.

CountyTax

1 2 3 4 5
10 6

MOVE 10 TO CountyTax(5)

ADD TaxPaid TO CountyTax(CountyNum)

ADD TaxPaid TO CountyTax(CountyNum + 2)


s
AAtable
tableis
isaacontiguous
contiguoussequence
sequenceofofmemory
memorylocations
locations
called
calledelements
elements, ,which
whichall
allhave
havethe
thesame
samename,
name and
name
name, andare
are
uniquely
uniquelyidentified
identifiedby
bythat
thatname
nameand
andby
bytheir
theirposition
positionin
in
the
thesequence.
sequence.

CountyTax
10
1 255 3 4 5 6

MOVE 10 TO CountyTax(5)
55 2
ADD TaxPaid TO CountyTax(CountyNum)

ADD TaxPaid TO CountyTax(CountyNum + 2)


s
AAtable
tableis
isaacontiguous
contiguoussequence
sequenceofofmemory
memorylocations
locations
called
calledelements
elements, ,which
whichall
allhave
havethe
thesame
samename,
name and
name
name, andare
are
uniquely
uniquelyidentified
identifiedby
bythat
thatname
nameand
andby
bytheir
theirposition
positionin
in
the
thesequence.
sequence.

CountyTax
55 10
1 2 3 455 5 6

MOVE 10 TO CountyTax(5)

ADD TaxPaid TO CountyTax(CountyNum)


55 2
ADD TaxPaid TO CountyTax(CountyNum + 2)
s
AAtable
tableis
isaacontiguous
contiguoussequence
sequenceofofmemory
memorylocations
locations
called
calledelements
elements, ,which
whichall
allhave
havethe
thesame
samename,
name and
name
name, andare
are
uniquely
uniquelyidentified
identifiedby
bythat
thatname
nameand
andby
bytheir
theirposition
positionin
in
the
thesequence.
sequence.

CountyTax The position index is called a


55 subscript. 55 10
1 2 3 4 5 6

MOVE 10 TO CountyTax(5)

ADD TaxPaid TO CountyTax(CountyNum)

ADD TaxPaid TO CountyTax(CountyNum + 2)


Subscript
CountyTax

1 2 3 4 5 6
PROCEDURE DIVISION.
Begin.
OPEN INPUT TaxFile
READ TaxFile
AT END SET EndOfTaxFile TO TRUE
END-READ
PERFORM UNTIL EndOfTaxFile
ADD TaxPaid TO CountyTax(CountyNum)
READ TaxFile
AT END SET EndOfTaxFile TO TRUE
END-READ
END-PERFORM. Subscript
PERFORM VARYING Idx FROM 1 BY 1
UNTIL Idx GREATER THAN 26
DISPLAY "County ", CountyNum
" tax total is " CountyTax(Idx)
END-PERFORM
CLOSE TaxFile
STOP RUN.
TaxRecord.
PAYENum CountyName TaxPaid
A-89432 CLARE 7894.55

CountyTax

1 2 3 4 5 6

IF CountyName = "CARLOW"
ADD TaxPaid TO CountyTax(1)
END-IF
IF CountyName = "CAVAN"
ADD TaxPaid TO CountyTax(2)
END-IF
: : : : :
: : : : :
24 TIMES
TaxRecord.
PAYENum CountyName TaxPaid Idx
A-89432 CLARE 7894.55 1

County
CARLOW CAVAN CLARE CORK DONEGAL DUBLIN
1 2 3 4 5 6
CountyTax
500.50 125.75 1000.00 745.55 345.23 123.45
1 2 3 4 5 6

PERFORM VARYING Idx FROM 1 BY 1


UNTIL County(Idx) = CountyName
END-PERFORM
ADD TaxPaid TO CountyTax(Idx)
TaxRecord.
PAYENum CountyName TaxPaid Idx
A-89432 CLARE 7894.55 2

County
CARLOW CAVAN CLARE CORK DONEGAL DUBLIN
1 2 3 4 5 6
CountyTax
500.50 125.75 1000.00 745.55 345.23 123.45
1 2 3 4 5 6

PERFORM VARYING Idx FROM 1 BY 1


UNTIL County(Idx) = CountyName
END-PERFORM
ADD TaxPaid TO CountyTax(Idx)
TaxRecord.
PAYENum CountyName TaxPaid Idx
A-89432 CLARE 7894.55 3

County
CARLOW CAVAN CLARE CORK DONEGAL DUBLIN
1 2 3 4 5 6
CountyTax
500.50 125.75 1000.00 745.55 345.23 123.45
1 2 3 4 5 6

PERFORM VARYING Idx FROM 1 BY 1


UNTIL County(Idx) = CountyName
END-PERFORM
ADD TaxPaid TO CountyTax(Idx)
TaxRecord.
PAYENum CountyName TaxPaid Idx
A-89432 CLARE 7894.55 3

County
CARLOW CAVAN CLARE CORK DONEGAL DUBLIN
1 2 3 4 5 6
CountyTax
500.50 125.75 8894.55 745.55 345.23 123.45
1 2 3 4 5 6

PERFORM VARYING Idx FROM 1 BY 1


UNTIL County(Idx) = CountyName
END-PERFORM
ADD TaxPaid TO CountyTax(Idx)
Tables.
TaxTotals
CountyTax
000000 000000 000000 000000 000000 000000

1 2 3 4 5 6

01 TaxTotals.
02 CountyTax PIC 9(10)V99
OCCURS 26 TIMES.
or
02 CountyTax OCCURS 26 TIMES
PIC 9(10)V99.

e.g.
MOVE ZEROS TO TaxTotals.
MOVE 20 TO CountyTax(5).
262
Elements.
TaxTotals

1 2 3 4 5 6
25 67

CountyTax PayerCount
000000 000000
CountyTaxDetails
01 TaxTotals.
02 CountyTaxDetails OCCURS 26 TIMES.
03 CountyTax PIC 9(10)V99.
03 PayerCount PIC 9(7).

e.g. MOVE 25 TO PayerCount(2).


MOVE 67 TO CountyTax(5).
MOVE ZEROS TO CountyTaxDetails(3).
PERFORM..VARYING
Syntax
  THRU    BEFORE  
PERFORM 1stProc  THROUGH  EndProc   WITH TEST  
       AFTER 
 Identifier 2 
 Identifer1   
VARYING   FROM  IndexName 2 
 IndexName1  Literal 
 
 Identifier3
BY   UNTIL Condition1
 Literal 
  Identifier5  
  Identifier4    
 AFTER   FROM  IndexName 4  
 IndexName3  Literal  
  
 
  Identifier6  
 BY   UNTIL Condition2 
  Literal  
[ StatementBlock END - PERFORM]

264
PERFORM VARYING Idx1 FROM 1 BY 1 UNTIL
Idx1 EQUAL TO 3
DISPLAY Idx1
END-PERFORM.

Idx1
1
Move 1 to Idx1

True
Idx1 = 3 Next Statement
False

Loop Body

Inc Idx1
PERFORM VARYING Idx1 FROM 1 BY 1 UNTIL
Idx1 EQUAL TO 3
DISPLAY Idx1
END-PERFORM.

Idx1
1
Move 1 to Idx1

True
Idx1 = 3 Next Statement
False

Loop Body

Inc Idx1
PERFORM VARYING Idx1 FROM 1 BY 1 UNTIL
Idx1 EQUAL TO 3
DISPLAY Idx1
END-PERFORM.

Idx1
1
Move 1 to Idx1

True
Idx1 = 3 Next Statement
False

Loop Body 1
Inc Idx1
PERFORM VARYING Idx1 FROM 1 BY 1 UNTIL
Idx1 EQUAL TO 3
DISPLAY Idx1
END-PERFORM.

Idx1
2
Move 1 to Idx1

True
Idx1 = 3 Next Statement
False

Loop Body 1
Inc Idx1
PERFORM VARYING Idx1 FROM 1 BY 1 UNTIL
Idx1 EQUAL TO 3
DISPLAY Idx1
END-PERFORM.

Idx1
2
Move 1 to Idx1

True
Idx1 = 3 Next Statement
False

Loop Body 1
Inc Idx1
PERFORM VARYING Idx1 FROM 1 BY 1 UNTIL
Idx1 EQUAL TO 3
DISPLAY Idx1
END-PERFORM.

Idx1
2
Move 1 to Idx1

True
Idx1 = 3 Next Statement
False

Loop Body 1
2
Inc Idx1
PERFORM VARYING Idx1 FROM 1 BY 1 UNTIL
Idx1 EQUAL TO 3
DISPLAY Idx1
END-PERFORM.

Idx1
3
Move 1 to Idx1

True
Idx1 = 3 Next Statement
False

Loop Body 1
2
Inc Idx1
PERFORM VARYING Idx1 FROM 1 BY 1 UNTIL
Idx1 EQUAL TO 3
DISPLAY Idx1
END-PERFORM.

Idx1
3
Move 1 to Idx1

True
Idx1 = 3 Next Statement
False Next Statement

Loop Body 1
2
Inc Idx1

Exit value = 3
PERFORM IterationCount VARYING Idx1 FROM 1 BY 2
UNTIL Idx1 EQUAL TO 5
AFTER Idx2 FROM 6 BY -1
UNTIL Idx2 LESS THAN 4

Move 1 to Idx1 T Idx1 Idx2


Move 6 to Idx2

1 1 6
Y
Idx1 = 5 Next Statement 2 1 5
N
3 1 4
Idx2 < 4
Y
4 3 6
N
Move 6 to Idx2
IterationCount
Inc Idx1
5 3 5
Dec Idx2 6 3 4
x =5 =6
Advanced
Tables.

274
One Dimension
Table.

01 JeansTable.
One Dimension
Table.

1 2 3 4

01 JeansTable.
02 Province OCCURS 4 TIMES.
03 SalesValue PIC 9(8)V99.
03 NumSold PIC 9(7).
One Dimension
Table.

1 2 3 4

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

12346.99 309

Province
SalesValue NumSold
Two Dimension
Table.

1 2 3 4

01 JeansTable.
02 Province OCCURS 4 TIMES.
Two 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.
04 SalesValue PIC 9(8)V99.
04 NumSold PIC 9(7).
Three Dimension
Table.
1 2 3 4

01 JeansTable.
02 Province OCCURS 4 TIMES.
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.
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.
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.
05 SalesValue PIC 9(8)V99.
05 NumSold PIC 9(7).
12346.99 309

Colour
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.
05 NumSold PIC 9(7).
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.
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.
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.
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).
Tables

01 LetterTable.
02 TableValues.
Tables

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

01 LetterTable.
02 TableValues.
03 FILLER PIC X(13)
VALUE "ABCDEFGHIJKLM".
03 FILLER PIC X(13)
VALUE "NOPQRSTUVWXYZ".
Tables

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

01 LetterTable.
02 TableValues.
03 FILLER PIC X(13)
VALUE "ABCDEFGHIJKLM".
03 FILLER PIC X(13)
VALUE "NOPQRSTUVWXYZ".

02 FILLER REDEFINES TableValues.


03 Letter PIC X OCCURS 26 TIMES.
Two Dimension Table of
Values.

50 75 90 75 85 95 35 43 65 40 60 85

01 BonusTable.
02 BonusValues.
03 FILLER PIC X(24)
VALUE "507590758595354365406085".
Two Dimension Table of
Values.

1 2 3 4

50 75 90 75 85 95 35 43 65 40 60 85

01 BonusTable.
02 BonusValues.
03 FILLER PIC X(24)
VALUE "507590758595354365406085".
02 FILLER REDEFINES BonusValues.
03 Province OCCURS 4 TIMES.
Two Dimension Table of
Values.

1 2 3 4
1 2 3 1 2 3 1 2 3 1 2 3
50 75 90 75 85 95 35 43 65 40 60 85

01 BonusTable.
02 BonusValues.
03 FILLER PIC X(24)
VALUE "507590758595354365406085".
02 FILLER REDEFINES BonusValues.
03 Province OCCURS 4 TIMES.
04 Bonus OCCURS 3 TIMES PIC 99.
Changes.
 Creating pre-filled tables without the REDEFINES clause.

01 DayTable VALUE "MonTueWedThrFriSatSun".


02 Day OCCURS 7 TIMES PIC X(3).

 Initializing Tables with values.

01 TaxTable.
02 County OCCURS 32 TIMES.
03 CountyTax PIC 9(5) VALUE ZEROS.
03 CountyName PIC X(12) VALUE SPACES.
295
The
PERFORM
Verb
 Iteration is an important programming construct. We use iteration
when we need to repeat the same instructions over and over again.

 Most programming languages have several iteration keywords (e.g.


WHILE, FOR, REPEAT) which facilitate the creation different
‘types’ of iteration structure.

 COBOL only has one iteration construct; PERFORM.

 But the PERFORM has several variations.

 Each variation is equivalent to one of the iteration ‘types’ available


in other languages.

 This lecture concentrates on three of the PERFORM formats. The


PERFORM..VARYING, the COBOL equivalent of the FOR , will
be introduced later.
297
Paragraphs :- Revisited
 A Paragraph is a block of code to which we have given a name.

 A Paragraph Name is a programmer defined name formed using


the standard rules for programmer defined names (A-Z, 0-9, -).

 A Paragraph Name is ALWAYS terminated with a ‘full-stop’.

 Any number of statements and sentences may be included in a


paragraph, and the last one (at least) must be terminated with a
‘full-stop’.

 The scope of a paragraph is delimited by the occurrence of


another paragraph name or the end of the program text.

298
Paragraph Example
ProcessRecord.
DISPLAY StudentRecord
READ StudentFile
AT END MOVE HIGH-VALUES TO StudentRecord
END-READ.

ProduceOutput.
DISPLAY “Here is a message”.

NOTE
NOTE
The
Thescope
scopeof
of‘ProcessRecord’
‘ProcessRecord’is
is
delimited
delimitedby
bythe
theoccurrence
occurrencethe
the
paragraph
paragraphname
name‘ProduceOutput’.
‘ProduceOutput’.
299
Format 1 Syntax.
   THRU  
PERFORM  1stProc    EndProc  
  THROUGH  

 This is the only type of PERFORM that is not an iteration


construct.
 It instructs the computer to transfer control to an out-of-line
block of code.
 When the end of the block is reached, control reverts to the
statement (not the sentence) immediately following the
PERFORM.
 1stProc and EndProc are the names of Paragraphs or
Sections.
 The PERFORM..THRU instructs the computer to treat the
Paragraphs or Sections from 1stProc TO EndProc as a single
block of code.
300
Example.
Run of PerformFormat1
In
In TopLevel.
TopLevel. Starting
Starting to
to run
run program
program
>>>>
>>>> Now
Now in
in OneLevelDown
OneLevelDown
>>>>>>>>
>>>>>>>> Now in
Now in TwoLevelsDown.
TwoLevelsDown.
>>>> Back in OneLevelDown
>>>> Back in OneLevelDown
Back
Back in
in TopLevel.
TopLevel.
PROCEDURE
PROCEDURE DIVISION.
DIVISION.
TopLevel.
TopLevel.
DISPLAY
DISPLAY"In
"InTopLevel.
TopLevel. Starting
Starting to
to run
run program"
program"
PERFORM
PERFORM OneLevelDown
OneLevelDown
DISPLAY
DISPLAY "Back in
"Back in TopLevel.".
TopLevel.".
STOP RUN.
STOP RUN.
TwoLevelsDown.
TwoLevelsDown.
DISPLAY
DISPLAY ">>>>>>>>
">>>>>>>> Now
Now in
in TwoLevelsDown."
TwoLevelsDown."
OneLevelDown.
OneLevelDown.
DISPLAY
DISPLAY ">>>>
">>>> Now
Now in
in OneLevelDown"
OneLevelDown"
PERFORM
PERFORM TwoLevelsDown
TwoLevelsDown
DISPLAY
DISPLAY ">>>> Back
">>>> Back in
in OneLevelDown".
OneLevelDown".
Example.
Run of PerformFormat1
In
In TopLevel.
TopLevel. Starting
Starting to
to run
run program
program
>>>> Now in OneLevelDown
>>>> Now in OneLevelDown
>>>>>>>>
>>>>>>>> Now
Now in
in TwoLevelsDown.
TwoLevelsDown.
>>>> Back in OneLevelDown
>>>> Back in OneLevelDown
Back
Back in
in TopLevel.
TopLevel.

PROCEDURE
PROCEDURE DIVISION.
DIVISION.
TopLevel.
TopLevel.
DISPLAY
DISPLAY "In
"In TopLevel.
TopLevel. Starting
Starting to
to run
run program"
program"
PERFORM
PERFORMOneLevelDown
OneLevelDown
DISPLAY
DISPLAY "Back
"Back in
in TopLevel.".
TopLevel.".
STOP RUN.
STOP RUN.
TwoLevelsDown.
TwoLevelsDown.
DISPLAY
DISPLAY ">>>>>>>>
">>>>>>>> Now
Now in
in TwoLevelsDown."
TwoLevelsDown."
OneLevelDown.
OneLevelDown.
DISPLAY
DISPLAY ">>>>
">>>> Now
Now in
in OneLevelDown"
OneLevelDown"
PERFORM
PERFORM TwoLevelsDown
TwoLevelsDown
DISPLAY
DISPLAY ">>>>
">>>> Back
Back in
in OneLevelDown".
OneLevelDown".
Example.
Run of PerformFormat1
In
In TopLevel.
TopLevel. Starting
Starting to
to run
run program
program
>>>>
>>>> Now
Now in
in OneLevelDown
OneLevelDown
>>>>>>>>
>>>>>>>> Now
Now in
in TwoLevelsDown.
TwoLevelsDown.
>>>> Back in OneLevelDown
>>>> Back in OneLevelDown
Back
Back in
in TopLevel.
TopLevel.

PROCEDURE
PROCEDURE DIVISION.
DIVISION.
TopLevel.
TopLevel.
DISPLAY
DISPLAY "In
"In TopLevel.
TopLevel. Starting
Starting to
to run
run program"
program"
PERFORM
PERFORM OneLevelDown
OneLevelDown
DISPLAY
DISPLAY "Back in
"Back in TopLevel.".
TopLevel.".
STOP RUN.
STOP RUN.
TwoLevelsDown.
TwoLevelsDown.
DISPLAY
DISPLAY ">>>>>>>>
">>>>>>>> Now
Now in
in TwoLevelsDown."
TwoLevelsDown."
OneLevelDown.
OneLevelDown.
DISPLAY
DISPLAY">>>>
">>>> Now
Now in
inOneLevelDown"
OneLevelDown"
PERFORM
PERFORM TwoLevelsDown
TwoLevelsDown
DISPLAY
DISPLAY ">>>>
">>>> Back
Back in
in OneLevelDown".
OneLevelDown".
Format 1
Example.
Run of PerformFormat1
In
In TopLevel.
TopLevel. Starting
Starting to
to run
run program
program
>>>> Now in OneLevelDown
>>>> Now in OneLevelDown
>>>>>>>>
>>>>>>>> Now
Now in
in TwoLevelsDown.
TwoLevelsDown.
>>>> Back in OneLevelDown
>>>> Back in OneLevelDown
Back
Back in
in TopLevel.
TopLevel.

PROCEDURE
PROCEDURE DIVISION.
DIVISION.
TopLevel.
TopLevel.
DISPLAY
DISPLAY "In
"In TopLevel.
TopLevel. Starting
Starting to
to run
run program"
program"
PERFORM
PERFORM OneLevelDown
OneLevelDown
DISPLAY
DISPLAY "Back in
"Back in TopLevel.".
TopLevel.".
STOP RUN.
STOP RUN.
TwoLevelsDown.
TwoLevelsDown.
DISPLAY
DISPLAY ">>>>>>>>
">>>>>>>> Now
Now in
in TwoLevelsDown."
TwoLevelsDown."
OneLevelDown.
OneLevelDown.
DISPLAY
DISPLAY ">>>>
">>>> Now
Now in
in OneLevelDown"
OneLevelDown"
PERFORM
PERFORMTwoLevelsDown
TwoLevelsDown
DISPLAY
DISPLAY ">>>>
">>>> Back
Back in
in OneLevelDown".
OneLevelDown".
Format 1
Example.
Run of PerformFormat1
In
In TopLevel.
TopLevel. Starting
Starting to
to run
run program
program
>>>> Now in OneLevelDown
>>>> Now in OneLevelDown
>>>>>>>>
>>>>>>>> Now
Now in
in TwoLevelsDown.
TwoLevelsDown.
>>>>
>>>> Back
Back in
in OneLevelDown
OneLevelDown
Back in TopLevel.
Back in TopLevel.

PROCEDURE
PROCEDURE DIVISION.
DIVISION.
TopLevel.
TopLevel.
DISPLAY
DISPLAY "In
"In TopLevel.
TopLevel. Starting
Starting to
to run
run program"
program"
PERFORM
PERFORM OneLevelDown
OneLevelDown
DISPLAY
DISPLAY "Back in
"Back in TopLevel.".
TopLevel.".
STOP RUN.
STOP RUN.
TwoLevelsDown.
TwoLevelsDown.
DISPLAY
DISPLAY">>>>>>>>
">>>>>>>> Now
Now in
inTwoLevelsDown."
TwoLevelsDown."
OneLevelDown.
OneLevelDown.
DISPLAY
DISPLAY ">>>>
">>>> Now
Now in
in OneLevelDown"
OneLevelDown"
PERFORM
PERFORM TwoLevelsDown
TwoLevelsDown
DISPLAY
DISPLAY ">>>>
">>>> Back
Back in
in OneLevelDown".
OneLevelDown".
Example.
Run of PerformFormat1
In
In TopLevel.
TopLevel. Starting
Starting to
to run
run program
program
>>>> Now in OneLevelDown
>>>> Now in OneLevelDown
>>>>>>>>
>>>>>>>> Now
Now in
in TwoLevelsDown.
TwoLevelsDown.
>>>>
>>>> Back
Back in
in OneLevelDown
OneLevelDown
Back
Back in
in TopLevel.
TopLevel.

PROCEDURE
PROCEDURE DIVISION.
DIVISION.
TopLevel.
TopLevel.
DISPLAY
DISPLAY "In
"In TopLevel.
TopLevel. Starting
Starting to
to run
run program"
program"
PERFORM
PERFORM OneLevelDown
OneLevelDown
DISPLAY
DISPLAY "Back in
"Back in TopLevel.".
TopLevel.".
STOP RUN.
STOP RUN.
TwoLevelsDown.
TwoLevelsDown.
DISPLAY
DISPLAY ">>>>>>>>
">>>>>>>> Now
Now in
in TwoLevelsDown."
TwoLevelsDown."
OneLevelDown.
OneLevelDown.
DISPLAY
DISPLAY ">>>>
">>>> Now
Now in
in OneLevelDown"
OneLevelDown"
PERFORM
PERFORM TwoLevelsDown
TwoLevelsDown
DISPLAY
DISPLAY">>>>
">>>> Back
Backin
in OneLevelDown".
OneLevelDown".
Format 1
Example.
Run of PerformFormat1
In
In TopLevel.
TopLevel. Starting
Starting to
to run
run program
program
>>>> Now in OneLevelDown
>>>> Now in OneLevelDown
>>>>>>>>
>>>>>>>> Now
Now in
in TwoLevelsDown.
TwoLevelsDown.
>>>> Back in OneLevelDown
>>>> Back in OneLevelDown
Back
Back in
in TopLevel.
TopLevel.

PROCEDURE
PROCEDURE DIVISION.
DIVISION.
TopLevel.
TopLevel.
DISPLAY
DISPLAY "In
"In TopLevel.
TopLevel. Starting
Starting to
to run
run program"
program"
PERFORM
PERFORM OneLevelDown
OneLevelDown
DISPLAY
DISPLAY"Back
"Backin
in TopLevel.".
TopLevel.".
STOP
STOP RUN.
RUN.
TwoLevelsDown.
TwoLevelsDown.
DISPLAY
DISPLAY ">>>>>>>>
">>>>>>>> Now
Now in
in TwoLevelsDown."
TwoLevelsDown."
OneLevelDown.
OneLevelDown.
DISPLAY
DISPLAY ">>>>
">>>> Now
Now in
in OneLevelDown"
OneLevelDown"
PERFORM
PERFORM TwoLevelsDown
TwoLevelsDown
DISPLAY
DISPLAY ">>>>
">>>> Back
Back in
in OneLevelDown".
OneLevelDown".
Why use the PERFORM
Thru?

PROCEDURE
PROCEDURE DIVISION.
DIVISION.
Begin.
Begin.
PERFORM
PERFORM SumSales
SumSales
STOP
STOP RUN.
RUN.
SumSales.
SumSales.
Statements
Statements
Statements
Statements
IF
IF NoErrorFound
NoErrorFound
Statements
Statements
Statements
Statements
IF
IF NoErrorFound
NoErrorFound
Statements
Statements
Statements
Statements
Statements
Statements
END-IF
END-IF
END-IF.
END-IF.
Go To and PERFORM
THRU
PROCEDURE
PROCEDURE DIVISION
DIVISION
Begin.
Begin.
PERFORM
PERFORM SumSales
SumSales THRU
THRU SumSalesExit
SumSalesExit
STOP
STOP RUN.
RUN.
SumSales.
SumSales.
Statements
Statements
Statements
Statements
IF
IF ErrorFound
ErrorFound GO
GO TO
TO SumSalesExit
SumSalesExit
END-IF
END-IF
Statements
Statements
Statements
Statements
Statements
Statements
IF
IF ErrorFound
ErrorFound GO
GO TO
TO SumSalesExit
SumSalesExit
END-IF
END-IF
Statements
Statements

SumSalesExit.
SumSalesExit.
EXIT.
EXIT.
Format 2 - Syntax
   THRU  
PERFORM  1stProc    EndProc  
  THROUGH  
RepeatCount TIMES
[ StatementBlock END - PERFORM]

PROCEDURE
PROCEDUREDIVISION.
DIVISION.
Begin.
Begin.
Statements
PERFORM DisplayName 4 TIMES
Statements
STOP RUN.

DisplayName.
DisplayName.
DISPLAY “Tom Ryan”.
Example
Run of PerformExample2
$$ SET
SET SOURCEFORMAT"FREE"
SOURCEFORMAT"FREE" Starting to run program
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION. Starting to run program
>>>>This is an in line Perform
PROGRAM-ID. PerformExample2. >>>>This is an in line Perform
PROGRAM-ID. PerformExample2. >>>>This is an in line Perform
>>>>Thisis
isan
anin
inline
linePerform
Perform
AUTHOR.
AUTHOR. Michael
Michael Coughlan.
Coughlan.
>>>>This
>>>>This is an in line Perform
Finished in line Perform
Finished in line Perform
>>>> This is an out of line Perform
DATA
DATA DIVISION.
DIVISION.
>>>> This is an out of line Perform
>>>> This is an out of line Perform
WORKING-STORAGE >>>> This is an out of line Perform
WORKING-STORAGE SECTION.
SECTION. >>>> This is an out of line Perform
>>>> This is an out of line Perform
>>>> This is an out of line Perform
01 NumofTimes
01 NumofTimes PIC
PIC 99 VALUE
VALUE 5.
5. >>>> This is an out of line Perform
>>>> This is an out of line Perform
>>>> This is an out of line Perform
Back in Begin. About to Stop
PROCEDURE Back in Begin. About to Stop
PROCEDURE DIVISION.
DIVISION.
Begin.
Begin.
DISPLAY
DISPLAY "Starting
"Starting to
to run
run program"
program"
PERFORM 3 TIMES
PERFORM 3 TIMES
DISPLAY
DISPLAY ">>>>This
">>>>This is
is an
an in
in line
line Perform"
Perform"
END-PERFORM
END-PERFORM
DISPLAY
DISPLAY "Finished
"Finished in
in line
line Perform"
Perform"
PERFORM
PERFORM OutOfLineEG NumOfTimes TIMES
OutOfLineEG NumOfTimes TIMES
DISPLAY
DISPLAY "Back in Begin. About to Stop".
"Back in Begin. About to Stop".
STOP RUN.
STOP RUN.
OutOfLineEG.
OutOfLineEG.
DISPLAY
DISPLAY ">>>>
">>>> This
This is
is an
an out
out of
of line
line Perform".
Perform".
Format 3 Syntax
   THRU     BEFORE  
PERFORM  1stProc    EndProc    WITH TEST  
  THROUGH     AFTER 
UNTIL Condition
[ StatementBlock END - PERFORM]

 This format is used where the WHILE or REPEAT constructs


are used in other languages.
 If the WITH TEST BEFORE phrase is used the PERFORM
behaves like a WHILE loop and the condition is tested before
the loop body is entered.
 If the WITH TEST AFTER phrase is used the PERFORM
behaves like a REPEAT loop and the condition is tested after
the loop body is entered.
 The WITH TEST BEFORE phrase is the default and so is
rarely explicitly stated.
312
PERFORM
PERFORMWITH
WITH PERFORM
PERFORMWITH
WITH
TEST
TESTBEFORE
BEFORE== TEST
TESTAFTER
AFTER==
WHILE
WHILE...
...DO
DO REPEAT
REPEAT...
...UNTIL
UNTIL

Loop Body Loop Body

t t
e False e False
s s
t t
True True

Next Statement Next Statement

313
Sequential File
Processing

 In general terms, the WHILE loop is an ideal construct for


processing sequences of data items whose length is not predefined.
 Such sequences of values are often called “streams”.
 Because the ‘length’ of the stream is unknown we have to be
careful how we manage the detection of the end of the stream.
 A useful way for solving this problem uses a strategy known as
“read ahead”.

314
Ahead
 With the “read ahead” strategy we always try to stay one data item
ahead of the processing.
 The general format of the “read ahead” algorithm is as follows;
Attempt to READ first data item
WHILE NOT EndOfStream
Process data item
Attempt to READ next data item
ENDWHILE
 Use this to process any stream of data.

315
File
 Algorithm Template
READ StudentRecords
AT END MOVE HIGH-VALUES TO StudentRecord
END-READ
PERFORM UNTIL StudentRecord = HIGH-VALUES
DISPLAY StudentRecord
READ StudentRecords
AT END MOVE HIGH-VALUES TO StudentRecord END-
READ
END-PERFORM

 This is an example of an algorithm which is capable of processing


any sequential file; ordered or unordered!

316
RUN OF SeqRead
9456789
9456789 COUGHLANMS
COUGHLANMS LM51
LM51
9367892
9367892 RYAN TG
RYAN TG LM60
LM60
9368934
9368934 WILSON
WILSON HR
HR LM61
LM61

PROCEDURE
PROCEDURE DIVISION.
DIVISION.
Begin.
Begin.
OPEN
OPEN INPUT
INPUT StudentFile
StudentFile
READ
READ StudentFile
StudentFile
AT
AT END
END MOVE
MOVE HIGH-VALUES
HIGH-VALUES TO
TO StudentDetails
StudentDetails
END-READ
END-READ
PERFORM
PERFORM UNTIL
UNTIL StudentDetails
StudentDetails == HIGH-VALUES
HIGH-VALUES
DISPLAY
DISPLAY StudentId SPACE StudentName SPACE
StudentId SPACE StudentName SPACE CourseCode
CourseCode
READ StudentFile
READ StudentFile
AT
AT END
END MOVE
MOVE HIGH-VALUES
HIGH-VALUES TO
TO StudentDetails
StudentDetails
END-READ
END-READ
END-PERFORM
END-PERFORM
CLOSE
CLOSE StudentFile
StudentFile
STOP RUN.
STOP RUN.
Searching Tables.
Creating Pre-filled
Tables

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

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
Creating Pre-filled
Tables

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

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.
Searching a
Table

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

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 "NOPQRSTUVWXYZ".
VALUE "NOPQRSTUVWXYZ".
02
02 FILLER REDEFINES
FILLER REDEFINES TableValues.
TableValues.
03
03 Letter PIC X OCCURS 26
Letter PIC X OCCURS 26 TIMES.
TIMES.

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.
Search
Syntax

322
SET
Syntax

323
Searching a
Table

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

01
01 LetterTable.
LetterTable.
02
02 TableValues.
TableValues.
03
03 FILLER
FILLER PIC
PIC X(13)
X(13)
VALUE "ABCDEFGHIJKLM".
VALUE "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
INDEXED
INDEXED BY
BY LetterIdx.
LetterIdx.
SET
SET LetterIdx
LetterIdx TOTO 1.
1.
SEARCH Letter
SEARCH Letter
AT
AT END
END DISPLAY
DISPLAY "Letter
"Letter not
not found!"
found!"
WHEN
WHEN Letter(LetterIdx)
Letter(LetterIdx) == LetterIn
LetterIn
DISPLAY
DISPLAY LetterIn,
LetterIn, "is
"is in
in position
position ",
", Idx
Idx
END-SEARCH.
END-SEARCH.
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.
Search All
Syntax.
Using the Search
All

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

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 "NOPQRSTUVWXYZ".
VALUE "NOPQRSTUVWXYZ".
02
02 FILLER REDEFINES
FILLER REDEFINES TableValues.
TableValues.
03
03 Letter PIC X OCCURS 26
Letter PIC X OCCURS 26 TIMES
TIMES
ASCENDING
ASCENDING KEY IS
KEY IS Letter
Letter
INDEXED
INDEXED BY
BY LetterIdx.
LetterIdx.

SEARCH
SEARCH ALL
ALL Letter
Letter
WHEN
WHEN Letter(LetterIdx) == LetterIn
Letter(LetterIdx) LetterIn
DISPLAY
DISPLAY LetterIn, "is in
LetterIn, "is in position
position ",
", Idx
Idx
END-SEARCH.
END-SEARCH.
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.
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 ItemNotInTable TO TRUE
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)

14 26 13 = M

ALGORITHM.
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 ItemNotInTable TO TRUE
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)

14 26 20 = T

ALGORITHM.
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 ItemNotInTable TO TRUE
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)

14 19 20 = T

ALGORITHM.
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 ItemNotInTable TO TRUE
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)

14 19 16 = P

ALGORITHM.
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 ItemNotInTable TO TRUE
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)

17 19 16 = P

ALGORITHM.
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 ItemNotInTable TO TRUE
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)

17 19 18 = R

ALGORITHM.
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 ItemNotInTable TO TRUE
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)

17 17 18 = R

ALGORITHM.
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 ItemNotInTable TO TRUE
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)

17 17 18 = Q

ALGORITHM.
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 ItemNotInTable TO TRUE
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)

17 17 18 = Q

ALGORITHM.
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 ItemNotInTable TO TRUE
Search All
Example.
01
01 StateTable.
StateTable.
02
02 StateValues.
StateValues.
03
03 FILLER
FILLER PIC
PIC X(20)
X(20) VALUE
VALUE ??????????????
??????????????
Post
Post 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 5050 TIMES
TIMES
ASCENDING
ASCENDING KEY
KEY ISIS StateName
StateName
INDEXED
INDEXED BY
BY StateIdx.
StateIdx.
04 PostCode
04 PostCode PIC
PIC X(6).
X(6).
04 StateName
04 StateName PIC X(14).
PIC 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 PostCode(StateIdx)
PostCode(StateIdx) TOTO PrintPostCode
PrintPostCode
END-SEARCH.
END-SEARCH.
INSPE
CT
INSPECT Syntax - Format
1

INSPECT FullName TALLYING UnstrPtr


FOR LEADING SPACES.

INSPECT SourceLine TALLYING ECount


FOR ALL "e" AFTER INITIAL
"start"
BEFORE INITIAL 340
INSPECT Example 1

READ TextFile
AT END SET EndOfFile TO TRUE
END-READ
PERFORM UNTIL EndOfFile
PERFORM VARYING idx FROM 1 BY 1 UNTIL idx > 26
INSPECT TextLine TALLYING LetterCount(idx)
FOR ALL Letter(idx)
END-PERFORM
READ TextFile
AT END SET EndOfFile TO TRUE
END-READ
END-PERFORM
PERFORM VARYING idx FROM 1 BY 1 UNTIL idx > 26
DISPLAY "Letter " Letter(idx)
" occurs " LetterCount(idx) " times"
END-PERFORM
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 behaviour of the INSPECT is modified by using the LEADING, FIRST, BEFORE and
AFTER phrases.

An ALL, LEADING, CHARACTERS, FIRST or CONVERTING phrase may only be followed


by one BEFORE and one AFTER phrase.

342
Modifying
Phrases
LEADING
The LEADING phrase causes counting/replacement of all
Compare$il characters from the first valid one encountered to the
first invalid one.

FIRST
The FIRST phrase causes only the first valid character to be
replaced.

BEFORE
The BEFORE phrase designates as valid those characters to the left
of the delimiter associated with it.

AFTER
The AFTER phrase designates as valid those characters to the right
of the delimiter associated with it. 343
INSPECT Syntax - Format
2

PERFORM VARYING idx FROM 1 BY 1 UNTIL idx > 10


INSPECT TextLine
REPLACING SwearWord(idx) BY "*#@!"
END-PERFORM

344
INSPECT Example 2

INSPECT StringData REPLACING ALL "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
INSPECT Example
2

INSPECT StringData REPLACING ALL "F" BY "G"


AFTER INITIAL "A" BEFORE INITIAL "Q".

StringData

F F F F A G G G G G Q F F F Z
INSPECT Example 3

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
INSPECT Example 3

INSPECT StringData REPLACING LEADING "F" BY "G"


AFTER INITIAL "A" BEFORE INITIAL "Z".

StringData

F F F F A G G G G G Q F F F Z
INSPECT Example 4

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
INSPECT Example
4

INSPECT StringData REPLACING ALL "F" BY "G"


AFTER INITIAL "A" BEFORE INITIAL "Z".

StringData

F F F F A G G G G G Q G G G Z
INSPECT Example 5

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
INSPECT Example
5

INSPECT StringData REPLACING FIRST "F" BY "G"


AFTER INITIAL "A" BEFORE INITIAL "Q".

StringData

F F F F A G F F F F Q F F F Z
INSPECT Example
6

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
INSPECT Example
6

INSPECT StringData REPLACING


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

StringData

F F F F A F R O G F Q F F F Z
INSPECT Syntax - Format 3

355
INSPECT Syntax - Format 4

INSPECT TextLine CONVERTING


"0123456789" TO "5298317046"
AFTER INITIAL "codeon"
BEFORE INITIAL "codeoff".

356
INSPECT Example 7

INSPECT StringData CONVERTING "FXTD"


FXTD TO "zyab".
zyab

StringData

P X P F P D P T P P F X T D P
INSPECT Example 7

INSPECT StringData CONVERTING "FXTD"


FXTD TO "zyab".
zyab

StringData

P y P z P b P a P P z y a b P
INSPECT Example 7

INSPECT StringData REPLACING "FXTD"


FXTD BY "zyab".
zyab

StringData

P X P F P D P T P P F X T D P
INSPECT Example 7

INSPECT StringData REPLACING "FXTD"


FXTD BY "zyab".
zyab

StringData

P X P F P D P T P P z y a b P
INSPECT Example 8

INSPECT StringData REPLACING ALL "x" BY "y"


"d" BY "z"
"f" BY "s".

StringData

P x P f P d P T P P f x T d P
INSPECT Example 8

INSPECT StringData REPLACING ALL "X" BY "y"


"D" BY "z"
"F" BY "s".

StringData

P y P s P z P T P P s y T z P
INSPECT Example
9

INSPECT CustAddress
CONVERTING "abcdefghijklmnopqrstuvwxyz"
abcdefghijklmnopqrstuvwxyz
TO "ABCDEFGHIJKLMNOPQRSTUVWXYZ".
ABCDEFGHIJKLMNOPQRSTUVWXYZ

01 AlphaChars.
02 AlphaLower PIC X(26) VALUE
"abcdefghijklmnopqrstuvwxyz".
02 AlphaUpper PIC X(26) VALUE
"ABCDEFGHIJKLMNOPQRSTUVWXYZ".

INSPECT CustAddress
CONVERTING AlphaLower TO AlphaUpper.
AlphaUpper
INSPECT CustAddress
CONVERTING AlphaUpper TO AlphaLower.
AlphaLower
INSPECT Example
10

01 RussianPay PIC $$$,$$$,$$9.99.

MOVE 12345.67 TO RussianPay.


INSPECT RussianPay REPLACING ALL "$" BY "R".
DISPLAY RussianPay " roubles".

RussianPay
INSPECT Example 10

01 RussianPay PIC $$$,$$$,$$9.99.

MOVE 12345.67 TO RussianPay.


INSPECT RussianPay REPLACING ALL "$" BY "R".
DISPLAY RussianPay " roubles".

RussianPay
$12,345.67
INSPECT Example 10

01 RussianPay PIC $$$,$$$,$$9.99.

MOVE 12345.67 TO RussianPay.


INSPECT RussianPay REPLACING ALL "$" BY "R".
DISPLAY RussianPay " roubles".

RussianPay
R12,345.67
INSPECT Example 10

01 RussianPay PIC $$$,$$$,$$9.99.

MOVE 12345.67 TO RussianPay.


INSPECT RussianPay REPLACING ALL "$" BY "R".
DISPLAY RussianPay " roubles".

RussianPay
R12,345.67 R12,345.67 roubles
STRI
NG
STRING Syntax.

STRING Ident1, Ident2, "10" DELIMITED BY SIZE


INTO DestString
END-STRING.
STRING Ident1 DELIMITED BY SIZE
Ident2 DELIMITED BY SPACES
Ident3 DELIMITED BY "Frogs"
INTO Ident4 WITH POINTER StrPtr
END-STRING.
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.
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.
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.
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.
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.
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.
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.
2
01 StrPtr PIC 99.
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 "-".
- - - - - - - - - - - - - - -

MOVE 1 TO StrPtr
STRING DayStr DELIMITED BY SPACES
"," DELIMITED BY SIZE
INTO DateStr WITH POINTER StrPtr
END-STRING.
STRING MonthStr DELIMITED BY SPACES
"," DELIMITED BY SIZE
INTO DateStr WITH POINTER StrPtr
END-STRING.
STRING YearStr DELIMITED BY SIZE
INTO DateStr WITH POINTER StrPtr
END-STRING.
STRING Example 2
01 StrPtr PIC 99.
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 , - - - - - - - - - - - - -

MOVE 1 TO StrPtr
STRING DayStr DELIMITED BY SPACES
"," DELIMITED BY SIZE
INTO DateStr WITH POINTER StrPtr
END-STRING.
STRING MonthStr DELIMITED BY SPACES
"," DELIMITED BY SIZE
INTO DateStr WITH POINTER StrPtr
END-STRING.
STRING YearStr DELIMITED BY SIZE
INTO DateStr WITH POINTER StrPtr
END-STRING.
STRING Example 2
01 StrPtr PIC 99.
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 , - - - - - - - -

MOVE 1 TO StrPtr
STRING DayStr DELIMITED BY SPACES
"," DELIMITED BY SIZE
INTO DateStr WITH POINTER StrPtr
END-STRING.
STRING MonthStr DELIMITED BY SPACES
"," DELIMITED BY SIZE
INTO DateStr WITH POINTER StrPtr
END-STRING.
STRING YearStr DELIMITED BY SIZE
INTO DateStr WITH POINTER StrPtr
END-STRING.
STRING Example 2
01 StrPtr PIC 99.
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 - - - -

MOVE 1 TO StrPtr
STRING DayStr DELIMITED BY SPACES
"," DELIMITED BY SIZE
INTO DateStr WITH POINTER StrPtr
END-STRING.
STRING MonthStr DELIMITED BY SPACES
"," DELIMITED BY SIZE
INTO DateStr WITH POINTER StrPtr
END-STRING.
STRING YearStr DELIMITED BY SIZE
INTO DateStr WITH POINTER StrPtr
END-STRING.
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.

This is the destination string

STRING Field1 DELIMITED BY SPACES


INTO Field2
END-STRING.
DISPLAY Field2.
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.

Whereis the destination string

STRING Field1 DELIMITED BY SPACES


INTO Field2
END-STRING.
DISPLAY Field2.
STRING Example 4
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.
STRING Example 4
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.
STRING Example 5
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

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.
STRING Example 5
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 WhereHerestination string

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.
STRING Example 6
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.

STRING Field1, Field2, Field3


DELIMITED BY SPACES
INTO Field4
END-STRING.
DISPLAY Field4
STRING Example 6
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.

WhereThisHere

STRING Field1, Field2, Field3


DELIMITED BY SPACES
INTO Field4
END-STRING.
DISPLAY Field4
STRING Example 7
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

MOVE 4 TO NewPtr.
STRING Field1 DELIMITED BY "this"
Field3 DELIMITED BY SPACE
"END" DELIMITED BY SIZE
INTO Field2
END-STRING.
STRING Example 7
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 HereENDation string

MOVE 4 TO NewPtr.
STRING Field1 DELIMITED BY "this"
Field3 DELIMITED BY SPACE
"END" DELIMITED BY SIZE
INTO Field2
END-STRING.
STRING Example 8
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


MOVE 4 TO NewPtr.
STRING Field1 DELIMITED BY "this"
Field3 DELIMITED BY SPACE
"Tom" DELIMITED BY SIZE
INTO Field2 WITH POINTER NewPtr
ON OVERFLOW DISPLAY "String Error"
NOT ON OVERFLOW DISPLAY Field2
END-STRING.
STRING Example 8
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.

ThiWhere he destination string


MOVE 4 TO NewPtr.
STRING Field1 DELIMITED BY "this"
Field3 DELIMITED BY SPACE
"Tom" DELIMITED BY SIZE
INTO Field2 WITH POINTER NewPtr
ON OVERFLOW DISPLAY "String Error"
NOT ON OVERFLOW DISPLAY Field2
END-STRING.
UNSTR
ING
UNSTRING Syntax.

UNSTRING FullName DELIMITED BY ALL SPACES


INTO FirstName, SecondName, Surname
END-UNSTRING
UNSTRING CustAddress DELIMITED BY ","
INTO AdrLine(1), AdrLine(2), AdrLine(3),
AdrLine(4), AdrLine(5), AdrLine(6)
TALLYING IN AdrLinesUsed
END-UNSTRING.
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 moves. There is space filling. 395
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.

396
UNSTRING
clauses.
 ON OVERFLOW.
The ON OVERFLOW is activated if :-
– The Unstring pointer (Pointer#i) is not pointing to a character
position within the SourceString 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.
397
The UNSTRING clauses 2.

 WITH POINTER
The Pointer#i holds the position of the next non-delimiter
character to be examined in the Source String.
Pointer#i must be large enough to hold a value one greater than
the size of the Source String.
 DELIMITER IN
A DELIMITER IN clause is associated with a particular Destination
String. HoldDelim$i holds the Delimiter that was encountered in
the Source String.
 ALL
When the ALL phrase is used, contiguous delimiters are treated as
if only one delimiter had been encountered.

398
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.
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.
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.
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.
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
UNSTRING Example 2

01 DayStr PIC XX.

01 MonthStr PIC XX.

01 YearStr PIC XX.


01 DateStr PIC X(8).

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

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

01 DayStr PIC XX. 1 9


01 MonthStr PIC XX.

01 YearStr PIC XX.


01 DateStr PIC X(8).

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

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

01 DayStr PIC XX. 1 9


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

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

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

01 DayStr PIC XX. 1 9


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

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

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

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
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
UNSTRING Example 3

01 DayStr PIC XX. 1 9


01 MonthStr PIC XX. 0 5
01 YearStr PIC XX.

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

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
UNSTRING Example 3

01 DayStr PIC XX. 1 9


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

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
UNSTRING Example 3

01 DayStr PIC XX. 1 9


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

ACCEPT DateStr.
UNSTRING DateStr
DELIMITED BY "/" OR "-"
INTO DayStr DELIMITER IN Hold1 1919 05
05 80
80
MonthStr DELIMITER IN Hold2
YearStr -- //
END-UNSTRING.
DISPLAY DayStr SPACE MonthStr SPACE YearStr.
DISPLAY Hold1 SPACE Hold2
UNSTRING Example 4

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
DELIMITED BY "/" OR "-"
INTO DayStr DELIMITER IN Hold1
MonthStr DELIMITER IN Hold1
YearStr
END-UNSTRING.
DISPLAY DayStr SPACE MonthStr SPACE YearStr.
DISPLAY Hold1
UNSTRING Example 4

01 DayStr PIC XX. 1 9


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

ACCEPT DateStr.
UNSTRING DateStr
DELIMITED BY "/" OR "-"
INTO DayStr DELIMITER IN Hold1 1919 05
05 80
80
MonthStr DELIMITER IN Hold1
YearStr //
END-UNSTRING.
DISPLAY DayStr SPACE MonthStr SPACE YearStr.
DISPLAY Hold1
UNSTRING Example 5

01 DayStr PIC XX.

01 MonthStr PIC XX.

01 YearStr PIC XX.

01 DateStr PIC X(11). 1 5 - - - 0 7 - - 9 4

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

01 DayStr PIC XX. 1 5


01 MonthStr PIC XX. 0 7
01 YearStr PIC XX. 9 4
01 DateStr PIC X(11). 1 5 - - - 0 7 - - 9 4

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

01 DayStr PIC XX.

01 MonthStr PIC XX.

01 YearStr PIC XX.

01 DateStr PIC X(11). 1 5 - - - 0 7 - - 9 4

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

01 DayStr PIC XX. 1 5


01 MonthStr PIC XX.

01 YearStr PIC XX.

01 DateStr PIC X(11). 1 5 - - - 0 7 - - 9 4

ACCEPT DateStr.
UNSTRING DateStr
DELIMITED BY "-"
INTO DayStr, MonthStr, YearStr
ON OVERFLOW DISPLAY "Chars Left" Chars
Chars Left
Left
END-UNSTRING.
UNSTRING Example 7
01 OldName PIC X(80).
Tim John Roberts
01 TempName.
02 NameInitial PIC X.
02 FILLER PIC X(15).
01 NewName PIC X(30).
01 Pointers.
02 StrPtr PIC 99 VALUE 1.
02 UnstrPtr PIC 99 VALUE 1.
88 NameProcessed VALUE 81.
PROCEDURE DIVISION.
ProcessName.
ACCEPT OldName.
PERFORM UNTIL NameProcessed
UNSTRING OldName DELIMITED BY ALL SPACES
INTO TempName WITH POINTER UnstrPtr
END-UNSTRING
Display TempName
END-PERFORM
STOP RUN.
UNSTRING Example 7
01 OldName PIC X(80).
Tim John Roberts
01 TempName. T im
02 NameInitial PIC X.
02 FILLER PIC X(15).
01 NewName PIC X(30).
01 Pointers.
02 StrPtr PIC 99 VALUE 1.
02 UnstrPtr PIC 99 VALUE 1.
88 NameProcessed VALUE 81. Tim
Tim
PROCEDURE DIVISION.
ProcessName.
ACCEPT OldName.
PERFORM UNTIL NameProcessed
UNSTRING OldName DELIMITED BY ALL SPACES
INTO TempName WITH POINTER UnstrPtr
END-UNSTRING
Display TempName
END-PERFORM
STOP RUN.
UNSTRING Example 7
01 OldName PIC X(80).
Tim John Roberts
01 TempName. J ohn
02 NameInitial PIC X.
02 FILLER PIC X(15).
01 NewName PIC X(30).
01 Pointers.
02 StrPtr PIC 99 VALUE 1.
02 UnstrPtr PIC 99 VALUE 1.
88 NameProcessed VALUE 81. John
John
PROCEDURE DIVISION.
ProcessName.
ACCEPT OldName.
PERFORM UNTIL NameProcessed
UNSTRING OldName DELIMITED BY ALL SPACES
INTO TempName WITH POINTER UnstrPtr
END-UNSTRING
Display TempName
END-PERFORM
STOP RUN.
UNSTRING Example 7
01 OldName PIC X(80).
Tim John Roberts
01 TempName. R oberts
02 NameInitial PIC X.
02 FILLER PIC X(15).
01 NewName PIC X(30).
01 Pointers.
02 StrPtr PIC 99 VALUE 1.
02 UnstrPtr PIC 99 VALUE 1.
88 NameProcessed VALUE 81. Roberts
Roberts
PROCEDURE DIVISION.
ProcessName.
ACCEPT OldName.
PERFORM UNTIL NameProcessed
UNSTRING OldName DELIMITED BY ALL SPACES
INTO TempName WITH POINTER UnstrPtr
END-UNSTRING
Display TempName
END-PERFORM
STOP RUN.
UNSTRING Example 8
OldName Tim John Roberts
TempName
NewName

PROCEDURE DIVISION.
ProcessName.
ACCEPT OldName.
UNSTRING OldName DELIMITED BY ALL SPACES
INTO TempName WITH POINTER UnstrPtr
END-UNSTRING
PERFORM UNTIL NameProcessed
STRING NameInitial "." DELIMITED BY SIZE
INTO NewName WITH POINTER StrPtr
END-STRING
UNSTRING OldName DELIMITED BY ALL SPACES
INTO TempName WITH POINTER UnstrPtr
END-UNSTRING
END-PERFORM
STRING SPACE TempName DELIMITED BY SIZE
INTO NewName WITH POINTER StrPtr
END-STRING
STOP RUN.
UNSTRING Example 8
OldName Tim John Roberts
TempName T im
NewName

PROCEDURE DIVISION.
ProcessName.
ACCEPT OldName.
UNSTRING OldName DELIMITED BY ALL SPACES
INTO TempName WITH POINTER UnstrPtr
END-UNSTRING
PERFORM UNTIL NameProcessed
STRING NameInitial "." DELIMITED BY SIZE
INTO NewName WITH POINTER StrPtr
END-STRING
UNSTRING OldName DELIMITED BY ALL SPACES
INTO TempName WITH POINTER UnstrPtr
END-UNSTRING
END-PERFORM
STRING SPACE TempName DELIMITED BY SIZE
INTO NewName WITH POINTER StrPtr
END-STRING
STOP RUN.
UNSTRING Example 8
OldName Tim John Roberts
TempName T im
NewName T.
PROCEDURE DIVISION.
ProcessName.
ACCEPT OldName.
UNSTRING OldName DELIMITED BY ALL SPACES
INTO TempName WITH POINTER UnstrPtr
END-UNSTRING
PERFORM UNTIL NameProcessed
STRING NameInitial "." DELIMITED BY SIZE
INTO NewName WITH POINTER StrPtr
END-STRING
UNSTRING OldName DELIMITED BY ALL SPACES
INTO TempName WITH POINTER UnstrPtr
END-UNSTRING
END-PERFORM
STRING SPACE TempName DELIMITED BY SIZE
INTO NewName WITH POINTER StrPtr
END-STRING
STOP RUN.
UNSTRING Example 8
OldName Tim John Roberts
TempName J ohn
NewName T.
PROCEDURE DIVISION.
ProcessName.
ACCEPT OldName.
UNSTRING OldName DELIMITED BY ALL SPACES
INTO TempName WITH POINTER UnstrPtr
END-UNSTRING
PERFORM UNTIL NameProcessed
STRING NameInitial "." DELIMITED BY SIZE
INTO NewName WITH POINTER StrPtr
END-STRING
UNSTRING OldName DELIMITED BY ALL SPACES
INTO TempName WITH POINTER UnstrPtr
END-UNSTRING
END-PERFORM
STRING SPACE TempName DELIMITED BY SIZE
INTO NewName WITH POINTER StrPtr
END-STRING
STOP RUN.
UNSTRING Example 8
OldName Tim John Roberts
TempName J ohn
NewName T.J.
PROCEDURE DIVISION.
ProcessName.
ACCEPT OldName.
UNSTRING OldName DELIMITED BY ALL SPACES
INTO TempName WITH POINTER UnstrPtr
END-UNSTRING
PERFORM UNTIL NameProcessed
STRING NameInitial "." DELIMITED BY SIZE
INTO NewName WITH POINTER StrPtr
END-STRING
UNSTRING OldName DELIMITED BY ALL SPACES
INTO TempName WITH POINTER UnstrPtr
END-UNSTRING
END-PERFORM
STRING SPACE TempName DELIMITED BY SIZE
INTO NewName WITH POINTER StrPtr
END-STRING
STOP RUN.
UNSTRING Example 8
OldName Tim John Roberts
TempName R oberts
NewName T.J.
PROCEDURE DIVISION.
ProcessName.
ACCEPT OldName.
UNSTRING OldName DELIMITED BY ALL SPACES
INTO TempName WITH POINTER UnstrPtr
END-UNSTRING
PERFORM UNTIL NameProcessed
STRING NameInitial "." DELIMITED BY SIZE
INTO NewName WITH POINTER StrPtr
END-STRING
UNSTRING OldName DELIMITED BY ALL SPACES
INTO TempName WITH POINTER UnstrPtr
END-UNSTRING
END-PERFORM
STRING SPACE TempName DELIMITED BY SIZE
INTO NewName WITH POINTER StrPtr
END-STRING
STOP RUN.
8
OldName Tim John Roberts
TempName R oberts
NewName T . J . Roberts
PROCEDURE DIVISION.
ProcessName.
ACCEPT OldName.
UNSTRING OldName DELIMITED BY ALL SPACES
INTO TempName WITH POINTER UnstrPtr
END-UNSTRING
PERFORM UNTIL NameProcessed
STRING NameInitial "." DELIMITED BY SIZE
INTO NewName WITH POINTER StrPtr
END-STRING
UNSTRING OldName DELIMITED BY ALL SPACES
INTO TempName WITH POINTER UnstrPtr
END-UNSTRING
END-PERFORM
STRING SPACE TempName DELIMITED BY SIZE
INTO NewName WITH POINTER StrPtr
END-STRING
STOP RUN.
Introductio
n
to
Sequential
Files
COBOL's
forte

 COBOL is generally used in situations where


the volume of data to be processed is large.

 These systems are sometimes referred to as


“data intensive” systems.

 Generally, large volumes of data arise not


because the data is inherently voluminous but
because the same items of information have
been recorded about a great many instances of
the same object.

430
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. 431
Files, Records,
Fields.

STUDENTS.DAT
StudId
StudId StudName
StudName DateOfBirth
DateOfBirth
9723456
9723456 COUGHLAN
COUGHLAN 10091961
10091961
9724567 RYAN
9724567 RYAN 31121976
31121976
9534118
9534118 COFFEY
COFFEY 23061964
23061964 occurrences
9423458 O'BRIEN
9423458 O'BRIEN 03111979
03111979
9312876
9312876 SMITH
SMITH 12121976
12121976

DATA
DATA DIVISION.
DIVISION.
Record Type
FILE SECTION.
FILE SECTION. (Template)
FD
FD StudentFile.
StudentFile. (Structure)
01 StudentDetails.
01 StudentDetails.
02
02 StudId
StudId PIC
PIC 9(7).
9(7).
02 StudName
02 StudName PIC X(8).
PIC X(8).
02
02 DateOfBirth PIC X(8).
DateOfBirth PIC X(8).

432
How files are
processed.
 Files are repositories of data that reside on backing storage
(hard disk or magnetic tape).
 A file may consist of hundreds of thousands or even millions of
records.
 Suppose we want to keep information about all the TV license
holders in the country. Suppose each record is about 150
characters/bytes long. If we estimate the number of licenses at
1 million this gives us a size for the file of 150 X 1,000,000 =
150 megabytes.
 If we want to process a file of this size we cannot do it by
loading the whole file into the computer’s memory at once.
 Files are processed by reading them into the computer’s
memory one record at a time.

433
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.
434
Record
Buffers

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

STUDENTS.DAT RecordBuffer
Declaration

435
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
436
Creating a Student
Record
Student Details.
01
01 StudentDetails.
StudentDetails.
Student

StudentId.
Id. 02
02 StudentId
StudentId PIC
PIC 9(7).
9(7).
Student Name.

Student Name. 02
02 StudentName.
StudentName.
Surname
Surname 03
03 Surname
Surname PIC
PIC X(8).
X(8).
Initials
Initials 03
03 Initials
Initials PIC
PIC XX.
XX.
Date

DateofofBirth
Birth 02
02 DaateOfBirth.
DaateOfBirth.
Year
YearofofBirth
Birth 03
03 YOBirth
YOBirth PIC
PIC 99.
99.
Month
MonthofofBirth
Birth 03
03 MOBirth
MOBirth PIC
PIC 99.
99.
Day
DayofofBirth
Birth 03
03 DOBirth
DOBirth PIC
PIC 99.
99.
Course

CourseCode
Code 02
02 CourseCode
CourseCode PIC
PIC X(4).
X(4).
Value of grant

Value of grant 02
02 Grant
Grant PIC
PIC 9(4).
9(4).
Gender

Gender 02
02 Gender
Gender PIC
PIC X.
X.
Describing the record buffer in COBOL
DATA
DATA DIVISION.
DIVISION.
FILE
FILE SECTION.
SECTION.
FD StudentFile.
FD StudentDetails.
StudentFile.
01
01 02
StudentDetails.
02 StudentId
StudentId PIC
PIC 9(7).
9(7).
02 StudentName.
02 03StudentName.
03 Surname
Surname PIC
PIC X(8).
X(8).
03 Initials
03 Initials PIC XX.
PIC XX.
02 DateOfBirth.
02 03DateOfBirth.
03 YOBirth
YOBirth PIC
PIC 9(2).
9(2).
03 MOBirth
03 DOBirth
MOBirth PIC 9(2).
PIC 9(2).
9(2).
03
03 DOBirth PIC
PIC X(4).
9(2).
02 CourseCode
02 Grant
CourseCode PIC
PIC 9(4).
X(4).
02
02 Gender
Grant PIC
PIC X.
9(4).
02
02 Gender PIC
PIC X.

 The record type/template/buffer of every file used in a program must be described in the
FILE SECTION by means of an FD (file description) entry.
 The FD entry consists of the letters FD and an internal file name.

438
The Select and Assign
Clause.
ENVIRONMENT
ENVIRONMENT DIVISION.
DIVISION.
INPUT-OUTPUT
INPUT-OUTPUT SECTION.
SECTION.
FILE-CONTROL.
FILE-CONTROL.
SELECT
SELECT StudentFile
StudentFile
ASSIGN
ASSIGN TO
TO “STUDENTS.DAT”.
“STUDENTS.DAT”.
DATA
DATA DIVISION.
DIVISION.
FILE
FILE SECTION.
SECTION.
FD StudentFile.
FD StudentDetails.
StudentFile.
DISK 01
01 02
StudentDetails.
02 StudentId
StudentId PIC
PIC 9(7).
9(7).
02 StudentName.
02 03StudentName.
03 Surname
Surname PIC
PIC X(8).
X(8).
STUDENTS.DAT 03 Initials PIC XX.
02 03 Initials
DateOfBirth. PIC XX.
02 03DateOfBirth.
YOBirth PIC 9(2).
03
03 YOBirth
MOBirth PIC
PIC 9(2).
9(2).
03 DOBirth
03 MOBirth PIC 9(2).
PIC 9(2).
02 03 DOBirth
CourseCode PIC X(4).
PIC 9(2).
02 Grant
02 CourseCode PIC 9(4).
PIC X(4).
02 Gender
02 Grant PIC X.
PIC 9(4).
02 Gender PIC X.

 The internal file name used in the FD entry is connected to an external file (on
disk or tape) by means of the Select and Assign clause.

439
Select and Assign
Syntax.

SELECT FileName ASSIGN TO ExternalFileReference


 LINE 
[ORGANIZATION IS   SEQUENTIAL ].
 RECORD 

 LINE SEQUENTIAL means each record is followed by the carriage


return and line feed characters.

 RECORD SEQUENTIAL means that the file consists of a stream of


bytes. Only the fact that we know the size of each record allows us to
retrieve them.

440
COBOL file handling
Verbs
 OPEN
Before your program can access the data in an input file or place data in an
output file you must make the file available to the program by OPENing it.

 READ
The READ copies a record occurrence/instance from the file and places it
in the record buffer.

 WRITE
The WRITE copies the record it finds in the record buffer to the file.

 CLOSE
You must ensure that (before terminating) your program closes all the files
it has opened. Failure to do so may result in data not being written to the
file or users being prevented from accessing the file.

441
OPEN and CLOSE verb
syntax

  INPUT  
  
OPEN   OUTPUT  InternalFileName ...
  EXTEND  
  

 When you open a file you have to indicate to the system what
how you want to use it (e.g. INPUT, OUTPUT, EXTEND) so
that the system can manage the file correctly.

 Opening a file does not transfer any data to the record buffer, it
simply provides access.

442
The READ verb
 Once the system has opened a file and made it
available to the program it is the programmers
responsibility to process it correctly.
 Remember, the file record buffer is our only
connection with the file and it is only able to store a
single record at a time.
 To process all the records in the file we have to
transfer them, one record at a time, from the file to the
buffer.
 COBOL provides the READ verb for this purpose.
443
READ verb
syntax
READ InternalFilename [ NEXT] RECORD
[ INTO Identifier]
AT END StatementBlock
END - READ

 The InternalFilename specified must be a file that has


been OPENed for INPUT.
 The NEXT RECORD clause is optional and generally not
used.
 Using INTO Identifier clause causes the data to be read
into the record buffer and then copied from there to the
specified Identifier in one operation.
– When this option is used there will be two copies of the data. It
is the equivalent of a READ followed by a MOVE. 444
How the READ
works
StudentRecord
StudentID StudentName Course.
9 3 3 4 5 6 7 F r a n k C u r t a i n L M 0 5 1

9 3 3 4 5 6 7 F r a n k C u r t a i n L M 0 5 1
9 3 8 3 7 1 5 T h o ma s H e a l y L M 0 6 8
9 3 4 7 2 9 2 T o n y O ‘ B r i a n L M 0 5 1
9 3 7 8 8 1 1 B i l l y D o w n e s L M 0 2 1
EOF

PERFORM UNTIL StudentRecord = HIGH-VALUES


READ StudentRecords
AT END MOVE HIGH-VALUES TO StudentRecord
END-READ
END-PERFORM.
445
How the READ
works
StudentRecord
StudentID StudentName Course.
9 3 8 3 7 1 5 T h o ma s H e a l y L M 0 6 8

9 3 3 4 5 6 7 F r a n k C u r t a i n L M 0 5 1
9 3 8 3 7 1 5 T h o ma s H e a l y L M 0 6 8
9 3 4 7 2 9 2 T o n y O ‘ B r i a n L M 0 5 1
9 3 7 8 8 1 1 B i l l y D o w n e s L M 0 2 1
EOF

PERFORM UNTIL StudentRecord = HIGH-VALUES


READ StudentRecords
AT END MOVE HIGH-VALUES TO StudentRecord
END-READ
END-PERFORM.
446
How the READ
works
StudentRecord
StudentID StudentName Course.
9 3 4 7 2 9 2 T o n y O ‘ B r i a n L M 0 5 1

9 3 3 4 5 6 7 F r a n k C u r t a i n L M 0 5 1
9 3 8 3 7 1 5 T h o ma s H e a l y L M 0 6 8
9 3 4 7 2 9 2 T o n y O ‘ B r i a n L M 0 5 1
9 3 7 8 8 1 1 B i l l y D o w n e s L M 0 2 1
EOF

PERFORM UNTIL StudentRecord = HIGH-VALUES


READ StudentRecords
AT END MOVE HIGH-VALUES TO StudentRecord
END-READ
END-PERFORM.
447
How the READ
works
StudentRecord
StudentID StudentName Course.
9 3 7 8 8 1 1 B i l l y D o w n e s L M 0 2 1

9 3 3 4 5 6 7 F r a n k C u r t a i n L M 0 5 1
9 3 8 3 7 1 5 T h o m a s H e a l y L M 0 6 8
9 3 4 7 2 9 2 T o n y O ‘ B r i a n L M 0 5 1
9 3 7 8 8 1 1 B i l l y D o w n e s L M 0 2 1
EOF

PERFORM UNTIL StudentRecord = HIGH-VALUES


READ StudentRecords
AT END MOVE HIGH-VALUES TO StudentRecord
END-READ
END-PERFORM.
448
How the READ
works
StudentRecord
StudentID StudentName Course.
                          

HIGH-VALUES
9 3 3 4 5 6 7 F r a n k C u r t a i n L M 0 5 1
9 3 8 3 7 1 5 T h o ma s H e a l y L M 0 6 8
9 3 4 7 2 9 2 T o n y O ‘ B r i a n L M 0 5 1
9 3 7 8 8 1 1 B i l l y D o w n e s L M 0 2 1
EOF

PERFORM UNTIL StudentRecord = HIGH-VALUES


READ StudentRecords
AT END MOVE HIGH-VALUES TO StudentRecord
END-READ
END-PERFORM.
449
WRITE
Syntax.
WRITE RecordName [ FROM Identifier]
   LINE   
  AdvanceNum   
  BEFORE    LINES  
 ADVANCING  MnemonicName 
 AFTER   PAGE 
  
   

 To WRITE data to a file move the data to the


record buffer (declared in the FD entry) and
then WRITE the contents of record buffer to
the file.
450
How the WRITE
works
OPEN
OPEN OUTPUT
OUTPUT StudentFile.
StudentFile.
MOVE
MOVE "9334567Frank Curtain
"9334567Frank Curtain LM051"
LM051" TO
TO StudentDetails.
StudentDetails.
WRITE StudentDetails.
WRITE StudentDetails.
MOVE
MOVE "9383715Thomas
"9383715Thomas Healy
Healy LM068"
LM068" TO
TO StudentDetails.
StudentDetails.
WRITE StudentDetails.
WRITE StudentDetails.
CLOSE
CLOSE StudentFile.
StudentFile.
STOP
STOP RUN.
RUN.

StudentRecord
StudentID StudentName Course.
9 3 3 4 5 6 7 F r a n k C u r t a i n L M 0 5 1

Students.Dat
9 3 3 4 5 6 7 F r a n k C u r t a i n L M 0 5 1
EO
F
How the WRITE
works
OPEN
OPEN OUTPUT
OUTPUT StudentFile.
StudentFile.
MOVE
MOVE "9334567Frank Curtain
"9334567Frank Curtain LM051"
LM051" TO
TO StudentDetails.
StudentDetails.
WRITE StudentDetails.
WRITE StudentDetails.
MOVE
MOVE "9383715Thomas
"9383715Thomas Healy
Healy LM068"
LM068" TO
TO StudentDetails.
StudentDetails.
WRITE StudentDetails.
WRITE StudentDetails.
CLOSE
CLOSE StudentFile.
StudentFile.
STOP
STOP RUN.
RUN.

StudentRecord
StudentID StudentName Course.
9 3 8 3 7 1 5 T h o ma s H e a l y L M 0 6 8

Students.Dat
9 3 3 4 5 6 7 F r a n k C u r t a i n L M 0 5 1
9 3 8 3 7 1 5 T h o ma s H e a l y L M 0 6 8
EO
F
$ SET SOURCEFORMAT"FREE"
$ SET SOURCEFORMAT"FREE"
IDENTIFICATION DIVISION.
IDENTIFICATION DIVISION.
PROGRAM-ID. SeqWrite.
PROGRAM-ID. SeqWrite.
AUTHOR. Michael Coughlan.
AUTHOR. Michael Coughlan.
ENVIRONMENT DIVISION.
ENVIRONMENT SECTION.
INPUT-OUTPUT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
FILE-CONTROL.
SELECT StudentFile ASSIGN TO "STUDENTS.DAT"
SELECT StudentFile
ORGANIZATION IS ASSIGN TO "STUDENTS.DAT"
LINE SEQUENTIAL.
ORGANIZATION IS LINE SEQUENTIAL.
DATA DIVISION.
DATASECTION.
FILE DIVISION.
FILE SECTION.
FD StudentFile.
FDStudentDetails.
01 StudentFile.
0102StudentDetails.
StudentId PIC 9(7).
02 StudentId
02 StudentName. PIC 9(7).
02 03StudentName.
Surname PIC X(8).
03Initials
03 Surname PICXX.
PIC X(8).
03 Initials
02 DateOfBirth. PIC XX.
02 03DateOfBirth.
YOBirth PIC 9(2).
03MOBirth
03 YOBirth PIC9(2).
PIC 9(2).
03DOBirth
03 MOBirth PIC9(2).
PIC 9(2).
03 DOBirth
02 CourseCode PICX(4).
PIC 9(2).
02 CourseCode
02 Grant PIC X(4).
PIC 9(4).
02 Grant
02 Gender PIC 9(4).
PIC X.
02 Gender PIC X.
PROCEDURE DIVISION.
PROCEDURE DIVISION.
Begin.
Begin.
OPEN OUTPUT StudentFile.
OPEN OUTPUT
DISPLAY StudentFile.
"Enter student details using template below. Enter no data to end.".
DISPLAY "Enter student details using template below. Enter no data to end.".
PERFORM GetStudentDetails.
PERFORM GetStudentDetails.
PERFORM UNTIL StudentDetails = SPACES
PERFORM UNTIL StudentDetails = SPACES
WRITE StudentDetails
PERFORM StudentDetails
WRITE GetStudentDetails
PERFORM GetStudentDetails
END-PERFORM.
END-PERFORM.
CLOSE StudentFile.
CLOSE
STOP StudentFile.
RUN.
STOP RUN.
GetStudentDetails.
GetStudentDetails.
DISPLAY "NNNNNNNSSSSSSSSIIYYMMDDCCCCGGGGS".
DISPLAYStudentDetails.
ACCEPT "NNNNNNNSSSSSSSSIIYYMMDDCCCCGGGGS".
ACCEPT StudentDetails.
$ SET SOURCEFORMAT"FREE"
$ SET SOURCEFORMAT"FREE"
IDENTIFICATION DIVISION.
IDENTIFICATION
PROGRAM-ID. SeqRead.DIVISION.
PROGRAM-ID.
AUTHOR. SeqRead.
Michael Coughlan.
AUTHOR. Michael Coughlan.
ENVIRONMENT DIVISION.
ENVIRONMENT SECTION.
INPUT-OUTPUT DIVISION.
FILE-CONTROL. SECTION.
INPUT-OUTPUT
FILE-CONTROL.
SELECT StudentFile ASSIGN TO “STUDENTS.DAT”
SELECT StudentFile
ORGANIZATION IS ASSIGN TO “STUDENTS.DAT”
LINE SEQUENTIAL.
ORGANIZATION IS LINE SEQUENTIAL.
DATA DIVISION.
DATASECTION.
FILE DIVISION.
FILE SECTION.
FD StudentFile.
FD StudentFile.
01 StudentDetails.
0102StudentDetails.
StudentId PIC 9(7).
0202 StudentName.
StudentId PIC 9(7).
02 03StudentName.
Surname PIC X(8).
03Initials
03 Surname PICXX.
PIC X(8).
03 Initials
02 DateOfBirth. PIC XX.
02 03DateOfBirth.
YOBirth PIC 9(2).
03 YOBirth
03 MOBirth PIC9(2).
PIC 9(2).
03 MOBirth
03 DOBirth PIC 9(2).
PIC 9(2).
03 DOBirth
02 CourseCode PIC 9(2).
PIC X(4).
02 CourseCode
02 Grant PIC X(4).
PIC 9(4).
02 Grant
02 Gender PIC 9(4).
PIC X.
02 Gender PIC X.
PROCEDURE DIVISION.
PROCEDURE DIVISION.
Begin.
Begin.
OPEN INPUT StudentFile
OPENStudentFile
READ INPUT StudentFile
READ StudentFile
AT END MOVE HIGH-VALUES TO StudentDetails
AT
END-READ END MOVE HIGH-VALUES TO StudentDetails
END-READ
PERFORM UNTIL StudentDetails = HIGH-VALUES
PERFORMStudentId
DISPLAY UNTIL StudentDetails = HIGH-VALUES
SPACE StudentName SPACE CourseCode
DISPLAY StudentId
READ StudentFile SPACE StudentName SPACE CourseCode
READ StudentFile
AT END MOVE HIGH-VALUES TO StudentDetails
AT END MOVE HIGH-VALUES TO StudentDetails
END-READ
END-READ
END-PERFORM
END-PERFORM
CLOSE StudentFile
CLOSE
STOP StudentFile
RUN.
STOP RUN.
Proces
sing
Sequen
tial
Files
$ SET SOURCEFORMAT"FREE"
Run of SeqWrite $ SET SOURCEFORMAT"FREE"
IDENTIFICATION DIVISION.
IDENTIFICATION DIVISION.
PROGRAM-ID. SeqWrite.
PROGRAM-ID. SeqWrite.
Enter student details using template below. Press CR to end. Coughlan.
AUTHOR. Michael
AUTHOR.
Enter student details using template below. Press Michael
CR to end. Coughlan.
NNNNNNNSSSSSSSSIIYYMMDDCCCCGGGGS
NNNNNNNSSSSSSSSIIYYMMDDCCCCGGGGS ENVIRONMENT DIVISION.
9456789COUGHLANMS580812LM510598M ENVIRONMENT SECTION.
INPUT-OUTPUT DIVISION.
9456789COUGHLANMS580812LM510598M
NNNNNNNSSSSSSSSIIYYMMDDCCCCGGGGS INPUT-OUTPUT SECTION.
NNNNNNNSSSSSSSSIIYYMMDDCCCCGGGGS FILE-CONTROL.
9367892RYAN TG521210LM601222F FILE-CONTROL.
SELECT StudentFile ASSIGN TO "STUDENTS.DAT"
9367892RYAN TG521210LM601222F
NNNNNNNSSSSSSSSIIYYMMDDCCCCGGGGS SELECT StudentFile
ORGANIZATION IS ASSIGN TO "STUDENTS.DAT"
LINE SEQUENTIAL.
NNNNNNNSSSSSSSSIIYYMMDDCCCCGGGGS ORGANIZATION IS LINE SEQUENTIAL.
9368934WILSON HR520323LM610786M
9368934WILSON HR520323LM610786M DATA DIVISION.
NNNNNNNSSSSSSSSIIYYMMDDCCCCGGGGS DATASECTION.
FILE DIVISION.
NNNNNNNSSSSSSSSIIYYMMDDCCCCGGGGS
CarriageReturn FILE SECTION.
CarriageReturn FD StudentFile.
FDStudentDetails.
01 StudentFile.
0102StudentDetails.
StudentId PIC 9(7).
0202 StudentName.
StudentId PIC 9(7).
02 03
StudentName.
Surname PIC X(8).
03Initials
03 Surname PICXX.
PIC X(8).
03 Initials
02 DateOfBirth. PIC XX.
02 03
DateOfBirth.
YOBirth PIC 9(2).
03MOBirth
03 YOBirth PIC9(2).
PIC 9(2).
03 MOBirth
03 DOBirth PIC 9(2).
PIC 9(2).
03 DOBirth
02 CourseCode PICX(4).
PIC 9(2).
0202 Grant
CourseCode PIC9(4).
PIC X(4).
02 Grant
02 Gender PIC
PIC X.9(4).
PROCEDURE DIVISION. 02 Gender PIC X.
PROCEDURE DIVISION.
Begin.
Begin.
OPEN OUTPUT StudentFile
OPEN OUTPUT
DISPLAY StudentFile
"Enter student details using template below. Press CR to end.".
DISPLAY "Enter student details using template below. Press CR to end.".
PERFORM GetStudentDetails
PERFORMUNTIL
PERFORM GetStudentDetails
StudentDetails = SPACES
PERFORM UNTIL StudentDetails = SPACES
WRITE StudentDetails
WRITE StudentDetails
PERFORM GetStudentDetails
PERFORM GetStudentDetails
END-PERFORM
END-PERFORM
CLOSE StudentFile
CLOSE
STOP StudentFile
RUN.
STOP RUN.
GetStudentDetails.
GetStudentDetails.
DISPLAY "NNNNNNNSSSSSSSSIIYYMMDDCCCCGGGGS".
DISPLAYStudentDetails.
ACCEPT "NNNNNNNSSSSSSSSIIYYMMDDCCCCGGGGS".
ACCEPT StudentDetails.
$ SET SOURCEFORMAT"FREE"
$ SET SOURCEFORMAT"FREE"
IDENTIFICATION DIVISION.
IDENTIFICATION
PROGRAM-ID. DIVISION.
SeqRead.
RUN OF SeqRead PROGRAM-ID. SeqRead.
AUTHOR. Michael Coughlan.
AUTHOR. Michael Coughlan.
9456789 COUGHLANMS LM51 ENVIRONMENT DIVISION.
9456789 COUGHLANMS LM51 ENVIRONMENT SECTION.
INPUT-OUTPUT DIVISION.
FILE-CONTROL. SECTION.
INPUT-OUTPUT
9367892 RYAN TG LM60 FILE-CONTROL.
SELECT StudentFile ASSIGN TO "STUDENTS.DAT"
9367892 RYAN TG LM60 SELECT StudentFile
ORGANIZATION IS ASSIGN TO "STUDENTS.DAT"
LINE SEQUENTIAL.
ORGANIZATION IS LINE SEQUENTIAL.
9368934 WILSON HR LM61
9368934 WILSON HR LM61 DATA DIVISION.
DATASECTION.
FILE DIVISION.
FILE SECTION.
FD StudentFile.
FDStudentDetails.
01 StudentFile.
0102StudentDetails.
StudentId PIC 9(7).
0202 StudentName.
StudentId PIC 9(7).
02 03
StudentName.
Surname PIC X(8).
03Initials
03 Surname PICXX.
PIC X(8).
03 Initials
02 DateOfBirth. PIC XX.
02 03
DateOfBirth.
YOBirth PIC 9(2).
03MOBirth
03 YOBirth PIC9(2).
PIC 9(2).
03DOBirth
03 MOBirth PIC9(2).
PIC 9(2).
03 DOBirth
02 CourseCode PIC 9(2).
PIC X(4).
0202 Grant
CourseCode PIC9(4).
PIC X(4).
PROCEDURE DIVISION. 0202 Gender
Grant PICX.
PIC 9(4).
PROCEDURE DIVISION.
Begin. 02 Gender PIC X.
Begin.
OPEN INPUT StudentFile
OPENStudentFile
READ INPUT StudentFile
READ
AT StudentFile
END MOVE HIGH-VALUES TO StudentDetails
AT
END-READEND MOVE HIGH-VALUES TO StudentDetails
END-READ
PERFORM UNTIL StudentDetails = HIGH-VALUES
PERFORM
DISPLAYUNTIL StudentDetails
StudentId = HIGH-VALUES
SPACE StudentName SPACE CourseCode
DISPLAY StudentId
READ StudentFile SPACE StudentName SPACE CourseCode
READ
AT StudentFile
END MOVE HIGH-VALUES TO StudentDetails
AT END MOVE HIGH-VALUES TO StudentDetails
END-READ
END-READ
END-PERFORM
END-PERFORM
CLOSE StudentFile
CLOSE
STOP StudentFile
RUN.
STOP RUN.
Organization and
Access
 Two important characteristics of files are
– DATA ORGANIZATION
– METHOD OF ACCESS

 Data organization refers to the way the records of the file are organized on the
backing storage device.
COBOL recognizes three main file organizations;
– Sequential - Records organized serially.
– Relative - Relative record number based organization.
– Indexed - Index based organization.

 The method of access refers to the way in which records are accessed.
– A file with an organization of Indexed or Relative may
still have its records accessed sequentially.
– But records in a file with an organization of Sequential can not be accessed
directly.

458
Sequential
Organization
 The simplest COBOL file organization is Sequential.
 In a Sequential file the records are arranged serially, one after another,
like cards in a dealing shoe.
 In a Sequential file the only way to access any particular record is to;
Start at the first record and read all the succeeding records until you find the
one you want or reach the end of the file.

 Sequential files may be


Ordered
or
Unordered (these should be called Serial files)

 The ordering of the records in a file has a significant impact on the


way in which it is processed and the processing that can be done on it.

459
Ordered and Unordered
Files

Ordered File Unordered File

RecordA
RecordA RecordM
RecordM
RecordB
RecordB RecordH
RecordH
RecordG
RecordG RecordB
RecordB
RecordH
RecordH RecordN
RecordN
RecordK
RecordK RecordA
RecordA
RecordM
RecordM RecordK
RecordK
RecordN
RecordN RecordG
RecordG

In an ordered file the records are sequenced on some


field in the record.
460
Adding records to unordered
files
Transaction Unordered
File PROGRAM File
FILE
FILE SECTION.
RecordF
RecordF SECTION.
PROGRAM RecordM
RecordM
TFRec
RecordP
RecordP RecordH
RecordH
UFRec
RecordW
RecordW RecordB
RecordB
PROCEDURE
PROCEDURE DIVISION.
DIVISION. RecordN
OPEN
RecordN
OPEN EXTEND
EXTEND UF.
UF.
OPEN
OPEN INPUT
INPUT TF.
TF.
RecordA
RecordA
READ
READ TF.
TF. RecordK
RecordK
MOVE
MOVE TFRec
TFRec TO
TO UFRec.
UFRec.
WRITE
WRITE UFRec.
UFRec. RecordG
RecordG
Adding records to unordered
files
Transaction Unordered
File PROGRAM File
FILE
FILE SECTION.
RecordF
RecordF SECTION.
PROGRAM RecordM
RecordM
RecordF
RecordP
RecordP RecordH
RecordH
RecordF
RecordW
RecordW RecordB
RecordB
PROCEDURE
PROCEDURE DIVISION.
DIVISION. RecordN
OPEN
RecordN
OPEN EXTEND
EXTEND UF.
UF.
OPEN
OPEN INPUT
INPUT TF.
TF.
RecordA
RecordA
READ
READ TF.
TF. RecordK
RecordK
MOVE
MOVE TFRec
TFRec TO
TO UFRec.
UFRec.
WRITE
WRITE UFRec.
UFRec. RecordG
RecordG
RecordF
RecordF
Adding records to unordered
files
Transaction Unordered
File File
RecordF
RecordF RecordM
RecordM
RecordP
RecordP RecordH
RecordH
RecordW
RecordW RecordB
RecordB
RecordN
RecordN
RecordA
RecordA
RESULT RecordK
RecordK
RecordG
RecordG
RecordF
RecordF
RecordP
RecordP
RecordW
RecordW
Problems with Unordered Sequential
Files

 It is easy to add records to an unordered Sequential file.


 But it is not really possible to delete records from an
unordered Sequential file.
 And it is not feasible to update records in an unordered
Sequential file

464
Problems with Unordered Sequential Files

 Records in a Sequential file can not be deleted or


updated “in situ”.
 The only way to delete Sequential file records is to
create a new file which does not contain them.
 The only way to update records in a Sequential File
is to create a new file which contains the updated
records.
 Because both these operations rely on record
matching they do not work for unordered Sequential
files.
 Why?
465
files?
Transaction File
RecordB
RecordB
RecordM
RecordM
RecordK
RecordK New File
RecordM
RecordM
Delete UF
Record? NO

Unordered File
RecordM
RecordM
RecordH
RecordH
RecordB
RecordB
RecordN
RecordN
RecordA
RecordA
RecordK
RecordK
files?
Transaction File
RecordB
RecordB
RecordM
RecordM
RecordK
RecordK New File
RecordM
RecordM
Delete UF
NO RecordH
RecordH
Record?

Unordered File
RecordM
RecordM
RecordH
RecordH
RecordB
RecordB
RecordN
RecordN
RecordA
RecordA
RecordK
RecordK
files?
Transaction File
RecordB
RecordB
RecordM
RecordM
RecordK
RecordK New File
RecordM
RecordM
Delete UF
YES RecordH
RecordH
Record?

Unordered File
RecordM
RecordM
RecordH
RecordH
RecordB
RecordB
RecordN
RecordN
RecordA
RecordA
RecordK
RecordK
files?
Transaction File
RecordB
RecordB
RecordM
RecordM
RecordK
RecordK New File
RecordM
RecordM
Delete UF
NO RecordH
RecordH
Record?
RecordN
RecordN
Unordered File
RecordM
RecordM
But wait...
RecordH
RecordH
We should have deleted
RecordB
RecordB RecordM. Too late. It’s
RecordN
RecordN already been written to the new
RecordA file.
RecordA
RecordK
RecordK
Deleting records from an ordered
file
Transaction File PROGRAM New File
FILE
FILE SECTION.
SECTION.
RecordB
RecordB
TFRec
RecordK
RecordK
OFRec
RecordM
RecordM
NFRec
PROCEDURE
PROCEDURE DIVISION.
DIVISION.
Ordered File OPEN
OPEN INPUT TF.
INPUT TF.
OPEN INPUT OF
OPEN INPUT OF
RecordA
RecordA OPEN
OPEN OUTPUT
OUTPUT NF.
NF.
READ TF.
READ TF.
RecordB
RecordB READ
READ OF.
OF.
IF
IF TFKey NOT
TFKey NOT == OFKey
OFKey
RecordG
RecordG MOVE
MOVE OFRec TO NFRec
OFRec TO NFRec
WRITE NFRec
WRITE NFRec
RecordH
RecordH READ
READ OF
OF
ELSE
ELSE
RecordK
RecordK READ
READ TF
TF
READ OF
READ OF
RecordM
RecordM END-IF.
END-IF.
RecordN
RecordN
Deleting records from an ordered
file
Transaction File PROGRAM New File
FILE
FILE SECTION.
SECTION.
RecordB
RecordB RecordA
RecordA
RecordB
RecordK
RecordK
RecordA
RecordM
RecordM
RecordA
PROCEDURE
PROCEDURE DIVISION.
DIVISION.
Ordered File OPEN
OPEN INPUT TF.
INPUT TF.
OPEN INPUT OF
OPEN INPUT OF Problem !!
RecordA
RecordA OPEN
OPEN OUTPUT
OUTPUT NF.
READ TF.
NF. How can we recognize
READ TF.
RecordB
RecordB READ which record we want to
READ OF.
OF.
IF
IF TFRec NOT
TFRec NOT == OFRec
OFRec delete?
RecordG
RecordG MOVE
MOVE OFRec TO NFRec
OFRec TO NFRec By its Key Field
WRITE NFRec
WRITE NFRec
RecordH
RecordH READ
READ OF
OF
ELSE
ELSE
RecordK
RecordK READ
READ TF
TF
READ OF
READ OF
RecordM
RecordM END-IF.
END-IF.
RecordN
RecordN
Deleting records from an ordered
file
Transaction File PROGRAM New File
FILE
FILE SECTION.
SECTION.
RecordB
RecordB RecordA
RecordA
RecordB
RecordK
RecordK
RecordB
RecordM
RecordM
RecordA
PROCEDURE
PROCEDURE DIVISION.
DIVISION.
Ordered File OPEN
OPEN INPUT TF.
INPUT TF.
OPEN INPUT OF
OPEN INPUT OF
RecordA
RecordA OPEN
OPEN OUTPUT
OUTPUT NF.
NF.
READ TF.
READ TF.
RecordB
RecordB READ
READ OF.
OF.
IF
IF TFKey NOT
TFKey NOT == OFKey
OFKey
RecordG
RecordG MOVE
MOVE OFRec TO NFRec
OFRec TO NFRec
WRITE NFRec
WRITE NFRec
RecordH
RecordH READ
READ OF
OF
ELSE
ELSE
RecordK
RecordK READ
READ TF
TF
READ OF
READ OF
RecordM
RecordM END-IF.
END-IF.
RecordN
RecordN
Deleting records from an ordered
file
Transaction File PROGRAM New File
FILE
FILE SECTION.
SECTION.
RecordB
RecordB RecordA
RecordA
RecordK
RecordK
RecordK RecordG
RecordG RecordG
RecordM
RecordM
RecordG
PROCEDURE
PROCEDURE DIVISION.
DIVISION.
Ordered File OPEN
OPEN INPUT TF.
INPUT TF.
OPEN INPUT OF
OPEN INPUT OF
RecordA
RecordA OPEN
OPEN OUTPUT
OUTPUT NF.
NF.
READ TF.
READ TF.
RecordB
RecordB READ
READ OF.
OF.
IF
IF TFKey NOT
TFKey NOT == OFKey
OFKey
RecordG
RecordG MOVE
MOVE OFRec TO NFRec
OFRec TO NFRec
WRITE NFRec
WRITE NFRec
RecordH
RecordH READ
READ OF
OF
ELSE
ELSE
RecordK
RecordK READ
READ TF
TF
READ OF
READ OF
RecordM
RecordM END-IF.
END-IF.
RecordN
RecordN
Deleting records from an ordered
file
Transaction File New File
RecordB
RecordB RecordA
RecordA
RecordK
RecordK RecordG
RecordG
RecordM
RecordM RecordH
RecordH
Ordered File RecordN
RecordN
RESULT
RecordA
RecordA
RecordB
RecordB
RecordG
RecordG
RecordH
RecordH
RecordK
RecordK
RecordM
RecordM
RecordN
RecordN
Updating records in an ordered
file
Transaction File PROGRAM New File
FILE
FILE SECTION.
SECTION.
RecordB
RecordB
TFRec
RecordH
RecordH
OFRec
RecordK
RecordK
NFRec
PROCEDURE
PROCEDURE DIVISION.
DIVISION.
Ordered File OPEN
OPEN INPUT TF.
INPUT TF.
OPEN INPUT
OPEN INPUT OFOF
RecordA
RecordA OPEN
OPEN OUTPUT
OUTPUT NF.
NF.
READ TF.
READ TF.
RecordB
RecordB READ
READ OF.
OF.
IF
IF TFKey == OFKey
TFKey OFKey
RecordG
RecordG Update
Update OFRec with
OFRec with TFRec
TFRec
MOVE OFRec+ TO NFRec
MOVE OFRec+ TO NFRec
RecordH
RecordH WRITE
WRITE NFRec
NFRec
READ TF
READ TF
RecordK
RecordK READ
READ OF
OF
ELSE
ELSE
RecordM
RecordM MOVE
MOVE OFRec
OFRec TO
TO NFRec
NFRec
WRITE NFRec
WRITE NFRec
RecordN
RecordN READ
READ OF
OF
END-IF.
END-IF.
Updating records in an ordered
file
Transaction File PROGRAM New File
FILE
FILE SECTION.
SECTION.
RecordB
RecordB RecordA
RecordA
RecordB
RecordH
RecordH
RecordA
RecordK
RecordK
RecordA
PROCEDURE
PROCEDURE DIVISION.
DIVISION.
Ordered File OPEN
OPEN INPUT TF.
INPUT TF.
OPEN INPUT
OPEN INPUT OFOF
RecordA
RecordA OPEN
OPEN OUTPUT
OUTPUT NF.
NF.
READ TF.
READ TF.
RecordB
RecordB READ
READ OF.
OF.
IF
IF TFKey == OFKey
TFKey OFKey
RecordG
RecordG Update
Update OFRec with
OFRec with TFRec
TFRec
MOVE OFRec+ TO NFRec
MOVE OFRec+ TO NFRec
RecordH
RecordH WRITE
WRITE NFRec
NFRec
READ TF
READ TF
RecordK
RecordK READ
READ OF
OF
ELSE
ELSE
RecordM
RecordM MOVE
MOVE OFRec
OFRec TO
TO NFRec
NFRec
WRITE NFRec
WRITE NFRec
RecordN
RecordN READ
READ OF
OF
END-IF.
END-IF.
Updating records in an ordered
file
Transaction File PROGRAM New File
FILE
FILE SECTION.
SECTION.
RecordB
RecordB RecordA
RecordA
RecordB
RecordH
RecordH RecordB+
RecordB+
RecordB
RecordK
RecordK
RecordB+
PROCEDURE
PROCEDURE DIVISION.
DIVISION.
Ordered File OPEN
OPEN INPUT TF.
INPUT TF.
OPEN INPUT
OPEN INPUT OFOF
RecordA
RecordA OPEN
OPEN OUTPUT
OUTPUT NF.
NF.
READ TF.
READ TF.
RecordB
RecordB READ
READ OF.
OF.
IF
IF TFKey == OFKey
TFKey OFKey
RecordG
RecordG Update
Update OFRec with
OFRec with TFRec
TFRec
MOVE OFRec+ TO NFRec
MOVE OFRec+ TO NFRec
RecordH
RecordH WRITE
WRITE NFRec
NFRec
READ TF
READ TF
RecordK
RecordK READ
READ OF
OF
ELSE
ELSE
RecordM
RecordM MOVE
MOVE OFRec
OFRec TO
TO NFRec
NFRec
WRITE NFRec
WRITE NFRec
RecordN
RecordN READ
READ OF
OF
END-IF.
END-IF.
Updating records in an ordered
file
Transaction File PROGRAM New File
FILE
FILE SECTION.
SECTION.
RecordB
RecordB RecordA
RecordA
RecordH
RecordH
RecordH RecordB+
RecordB+
RecordG
RecordK
RecordK RecordG
RecordG
RecordG
PROCEDURE
PROCEDURE DIVISION.
DIVISION.
Ordered File OPEN
OPEN INPUT TF.
INPUT TF.
OPEN INPUT
OPEN INPUT OFOF
RecordA
RecordA OPEN
OPEN OUTPUT
OUTPUT NF.
NF.
READ TF.
READ TF.
RecordB
RecordB READ
READ OF.
OF.
IF
IF TFKey == OFKey
TFKey OFKey
RecordG
RecordG Update
Update OFRec with
OFRec with TFRec
TFRec
MOVE OFRec+ TO NFRec
MOVE OFRec+ TO NFRec
RecordH
RecordH WRITE
WRITE NFRec
NFRec
READ TF
READ TF
RecordK
RecordK READ
READ OF
OF
ELSE
ELSE
RecordM
RecordM MOVE
MOVE OFRec
OFRec TO
TO NFRec
NFRec
WRITE NFRec
WRITE NFRec
RecordN
RecordN READ
READ OF
OF
END-IF.
END-IF.
Inserting records into an ordered
file
Transaction File PROGRAM New File
FILE
FILE SECTION.
SECTION.
RecordC
RecordC
TFRec
RecordF
RecordF
OFRec
RecordP
RecordP
NFRec
PROCEDURE
PROCEDURE DIVISION.
DIVISION.
Ordered File OPEN
OPEN INPUT TF.
INPUT TF.
OPEN INPUT OF
OPEN INPUT OF
RecordA
RecordA OPEN
OPEN OUTPUT
OUTPUT NF.
NF.
READ TF.
READ TF.
RecordB
RecordB READ
READ OF.
OF.
IF
IF TFKey << OFKey
TFKey OFKey
RecordG
RecordG MOVE
MOVE TFRec TO
TFRec TO NFRec
NFRec
WRITE NFRec
WRITE NFRec
RecordH
RecordH READ
READ TF
TF
ELSE
ELSE
RecordK
RecordK MOVE
MOVE OFRec
OFRec TO
TO NFRec
NFRec
WRITE NFRec
WRITE NFRec
RecordM
RecordM READ
READ OF
OF
END-IF.
END-IF.
RecordN
RecordN
Inserting records into an ordered
file
Transaction File PROGRAM New File
FILE
FILE SECTION.
SECTION.
RecordC
RecordC RecordA
RecordA
RecordC
RecordF
RecordF
RecordA
RecordP
RecordP
RecordA
PROCEDURE
PROCEDURE DIVISION.
DIVISION.
Ordered File OPEN
OPEN INPUT TF.
INPUT TF.
OPEN INPUT OF
OPEN INPUT OF
RecordA
RecordA OPEN
OPEN OUTPUT
OUTPUT NF.
NF.
READ TF.
READ TF.
RecordB
RecordB READ
READ OF.
OF.
IF
IF TFKey << OFKey
TFKey OFKey
RecordG
RecordG MOVE
MOVE TFRec TO
TFRec TO NFRec
NFRec
WRITE NFRec
WRITE NFRec
RecordH
RecordH READ
READ TF
TF
ELSE
ELSE
RecordK
RecordK MOVE
MOVE OFRec
OFRec TO
TO NFRec
NFRec
WRITE NFRec
WRITE NFRec
RecordM
RecordM READ
READ OF
OF
END-IF.
END-IF.
RecordN
RecordN
Inserting records into an ordered
file
Transaction File PROGRAM New File
FILE
FILE SECTION.
SECTION.
RecordC
RecordC RecordA
RecordA
RecordC
RecordF
RecordF RecordB
RecordB
RecordB
RecordP
RecordP
RecordB
PROCEDURE
PROCEDURE DIVISION.
DIVISION.
Ordered File OPEN
OPEN INPUT TF.
INPUT TF.
OPEN INPUT OF
OPEN INPUT OF
RecordA
RecordA OPEN
OPEN OUTPUT
OUTPUT NF.
NF.
READ TF.
READ TF.
RecordB
RecordB READ
READ OF.
OF.
IF
IF TFKey << OFKey
TFKey OFKey
RecordG
RecordG MOVE
MOVE TFRec TO
TFRec TO NFRec
NFRec
WRITE NFRec
WRITE NFRec
RecordH
RecordH READ
READ TF
TF
ELSE
ELSE
RecordK
RecordK MOVE
MOVE OFRec
OFRec TO
TO NFRec
NFRec
WRITE NFRec
WRITE NFRec
RecordM
RecordM READ
READ OF
OF
END-IF.
END-IF.
RecordN
RecordN
Inserting records into an ordered
file
Transaction File PROGRAM New File
FILE
FILE SECTION.
SECTION.
RecordC
RecordC RecordA
RecordA
RecordC
RecordF
RecordF RecordB
RecordB
RecordG
RecordP
RecordP RecordC
RecordC
RecordC
PROCEDURE
PROCEDURE DIVISION.
DIVISION.
Ordered File OPEN
OPEN INPUT TF.
INPUT TF.
OPEN INPUT OF
OPEN INPUT OF
RecordA
RecordA OPEN
OPEN OUTPUT
OUTPUT NF.
NF.
READ TF.
READ TF.
RecordB
RecordB READ
READ OF.
OF.
IF
IF TFKey << OFKey
TFKey OFKey
RecordG
RecordG MOVE
MOVE TFRec TO
TFRec TO NFRec
NFRec
WRITE NFRec
WRITE NFRec
RecordH
RecordH READ
READ TF
TF
ELSE
ELSE
RecordK
RecordK MOVE
MOVE OFRec
OFRec TO
TO NFRec
NFRec
WRITE NFRec
WRITE NFRec
RecordM
RecordM READ
READ OF
OF
END-IF.
END-IF.
RecordN
RecordN
Inserting records into an ordered
file
Transaction File PROGRAM New File
FILE
FILE SECTION.
SECTION.
RecordC
RecordC RecordA
RecordA
RecordF
RecordF
RecordF RecordB
RecordB
RecordG
RecordP
RecordP RecordC
RecordC
RecordF
RecordF
RecordF
PROCEDURE
PROCEDURE DIVISION.
DIVISION.
Ordered File OPEN
OPEN INPUT TF.
INPUT TF.
OPEN INPUT OF
OPEN INPUT OF
RecordA
RecordA OPEN
OPEN OUTPUT
OUTPUT NF.
NF.
READ TF.
READ TF.
RecordB
RecordB READ
READ OF.
OF.
IF
IF TFKey << OFKey
TFKey OFKey
RecordG
RecordG MOVE
MOVE TFRec TO
TFRec TO NFRec
NFRec
WRITE NFRec
WRITE NFRec
RecordH
RecordH READ
READ TF
TF
ELSE
ELSE
RecordK
RecordK MOVE
MOVE OFRec
OFRec TO
TO NFRec
NFRec
WRITE NFRec
WRITE NFRec
RecordM
RecordM READ
READ OF
OF
END-IF.
END-IF.
RecordN
RecordN
Inserting records into an ordered
file
Transaction File PROGRAM New File
FILE
FILE SECTION.
SECTION.
RecordC
RecordC RecordA
RecordA
RecordP
RecordF
RecordF RecordB
RecordB
RecordG
RecordP
RecordP RecordC
RecordC
RecordG
RecordF
RecordF
PROCEDURE
PROCEDURE DIVISION.
DIVISION.
Ordered File OPEN
OPEN INPUT TF.
INPUT TF. RecordG
RecordG
OPEN INPUT OF
OPEN INPUT OF
RecordA
RecordA OPEN
OPEN OUTPUT
OUTPUT NF.
NF.
READ TF.
READ TF.
RecordB
RecordB READ
READ OF.
OF.
IF
IF TFKey << OFKey
TFKey OFKey
RecordG
RecordG MOVE
MOVE TFRec TO
TFRec TO NFRec
NFRec
WRITE NFRec
WRITE NFRec
RecordH
RecordH READ
READ TF
TF
ELSE
ELSE
RecordK
RecordK MOVE
MOVE OFRec
OFRec TO
TO NFRec
NFRec
WRITE NFRec
WRITE NFRec
RecordM
RecordM READ
READ OF
OF
END-IF.
END-IF.
RecordN
RecordN
Advanc
ed
Seque
ntial
Files 1.

485
Single Record Type
Files

 In a file which contains only one record type (the


kind we have examined so far) the record structure is
described as part of the file FD using an 01 level
number.
 The record description creates a ‘buffer’ capable of
storing one record instance at a time.
 Each time a record is read from the file it overwrites
the previous contents of the buffer.
 The record buffer is the only connection between the
file and the program.
486
Files
 Quite often a single file will contain more than one
type of record.
 For instance, some of the terminal exercises required
that your program apply a file of transaction records
to the StudentsFile.
 For simplicity, the Transaction file in these exercises
contained one record type only; either Insertion or
Update or Deletion.
 In a real environment, transactions of this sort would
normally be collected together into one single
transaction file.
487
Implications of a multiple record transaction
file.

 Gathering all the transactions into a single file implies


that the file will contain different record types (i.e.
records with different structures).
 The different record structures may give rise to records
which are also of different lengths.
 For example
● an insertion transaction will contain all the fields that
appear in the StudentFile record (32 characters).
● a deletion transaction will contain only the StudentId (7
characters).
● an update transaction used to record course changes might
contain the StudentId, the OldCourseCode and the
NewCourseCode (15 characters).
488
Describing multiple record
files

 Todescribe these different record types


we have to use more than one record
description in the file's FD.

 Because record descriptions always begin


with level 01 we provide a 01 level for
each record type in the file.

489
Multiple record descriptions - One record
buffer
DATA DIVISION.
FILE SECTION.  What is not obvious
FD TransactionFile.
01 InsertionRec. from this description is
02 StudentId PIC 9(7).
02 StudentName. that COBOL continues
03 Surname PIC X(8). to create just a single
03 Initials PIC XX.
02 DateOfBirth. ‘record buffer’ for the
03 YOBirth PIC 9(2). file!
03 MOBirth PIC 9(2).
03 DOBirth PIC 9(2).  And this ‘record
02 CourseCode PIC X(4).
02 Grant PIC 9(4). buffer’ is only able to
02 Gender PIC X.
store a single record at
01 DeleteRec. a time!
02 StudentId PIC 9(7).
01 UpdateRec.
02 StudentId PIC 9(7).
02 OldCourseCode PIC X(4).
02 NewCourseCode PIC X(4).
 Multiple record descriptions in a file are IMPLICITLY redefinitions of the single record buffer.

TransactionFile Buffer

9230165HENNESSYRM710915LM510550F
 Multiple record descriptions in a file are IMPLICITLY redefinitions of the single record buffer.

TransactionFile Buffer
InsertionRec
StudentId StudentName DateOfBirth CourseCode Grant Gender

9230165HENNESSYRM710915LM510550F
 Multiple record descriptions in a file are IMPLICITLY redefinitions of the single record buffer.

TransactionFile Buffer
InsertionRec
StudentId StudentName DateOfBirth CourseCode Grant Gender

9230165HENNESSYRM710915LM510550F

StudentId
DeletionRec
 Multiple record descriptions in a file are IMPLICITLY redefinitions of the single record buffer.

TransactionFile Buffer
InsertionRec
StudentId StudentName DateOfBirth CourseCode Grant Gender

9230165HENNESSYRM710915LM510550F

StudentId
DeletionRec

StudentId OldCourseCode NewCourseCode


UpdateRec
 All these record descriptions are valid at the same time.
 But only one description makes sense for the values in the buffer.
 How can we tell which description to use?

TransactionFile Buffer
InsertionRec
StudentId StudentName DateOfBirth CourseCode Grant Gender

9230165HENNESSYRM710915LM510550F

StudentId
DeletionRec

StudentId OldCourseCode NewCourseCode


UpdateRec
The Transaction Type
Code
 Generally we cannot reliably establish the type of
record READ into the buffer by examining its
contents.
 To allow us to distinguish between the record types,
a special data item is inserted into each transaction
which identifies the transaction type.
 This data item is usually the first data item in the
transaction record and one character in size, but it
does not have to be.
 Transaction types can be identified using a number,
a letter or other character.
496
The Revised FD.
DATA DIVISION.  TransCode occurs in all the
FILE SECTION. record descriptions.
FD TransactionFile.
01 InsertionRec.  How can we refer to the one
02 TransCode PIC X.
02 StudentId PIC 9(7). in DeleteRec?
02 StudentName.
03 Surname PIC X(8).  MOVE TransCode OF
03 Initials PIC XX. DeleteRec TO TCode.
02 DateOfBirth.
03 YOBirth PIC 9(2).  But TransCode really only
03 MOBirth PIC 9(2).
03 DOBirth PIC 9(2). needs to be defined in one
02 CourseCode PIC X(4). record.
02 Grant PIC 9(4).
02 Gender PIC X.  Since all the records map on
01 DeleteRec. to the same area of storage
02 TransCode PIC X. the TransCode defined for the
02 StudentId PIC 9(7).
InsertionRec can be used no
01 UpdateRec. matter which record type is
02 TransCode PIC X.
02 StudentId PIC 9(7). actually in the buffer .
02 OldCourseCode PIC X(4).
02 NewCourseCode PIC X(4).
FD.
DATA DIVISION.
FILE SECTION.  TransCode and
FD TransactionFile.
01 InsertionRec. StudentId have the
88 EndOfTransFile VALUE HIGH-VALUES. same description
02 TransCode PIC X.
88 Insertion VALUE "I". and are in the same
88 Deletion VALUE "D". location in all three
88 Update VALUE "U". records.
02 StudentId PIC 9(7).
02 StudentName.  So they are defined
03 Surname PIC X(8).
03 Initials PIC XX. only in the
02 DateOfBirth. InsertionRec.
03 YOBirth PIC 9(2).
03 MOBirth PIC 9(2).  In the other records
03 DOBirth PIC 9(2). the area occupied
02 CourseCode PIC X(4).
02 Grant PIC 9(4). by these two items
02 Gender PIC X. is defined using
01 DeleteRec. FILLER.
02 FILLER PIC X(8).
01 UpdateRec.
02 FILLER PIC X(8).
02 OldCourseCode PIC X(4).
02 NewCourseCode PIC X(4).
 What happens when we display the OldCourseCode?
 What happens if we now read an Update record into
the buffer?

TransactionFile Buffer
InsertionRec
TransCode StudentId StudentName DateOfBirth CourseCode Grant Gender

I9230165HENNESSYRM710915LM510550F

FILLER
DeletionRec

FILLER OldCourseCode NewCourseCode


UpdateRec
 When a record smaller than the size of the largest record is read
into the buffer any data that is not explicitly overwritten is left
intact.
 What happens when we display StudentName and
DateOfBirth?
TransactionFile Buffer
InsertionRec
TransCode StudentId StudentName DateOfBirth CourseCode Grant Gender

U9315682LM61LM51RM710915LM510550F

FILLER
DeletionRec

FILLER OldCourseCode NewCourseCode


UpdateRec
Printing a
Report.

 A program is required which will print a report.


 The report, called the Student Details Report, will
be based on the file Students.Dat.
 The report will show the Name, StudentId, Gender
and CourseCode of each student in the file.

 A report is made up of groups of printed lines of


different types.
 What types of line are required for the Student
Details Report?
501
Report Print
Lines.
 Page Heading.
– UL Student Details Report

 Page Footing.
– Page : PageNum

 Column Headings.
– Student Id. Student Name Gender Course

 Student Detail Line.


– StudentId. StudentName Gender CourseCode

 Report Footing.
– *** End of Student Details Report ***
502
Lines.
01 PageHeading.
02 FILLER PIC X(7) VALUE SPACES.
02 FILLER PIC X(25)
VALUE "UL Student Details Report".
01 PageFooting.
02 FILLER PIC X(19) VALUE SPACES.
02 FILLER PIC X(7) VALUE "Page : ".
02 FILLER PIC 99.
01 ColumnHeadings PIC X(36)
VALUE " StudentId StudentName Gender Course".
01 StudentDetailLine.
02 PrnStudId PIC BB9(7).
02 PrnStudName PIC BBX(10).
02 PrnGender PIC BBBBX.
02 PrnCourse PIC BBBBX(4).
01 ReportFooting PIC X(38)
VALUE "*** End of Student Details Report ***".

 The Print Lines are all different record types!


Buffer
 All data coming from, or going to, the peripherals must pass
through a file buffer declared in the File Section.
 The file buffer is associated ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
with the physical device by FILE-CONTROL.
SELECT Printer
means of a Select and ASSIGN TO “LPT1”.
Assign clause.
DATA DIVISION.
 In previous FILE SECTION.
FD Printer.
lectures we saw 01 PrintLine.
that the file buffer ????????????????
is represented by a record description (01 level).
 But the different types of line that must appear on our report
are declared as different record types.
 How can we declare these different record types in the File
Section?

504
No VALUE clause in the FILE
SECTION.
 Defining a file buffer which is used by different record types
is easy (as we have seen).
But !!
 These record types all map on to the same area of storage and
print line records cannot share the same area of storage.
 Why? Because most of the print line record values are
assigned using the VALUE clause and these values are
assigned as soon as the program starts.
 To prevent us trying to use the VALUE clause to assign values
to a File buffer COBOL has a rule which states that;
In the FILE SECTION, the VALUE clause must be used
in condition-name entries only (i.e. it cannot be used
to give an initial value to an item).

505
A
Solution

We get round the problem as follows;

 We define the print records in the WORKING-


STORAGE SECTION.
 We create a file buffer in the FILE SECTION
which is the size of the largest print record.
 We print a line by moving the appropriate print
record to the file buffer and then WRITEing the
contents of the file buffer to the device.

506
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT ReportFile ASSIGN TO “STUDENTS.RPT”.
DATA DIVISION.
FILE SECTION.
FD ReportFile.
01 PrintLine PIC X(38).
WORKING-STORAGE SECTION. DISK
01 PageHeading.
02 FILLER PIC X(7) VALUE SPACES. STUDENTS.RPT
02 FILLER PIC X(25)
VALUE "UL Student Details Report".
01 PageFooting.
02 FILLER PIC X(19) VALUE SPACES.
02 FILLER PIC X(7) VALUE "Page : ".
02 FILLER PIC 99.
01 ColumnHeadings PIC X(36)
VALUE " StudentId StudentName Gender Course".
01 StudentDetailLine.
02 PrnStudId PIC BB9(7).
02 PrnStudName PIC BBX(10).
02 PrnGender PIC BBBBX.
02 PrnCourse PIC BBBBX(4).
01 ReportFooting PIC X(38)
VALUE "*** End of Student Details Report ***".
WRITE Syntax
revisited.
 When we are writing to a printer or a print file we
use a form of the WRITE command different from
that we use when writing to a sequential file.

508
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT ReportFile ASSIGN TO "STUDENTS.RPT"
ORGANIZATION IS LINE SEQUENTIAL.
DATA DIVISION. DISK
FILE SECTION.
FD ReportFile.
01 PrintLine PIC X(40).
STUDENTS.RPT
WORKING-STORAGE SECTION.
01 HeadingLine PIC X(21) VALUE " Record Count Report".
01 StudentTotalLine.
02 FILLER PIC X(17) VALUE "Total Students = ".
02 PrnStudentCount PIC Z,ZZ9.
01 MaleTotalLine.
02 FILLER PIC X(17) VALUE "Total Males = ".
02 PrnMaleCount PIC Z,ZZ9.
01 FemaleTotalLine.
02 FILLER PIC X(17) VALUE "Total Females = ".
02 PrnFemaleCount PIC Z,ZZ9.

MOVE StudentCount TO PrnStudentCount


MOVE MaleCount TO PrnMaleCount
MOVE FemaleCount TO PrnFemaleCount
WRITE PrintLine FROM HeadingLine AFTER ADVANCING PAGE
WRITE PrintLine FROM StudentTotalLine AFTER ADVANCING 2 LINES
WRITE PrintLine FROM MaleTotalLine AFTER ADVANCING 2 LINES
WRITE PrintLine FROM FemaleTotalLine AFTER ADVANCING 2 LINES.
Sort
and
Mer
ge

510
DATA DIVISION.
FILE SECTION.
FD StudentFile.
01 StudentDetails.
02 StudentId PIC 9(7).
02 StudentName.
03 Surname PIC X(8).
03 Initials PIC XX.
02 DateOfBirth.
03 YOBirth PIC 9(2).
03 MOBirth PIC 9(2).
03 DOBirth PIC 9(2).
02 CourseCode PIC X(4).
02 Grant PIC 9(4).
02 Gender PIC X.

 The StudentFile is a sequential file sequenced upon


ascending StudentId.
 Write a program to display the number of students taking
each course. How?
511
Syntax.

 The WorkFileName identifies a temporary work file that the SORT


process uses for the sort. It is defined in the FILE SECTION using
an SD entry.
 Each SortKeyIdentifier identifies a field in the record of the work
file upon which the file will be sequenced.
 When more than one SortKeyIdentifier is specified, the keys
decrease in significance from left to right (leftmost key is most
significant, rightmost is least significant).
 InFileName and OutFileName, are the names of the input and output
files. These files are automatically opened by the SORT. When the
SORT executes they must not be already open.
Example.
FD SalesFile.
01 SalesRec.
02 FILLER PIC X(10).
SD WorkFile.
01 WorkRec.
02 WSalesmanNum PIC 9(5).
02 FILLER PIC X(5).
FD SortedSalesFile.
01 SortedSalesRec.
02 SalesmanNum PIC 9(5).
02 ItemType PIC X.
02 QtySold PIC 9(4).
PROCEDURE DIVISION.
Begin.
SORT WorkFile ON ASCENDING KEY WSalesmanNum
USING SalesFile
GIVING SortedSalesFile.
OPEN INPUT SortedSalesFile.
ENVIRONMENT
ENVIRONMENT DIVISION.
DIVISION.
INPUT-OUTPUT
INPUT-OUTPUT SECTION.
SECTION.
FILE-CONTROL.
FILE-CONTROL.
SELECT
SELECT WorkFile
WorkFile ASSIGN
ASSIGN TO
TO "WORK.TMP".
"WORK.TMP".

SD
SD WorkFile.
WorkFile.
01 WorkRecord.
01 WorkRecord.
02
02 ProvinceCode
ProvinceCode PIC
PIC 9.
9.
02
02 SalesmanCode
SalesmanCode PIC
PIC 9(5).
9(5).
02
02 FILLER
FILLER PIC
PIC X(19).
X(19).

PROCEDURE
PROCEDURE DIVISION.
DIVISION.
Begin.
Begin.
SORT
SORT WorkFile
WorkFile ON
ON ASCENDING
ASCENDING KEY
KEY ProvinceCode
ProvinceCode
DESCENDING
DESCENDING KEY
KEY SalesmanCode
SalesmanCode
USING
USING UnsortedSales
UnsortedSales
GIVING
GIVING SortedSales.
SortedSales.
OPEN
OPEN INPUT
INPUT SortedSales.
SortedSales.
How the SORT works.

SalesFile SortedSalesFile

Unsorted Sorted
Records Records
SORT
Process

WorkFile

SORT WorkFile ON ASCENDING KEY WSalesmanNum


USING SalesFile
GIVING SortedSalesFile.
How the INPUT PROCEDURE
works.

SalesFile SortedSalesFile

Unsorted Sorted
Records Records
Unsorted
Hat SORT
Records
Process

SelectHatSale
s
WorkFile

SORT WorkFile ON ASCENDING KEY WSalesmanNum


INPUT PROCEDURE IS SelectHatSales
GIVING SortedSalesFile.
INPUT PROCEDURE
Template

OPEN
OPEN INPUT
INPUT InFileName
InFileName
READ
READ InFileName
InFileName RECORD
RECORD
PERFORM
PERFORM UNTIL
UNTIL Condition
Condition
RELEASE
RELEASE SDWorkRec
SDWorkRec
READ
READ InFileName
InFileName RECORD
RECORD
END-PERFORM
END-PERFORM
CLOSE
CLOSE InFile
InFile

517
INPUT PROCEDURE - Example

FD
FD SalesFile.
SalesFile.
01
01 SalesRec.
SalesRec.
88
88 EndOfSales
EndOfSales VALUE
VALUE HIGH-VALUES.
HIGH-VALUES.
02 FILLER
02 FILLER PIC 9(5).
PIC 9(5).
02 FILLER
02 FILLER PIC
PIC X.
X.
88 HatRecord
88 HatRecord VALUE
VALUE "H".
"H".
02 FILLER
02 FILLER PIC X(4).
PIC X(4).
SD
SD WorkFile.
WorkFile.
01
01 WorkRec.
WorkRec.
02
02 WSalesmanNum
WSalesmanNum PIC
PIC 9(5).
9(5).
02
02 FILLER
FILLER PIC
PIC X(5).
X(5).
FD
FD SortedSalesFile.
SortedSalesFile.
01 SortedSalesRec.
01 SortedSalesRec.
02
02 SalesmanNum
SalesmanNum PIC
PIC 9(5).
9(5).
02
02 ItemType
ItemType PIC
PIC X.
X.
02
02 QtySold
QtySold PIC
PIC 9(4).
9(4).
PROCEDURE
PROCEDURE DIVISION.
DIVISION.
Begin.
Begin.
SORT
SORT WorkFile
WorkFile ONON ASCENDING
ASCENDING KEYKEY WSalesmanNum
WSalesmanNum
INPUT PROCEDURE IS SelectHatSales
INPUT PROCEDURE IS SelectHatSales
GIVING
GIVING SortedSalesFile.
SortedSalesFile.
New Version
SelectHatSales.
SelectHatSales.
OPEN
OPEN INPUT
INPUT SalesFile
SalesFile
READ
READ SalesFile
SalesFile
AT
AT END
END SET
SET EndOfSales
EndOfSales TO
TO TRUE
TRUE
END-READ
END-READ
PERFORM
PERFORM UNTIL
UNTIL EndOfSales
EndOfSales
IF
IF HatRecord
HatRecord
RELEASE
RELEASE WorkRec
WorkRec FROM
FROM SalesRec
SalesRec
END-IF
END-IF
READ
READ SalesFile
SalesFile
AT
AT END
END SET
SET EndOfSales
EndOfSales TO
TO TRUE
TRUE
END-READ
END-READ
END-PERFORM
END-PERFORM
CLOSE
CLOSE SalesFile.
SalesFile.
Old Version
SelectHatSales
SelectHatSales SECTION.
SECTION.
BeginHatSales.
BeginHatSales.
OPEN
OPEN INPUT
INPUT SalesFile
SalesFile
READ
READ SalesFile
SalesFile
AT
AT END
END SET
SET EndOfSales
EndOfSales TO
TO TRUE
TRUE
END-READ
END-READ
PERFORM
PERFORM GetHatSales
GetHatSales UNTIL
UNTIL EndOfSales
EndOfSales
CLOSE
CLOSE SalesFile
SalesFile
GO
GO TO
TO SelectHatSalesExit.
SelectHatSalesExit.
GetHatSales.
GetHatSales.
IF
IF HatRecord
HatRecord
RELEASE
RELEASE WorkRec
WorkRec FROM
FROM SalesRec
SalesRec
END-IF
END-IF
READ
READ SalesFile
SalesFile
AT
AT END
END SET
SET EndOfSales
EndOfSales TO
TO TRUE
TRUE
END-READ.
END-READ.
SelectHatSalesExit
SelectHatSalesExit
EXIT.
EXIT.
ENVIRONMENT
ENVIRONMENT DIVISION.
DIVISION.
INPUT-OUTPUT
INPUT-OUTPUT SECTION.
SECTION.
FILE-CONTROL.
FILE-CONTROL.
SELECT
SELECT WorkFile
WorkFile ASSIGN
ASSIGN TO
TO "WORK.TMP".
"WORK.TMP".

SD
SD WorkFile.
WorkFile.
01
01 WorkRecord.
WorkRecord.
88
88 EndOfWorkFile
EndOfWorkFile VALUE
VALUE HIGH-VALUES.
HIGH-VALUES.
02
02 ProvinceCode
ProvinceCode PIC
PIC 9.
9.
88
88 ProvinceIsUlster
ProvinceIsUlster VALUE
VALUE 4.4.
02
02 SalesmanCode
SalesmanCode PIC
PIC 9(5).
9(5).
02
02 FILLER
FILLER PIC
PIC X(19).
X(19).
FD
FD UnsortedSales.
UnsortedSales.
01 FILLER
01 FILLER PIC
PIC X(25).
X(25).
FD
FD SortedSales.
SortedSales.
01 SortedRec.
01 SortedRec.
88
88 EndOfSalesFile
EndOfSalesFile VALUE
VALUE HIGH-VALUES.
HIGH-VALUES.
02 ProvinceCode
02 ProvinceCode PIC 9.
PIC 9.
02
02 SalesmanCode
SalesmanCode PIC
PIC 9(5).
9(5).
02
02 ItemCode
ItemCode PIC
PIC 9(7).
9(7).
02
02 ItemCost
ItemCost PIC
PIC 9(3)V99.
9(3)V99.
02
02 QtySold
QtySold PIC
PIC 9(7).
9(7).
PROCEDURE
PROCEDURE DIVISION.
DIVISION.
Begin.
Begin.
SORT
SORT WorkFile
WorkFile
ON
ON ASCENDING
ASCENDING KEY
KEY ProvinceCode
ProvinceCode
SalesmanCode
SalesmanCode
INPUT
INPUT PROCEDURE IS SelectUlsterRecs
PROCEDURE IS SelectUlsterRecs
GIVING SortedSales.
GIVING SortedSales.
OPEN
OPEN INPUT
INPUT SortedSales.
SortedSales.

SelectUlsterRecs.
SelectUlsterRecs.
OPEN
OPEN INPUT
INPUT UnsortedSales
UnsortedSales
READ
READ UnsortedSales INTO
UnsortedSales INTO WorkRec
WorkRec
AT
AT END SET EndOfSalesFile TO
END SET EndOfSalesFile TO TRUE
TRUE
END-READ
END-READ
PERFORM
PERFORM UNTIL
UNTIL EndOfSalesFile
EndOfSalesFile
IF
IF ProvinceIsUlster
ProvinceIsUlster RELEASE
RELEASE WorkRec
WorkRec
END-IF
END-IF
READ
READ UnsortedSales
UnsortedSales INTO
INTO WorkRec
WorkRec
AT
AT END SET EndOfSalesFile TO
END SET EndOfSalesFile TO TRUE
TRUE
END-READ
END-READ
END-PERFORM
END-PERFORM
CLOSE
CLOSE UnsortedSales
UnsortedSales
Full Sort
Syntax.

 ProcedureName is the name of a section or


paragraph.
works.

SalesFile SalesSummaryFile

Unsorted Salesman
Summary
Records Record
Sorted
SORT Records
Process
SummariseSale
s

WorkFile

SORT WorkFile ON ASCENDING KEY WSalesmanNum


USING SalesFile
OUTPUT PROCEDURE IS SummariseSales.
OUTPUT PROCEDURE
Template

OPEN OUTPUT OutFile


RETURN SDWorkFile RECORD
PERFORM UNTIL Condition
WRITE OutRec
RETURN SDWorkFile RECORD
END-PERFORM
CLOSE OutFile
Output PROCEDURE - Example

FD
FD SalesFile.
SalesFile.
01
01 SalesRec
SalesRec PIC
PIC X(10).
X(10).
SD
SD WorkFile.
WorkFile.
01
01 WorkRec.
WorkRec.
88
88 EndOfWorkFile
EndOfWorkFile VALUE
VALUE HIGH-VALUES.
HIGH-VALUES.
02
02 WSalesmanNum
WSalesmanNum PIC
PIC 9(5).
9(5).
02
02 FILLER
FILLER PIC
PIC X.
X.
02
02 WQtySold
WQtySold PIC
PIC X(4).
X(4).
FD
FD SalesSummaryFile.
SalesSummaryFile.
01
01 SummaryRec.
SummaryRec.
02
02 SalesmanNum
SalesmanNum PIC
PIC 9(5).
9(5).
02
02 TotalQtySold
TotalQtySold PIC
PIC 9(6).
9(6).
PROCEDURE
PROCEDURE DIVISION.
DIVISION.
Begin.
Begin.
SORT
SORT WorkFile
WorkFile ONON ASCENDING
ASCENDING KEYKEY WSalesmanNum
WSalesmanNum
USING
USING SalesFile
SalesFile
OUTPUT
OUTPUT PROCEDURE
PROCEDURE IS IS SummariseSales.
SummariseSales.
OPEN
OPEN INPUT
INPUT SalesSummaryFile.
SalesSummaryFile.
PERFORM
PERFORM PrintSummaryReport.`
PrintSummaryReport.`
SummariseSales.
SummariseSales.
OPEN
OPEN OUTPUT
OUTPUT SalesSummaryFile
SalesSummaryFile
RETURN
RETURN WorkFile
WorkFile
AT
AT END
END SET
SET EndOfWorkFile
EndOfWorkFile TO TO TRUE
TRUE
END-RETURN
END-RETURN
PERFORM
PERFORM UNTIL
UNTIL EndOfWorkFile
EndOfWorkFile
MOVE
MOVE WSalesmanNum
WSalesmanNum TO TO SalesmanNum
SalesmanNum
MOVE
MOVE ZEROS
ZEROS TOTO TotalQtySold
TotalQtySold
PERFORM
PERFORM UNTIL
UNTIL WSalesManNum
WSalesManNum NOT
NOT == SalesmanNum
SalesmanNum
OR
OR EndOfWorkFile
EndOfWorkFile
ADD
ADD WQtySold
WQtySold TO TO TotalQtySold
TotalQtySold
RETURN
RETURN WorkFile
WorkFile
AT
AT END
END SET
SET EndOfWorkFile
EndOfWorkFile TOTO TRUE
TRUE
END-RETURN
END-RETURN
END-PERFORM
END-PERFORM
WRITE
WRITE SummaryRec
SummaryRec
END-PERFORM
END-PERFORM
CLOSE
CLOSE SalesSummaryFile.
SalesSummaryFile.
RELEASE and RETURN
Syntax

Write

Read

528
Feeding the SORT from the
keyboard.

8965125COUGHLAN

StudentFile

Sorted
Student
Unsorted Records
Student SORT
Records Process
GetStudentDetail
s
WorkFile

SORT WorkFile ON ASCENDING KEY WStudentId


INPUT PROCEDURE IS GetStudentDetails
GIVING StudentFile.
ENVIRONMENT
ENVIRONMENT DIVISION.
DIVISION.
INPUT-OUTPUT
INPUT-OUTPUT SECTION.
SECTION.
FILE-CONTROL.
FILE-CONTROL.
SELECT
SELECT StudentFile
StudentFile ASSIGN
ASSIGN TOTO "SORTSTUD.DAT"
"SORTSTUD.DAT"
ORGANIZATION
ORGANIZATION IS LINE SEQUENTIAL.
IS LINE SEQUENTIAL.
SELECT WorkFile ASSIGN TO "WORK.TMP".
SELECT WorkFile ASSIGN TO "WORK.TMP".
DATA
DATA DIVISION.
DIVISION.
FILE SECTION.
FILE SECTION.
FD
FD StudentFile.
StudentFile.
01 StudentDetails
01 StudentDetails PIC
PIC X(32).
X(32).
SD WorkFile.
SD WorkFile.
01
01 WorkRec.
WorkRec.
02
02 WStudentId
WStudentId PIC
PIC 9(7).
9(7).
02 FILLER
02 FILLER PIC X(25).
PIC X(25).
PROCEDURE DIVISION.
PROCEDURE DIVISION.
Begin.
Begin.
SORT
SORT WorkFile
WorkFile ONON ASCENDING
ASCENDING KEY
KEY WStudentId
WStudentId
INPUT PROCEDURE IS GetStudentDetails
INPUT PROCEDURE IS GetStudentDetails
GIVING
GIVING StudentFile.
StudentFile.
STOP RUN.
STOP RUN.
GetStudentDetails.
GetStudentDetails.
DISPLAY
DISPLAY "Enter
"Enter student
student details
details using
using template
template below."
below."
DISPLAY "Enter no data to end.".
DISPLAY "Enter no data to end.".
DISPLAY
DISPLAY "NNNNNNNSSSSSSSSIIYYMMDDCCCCGGGGS".
"NNNNNNNSSSSSSSSIIYYMMDDCCCCGGGGS".
ACCEPT WorkRec.
ACCEPT WorkRec.
PERFORM
PERFORM UNTIL
UNTIL WorkRec
WorkRec == SPACES
SPACES
RELEASE WorkRec
RELEASE WorkRec
ACCEPT
ACCEPT WorkRec
WorkRec
END-PERFORM.
END-PERFORM.
MERGE
Syntax.

 The Merge takes two or more identically sequenced files and


combines them, according to the key values specified, to produce a
combined file which is then output to an output file or OUTPUT
PROCEDURE.
 e.g.
MERGE WorkFile ON ASCENDING KEY StudentId
USING InsertionsFile, StudentFile
GIVING NewStudentFile.
531
ENVIRONMENT
ENVIRONMENT DIVISION.
DIVISION.
INPUT-OUTPUT
INPUT-OUTPUT SECTION.
SECTION.
FILE-CONTROL.
FILE-CONTROL.
SELECT
SELECT StudentFile
StudentFile ASSIGN
ASSIGN TO
TO "STUDENTS.DAT"
"STUDENTS.DAT"
ORGANIZATION IS LINE SEQUENTIAL.
ORGANIZATION IS LINE SEQUENTIAL.
SELECT
SELECT InsertionsFile ASSIGN
InsertionsFile ASSIGN TO
TO "TRANSINS.DAT"
"TRANSINS.DAT"
ORGANIZATION IS LINE SEQUENTIAL.
ORGANIZATION IS LINE SEQUENTIAL.
SELECT
SELECT NewStudentFile ASSIGN
NewStudentFile ASSIGN TO
TO "STUDENTS.NEW"
"STUDENTS.NEW"
ORGANIZATION IS LINE SEQUENTIAL.
ORGANIZATION IS LINE SEQUENTIAL.
SELECT WorkFile
SELECT WorkFile ASSIGN
ASSIGN TO
TO "WORK.TMP".
"WORK.TMP".
DATA
DATA DIVISION.
DIVISION.
FILE SECTION.
FILE SECTION.
FD
FD StudentFile.
StudentFile.
01 StudentRec
01 StudentRec PIC
PIC X(32).
X(32).
FD
FD InsertionsFile.
InsertionsFile.
01 InsertionRec
01 InsertionRec PIC
PIC X(32).
X(32).
FD
FD NewStudentFile.
NewStudentFile.
01 NewStudentRec
01 NewStudentRec PIC
PIC X(32).
X(32).
SD
SD WorkFile.
WorkFile.
01 WorkRec.
01 WorkRec.
02
02 WStudentId
WStudentId PIC
PIC 9(7).
9(7).
02 FILLER
02 FILLER PIC X(25).
PIC X(25).
PROCEDURE
PROCEDURE DIVISION.
DIVISION.
Begin.
Begin.
MERGE
MERGE WorkFile
WorkFile ON
ON ASCENDING
ASCENDING KEY
KEY WStudentId
WStudentId
USING InsertionsFile, StudentFile
USING InsertionsFile, StudentFile
GIVING
GIVING NewStudentFile.
NewStudentFile.
STOP RUN.
STOP RUN.
Introductio
n to
Direct
Access
Files.
Record

Ordered Rec085 Unordered


Rec001 Rec300
Rec005 Rec150
Rec045 Rec005
Rec090 Rec090
Rec100 Rec045
Rec150 Rec100
Rec300 Rec001
Rec325 Rec325
^Z ^Z
Record

New-Ordered Rec085 Extend-Unordered


Rec001 Rec300
Rec005 Rec150
Rec045 Rec005
Rec085 Rec090
Rec090 Rec045
Rec100 Rec100
Rec150 Rec001
Rec300 Rec325
Rec325 Rec085
^Z ^Z
Sequential Files - Deleting a
Record

Ordered Rec150 Unordered


Rec001 Rec300
Rec005 Rec150
Rec045 Rec005
Rec090 Rec090
Rec100 Rec045
Rec150 Rec100
Rec300 Rec001
Rec325 Rec325
^Z ^Z
Sequential Files - Deleting a
Record

New-Ordered Rec150 New-Unordered


Rec001 Rec300
Rec005 Rec005
Rec045 Rec090
Rec090 Rec045
Rec100 Rec100
Rec300 Rec001
Rec325 Rec325
^Z ^Z
Record

Ordered Rec045 Unordered


Rec001 Rec300
Rec005 Rec150
Rec045 Rec005
Rec090 Rec090
Rec100 Rec045
Rec150 Rec100
Rec300 Rec001
Rec325 Rec325
^Z ^Z
Record

New-Ordered Rec045 New-Unordered


Rec001 Rec300
Rec005 Rec150
Rec045 Rec005
Rec090 Rec090
Rec100 Rec045
Rec150 Rec100
Rec300 Rec001
Rec325 Rec325
^Z ^Z
Organization
1 Rec001
2 free
3 Rec003
Relative
4 Rec004
Record 5 free
Number
6 free
7 Rec007

325 Rec325
326 Rec326
327 free
328 Rec328
Record
1 Rec001
2 free
3 Rec003 Rec327
Relative
4 Rec004
Record 5 free
Number
6 free
7 Rec007

325 Rec325
326 Rec326
327 free
328 Rec328
Record
1 Rec001
2 free
3 Rec003 Rec327
Relative
4 Rec004
Record 5 free
Number
6 free
7 Rec007

325 Rec325
326 Rec326
327 Rec327
328 Rec328
Record
1 Rec001
2 free
3 Rec003 Rec325
Relative
4 Rec004
Record 5 free
Number
6 free
7 Rec007

325 Rec325
326 Rec326
327 free
328 Rec328
Record
1 Rec001
2 free
3 Rec003 Rec325
Relative
4 Rec004
Record 5 free
Number
6 free
7 Rec007

325 deleted/free
326 Rec326
327 free
328 Rec328
Relative Files - Amending a
Record
1 Rec001
2 free
3 Rec003 Rec007
Relative
4 Rec004
Record 5 free
Number
6 free
7 Rec007

325 Rec325
326 Rec326
327 free
328 Rec328
Relative Files - Amending a
Record
1 Rec001
2 free
3 Rec003 Rec007
Relative
4 Rec004
Record 5 free
Number
6 free
7 Rec007

325 Rec325
326 Rec326
327 free
328 Rec328
Organization

H R Z
Index Records

C F H L O R T W Z

Mi Nf Ni Nt Oi Ot

Data Records
Ni

H R Z
Index Records

C F H L O R T W Z

Mi Nf Ni Nt Oi Ot

Data Records
Ni

H R Z
Index Records

C F H L O R T W Z

Mi Nf Ni Nt Oi Ot

Data Records
Indexed Files - Reading Record
Ni

H R Z
Index Records

C F H L O R T W Z

Mi Nf Ni Nt Oi Ot

Data Records
Sequential
Files.

Disadvantages.
 Slow - when the hit rate is low.
 Complicated to change (insert, delete, amend)

Advantages.

 Fast - when the hit rate is high.


 Most storage efficient.
 Simple organization.
 Recovers space from deleted records.
551
Relative
Files.
Disadvantages.
 Wasteful of storage if the file is only partially
populated.
 Cannot recover space from deleted records.
 Only a single, numeric key allowed.
 Keys must map on to the range of the Relative
Record numbers.

Advantages.

 Fastest Direct Access organization.


 Very little storage overhead.
 Can be read sequentially. 552
Indexed
Files.
Disadvantages.
 Slowest Direct Access organization.
 Especially slow when adding or deleting records.
 Not very storage efficient. Must store the Index
records, the alternate Index records, the data records
and the alternate data records.

Advantages.

 Can use multiple, alphanumeric keys.


 Can have duplicate alternate keys.
 Can be read sequentially on any of its keys.
553
 Can partially recover space from deleted records.
Relati
ve
Files.
File
$$ SET
SET SOURCEFORMAT"FREE"
SOURCEFORMAT"FREE"
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID.
PROGRAM-ID. CreateRelativeFromSeq.
CreateRelativeFromSeq.
** Creates
Creates aa Relative
Relative file
file from
from aa sequential
sequential file.
file.
ENVIRONMENT
ENVIRONMENT DIVISION.
DIVISION.
INPUT-OUTPUT
INPUT-OUTPUT SECTION.
SECTION.
FILE-CONTROL.
FILE-CONTROL.
SELECT
SELECT SupplierFile
SupplierFile ASSIGN
ASSIGN TO
TO "SUPP.DAT"
"SUPP.DAT"
ORGANIZATION IS RELATIVE
ORGANIZATION IS RELATIVE
ACCESS
ACCESS MODE
MODE IS
IS RANDOM
RANDOM
RELATIVE
RELATIVE KEY IS SupplierKey
KEY IS SupplierKey
FILE
FILE STATUS
STATUS IS
IS SupplierStatus.
SupplierStatus.
SELECT
SELECT SupplierFileSeq
SupplierFileSeq ASSIGN
ASSIGN TOTO "INSUPP.DAT".
"INSUPP.DAT".
DATA
DATA DIVISION.
DIVISION.
FILE
FILE SECTION.
SECTION.
FD SupplierFile.
FD SupplierFile.
01
01 SupplierRecord.
SupplierRecord.
02
02 SupplierCode
SupplierCode PIC
PIC 99.
99.
02 SupplierName
02 SupplierName PIC X(20).
PIC X(20).
02
02 SupplierAddress
SupplierAddress PIC
PIC X(60).
X(60).
FD
FD SupplierFileSeq.
SupplierFileSeq.
01 SupplierRecordSeq.
01 SupplierRecordSeq.
88
88 EndOfFile
EndOfFile VALUE
VALUE HIGH-VALUES.
HIGH-VALUES.
02 SupplierCodeSeq
02 SupplierCodeSeq PIC
PIC 99.
99.
02 SupplierNameSeq
02 SupplierNameSeq PIC X(20).
PIC X(20).
02
02 SupplierAddressSeq
SupplierAddressSeq PIC
PIC X(60).
X(60).
WORKING-STORAGE
WORKING-STORAGE SECTION.
SECTION.
01 SupplierStatus
01 SupplierStatus PIC
PIC X(2).
X(2).
01 SupplierKey
01 SupplierKey PIC 99.
PIC 99.
File
$$ SET
SET SOURCEFORMAT"FREE"
SOURCEFORMAT"FREE"
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID.
PROGRAM-ID. CreateRelativeFromSeq.
CreateRelativeFromSeq.
** Creates
Creates aa Relative
Relative file
file from
from aa sequential
sequential file.
file.
ENVIRONMENT
ENVIRONMENT DIVISION.
DIVISION.
INPUT-OUTPUT
INPUT-OUTPUT SECTION.
SECTION.
FILE-CONTROL.
FILE-CONTROL.
SELECT
SELECT SupplierFile
SupplierFile ASSIGN
ASSIGN TO
TO "SUPP.DAT"
"SUPP.DAT"
ORGANIZATION IS RELATIVE
ORGANIZATION IS RELATIVE
ACCESS
ACCESS MODE
MODE IS
IS RANDOM
RANDOM
RELATIVE
RELATIVE KEY IS SupplierKey
KEY IS SupplierKey
FILE
FILE STATUS
STATUS IS
IS SupplierStatus.
SupplierStatus
SupplierStatus.
SupplierStatus
SELECT
SELECT SupplierFileSeq ASSIGN
SupplierFileSeq ASSIGN TOTO "INSUPP.DAT".
"INSUPP.DAT".
DATA
DATA DIVISION.
DIVISION.
FILE
FILE SECTION.
SECTION.
FD SupplierFile.
FD SupplierFile.
01
01 SupplierRecord.
SupplierRecord.
02
02 SupplierCode
SupplierCode PIC
PIC 99.
99.
02 SupplierName
02 SupplierName PIC X(20).
PIC X(20).
02
02 SupplierAddress
SupplierAddress PIC
PIC X(60).
X(60).
FD
FD SupplierFileSeq.
SupplierFileSeq.
01 SupplierRecordSeq.
01 SupplierRecordSeq.
88
88 EndOfFile
EndOfFile VALUE
VALUE HIGH-VALUES.
HIGH-VALUES.
02 SupplierCodeSeq
02 SupplierCodeSeq PIC
PIC 99.
99.
02 SupplierNameSeq
02 SupplierNameSeq PIC X(20).
PIC X(20).
02
02 SupplierAddressSeq
SupplierAddressSeq PIC
PIC X(60).
X(60).
WORKING-STORAGE
WORKING-STORAGE SECTION.
SECTION.
01 SupplierStatus
01 SupplierStatus PIC
PIC X(2).
X(2).
01 SupplierKey
01 SupplierKey PIC 99.
PIC 99.
Creating a Relative
File

PROCEDURE
PROCEDURE DIVISION.
DIVISION.
Begin.
Begin.
OPEN
OPEN OUTPUT
OUTPUT SupplierFile.
SupplierFile.
OPEN INPUT SupplierFileSeq.
OPEN INPUT SupplierFileSeq.
READ
READ SupplierFileSeq
SupplierFileSeq
AT
AT END SET
END SET EndOfFile
EndOfFile TO
TO TRUE
TRUE
END-READ
END-READ
PERFORM
PERFORM UNTIL
UNTIL EndOfFile
EndOfFile
MOVE
MOVE SupplierCodeSeq TO
SupplierCodeSeq TO SupplierKey
SupplierKey
MOVE
MOVE SupplierRecordSeq TO SupplierRecord
SupplierRecordSeq TO SupplierRecord
WRITE SupplierRecord
WRITE SupplierRecord
INVALID
INVALID KEY
KEY DISPLAY
DISPLAY "SUPP
"SUPP STATUS
STATUS :-",
:-", SupplierStatus
SupplierStatus
END-WRITE
END-WRITE
READ
READ SupplierFileSeq
SupplierFileSeq
AT
AT END SET
END SET EndOfFile
EndOfFile TOTO TRUE
TRUE
END-READ
END-READ
END-PERFORM.
END-PERFORM.
CLOSE
CLOSE SupplierFile,
SupplierFile, SupplierFileSeq.
SupplierFileSeq.
STOP RUN.
STOP RUN.
File.
$$ SET
SET SOURCEFORMAT"FREE"
SOURCEFORMAT"FREE"
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID.
PROGRAM-ID. ReadRelative.
ReadRelative.
** Reads
Reads aa Relative
Relative file
file directly
directly or
or inin sequence
sequence
ENVIRONMENT
ENVIRONMENT DIVISION.
DIVISION.
INPUT-OUTPUT
INPUT-OUTPUT SECTION.
SECTION.
FILE-CONTROL.
FILE-CONTROL.
SELECT
SELECT SupplierFile
SupplierFile ASSIGN
ASSIGN TO
TO "SUPP.DAT"
"SUPP.DAT"
ORGANIZATION IS RELATIVE
ORGANIZATION IS RELATIVE
ACCESS
ACCESS MODE
MODE IS
IS DYNAMIC
DYNAMIC
RELATIVE
RELATIVE KEY
KEY IS
IS SupplierKey
SupplierKey
FILE STATUS IS SupplierStatus.
SupplierStatus
FILE STATUS IS SupplierStatus.
SupplierStatus
DATA
DATA DIVISION.
DIVISION.
FILE
FILE SECTION.
SECTION.
FD SupplierFile.
FD SupplierFile.
01
01 SupplierRecord.
SupplierRecord.
88
88 EndOfFile
EndOfFile VALUE
VALUE HIGH-VALUES.
HIGH-VALUES.
02 SupplierCode
02 SupplierCode PIC
PIC 99.
99.
02
02 SupplierName
SupplierName PIC
PIC X(20).
X(20).
02 SupplierAddress
02 SupplierAddress PIC X(60).
PIC X(60).
WORKING-STORAGE
WORKING-STORAGE SECTION.
SECTION.
01
01 SupplierStatus
SupplierStatus PIC
PIC X(2).
X(2).
88 RecordFound
88 RecordFound VALUE
VALUE "00".
"00".
01 SupplierKey
01 SupplierKey PIC 99.
PIC 99.
01
01 PrnSupplierRecord.
PrnSupplierRecord.
02
02 PrnSupplierCode
PrnSupplierCode PIC
PIC BB99.
BB99.
02
02 PrnSupplierName
PrnSupplierName PIC
PIC BBX(20).
BBX(20).
02 PrnSupplierAddress
02 PrnSupplierAddress PIC BBX(50).
PIC BBX(50).
01 ReadType
01 ReadType PIC
PIC 9.
9.
88 DirectRead
88 DirectRead VALUE
VALUE 1.1.
88 SequentialRead
88 SequentialRead VALUE 2.
VALUE 2.
File.
PROCEDURE
PROCEDURE DIVISION.
DIVISION.
BEGIN.
BEGIN.
OPEN
OPEN INPUT
INPUT SupplierFile.
SupplierFile.
DISPLAY
DISPLAY "Enter
"Enter Read
Read type
type (Direct=1,
(Direct=1, Seq=2)->
Seq=2)-> "" WITH
WITH NO
NO ADVANCING.
ADVANCING.
ACCEPT
ACCEPT ReadType.
ReadType.
IF
IF DirectRead
DirectRead
DISPLAY
DISPLAY "Enter
"Enter supplier
supplier key
key (2
(2 digits)->
digits)-> "" WITH
WITH NO
NO ADVANCING
ADVANCING
ACCEPT
ACCEPT SupplierKey
SupplierKey
READ SupplierFile
READINVALID
SupplierFile
INVALID KEY
KEY DISPLAY
DISPLAY "SUPP
"SUPP STATUS
STATUS :-",
:-", SupplierStatus
SupplierStatus
END-READ
END-READ
PERFORM
PERFORM DisplayRecord
DisplayRecord
END-IF
END-IF
IF
IF SequentialRead
SequentialRead
READ SupplierFile
READATSupplierFile NEXT
NEXT RECORD
RECORD
AT END SET EndOfFile TO
END-READ
END SET EndOfFile TO TRUE
TRUE
END-READ
PERFORM UNTIL EndOfFile
PERFORM UNTIL
PERFORM EndOfFile
DisplayRecord
PERFORM
READ DisplayRecord
SupplierFile NEXT
READATSupplierFile
END SET NEXT RECORD
EndOfFile RECORD
TO
AT
END-READ END SET EndOfFile TO TRUE
TRUE
END-READ
END-PERFORM
END-IFEND-PERFORM
END-IF
CLOSE SupplierFile.
CLOSERUN.
SupplierFile.
STOP
STOP RUN.
DisplayRecord.
DisplayRecord.
IF
IF RecordFound
RecordFound
MOVE
MOVE SupplierCode
SupplierCode TO TO PrnSupplierCode
PrnSupplierCode
MOVE SupplierName
MOVE SupplierAddress TO
SupplierName TO TO PrnSupplierName
PrnSupplierName
MOVE
MOVE SupplierAddress TO PrnSupplierAddress
PrnSupplierAddress
DISPLAY
DISPLAY PrnSupplierRecord
PrnSupplierRecord
END-IF.
END-IF.
Reading a Relative
File.

RUN
RUN OF
OF REL-EG2.EXE
REL-EG2.EXE USING
USING SEQUENTIAL
SEQUENTIAL READING
READING
Enter Read type (Direct=1, Seq=2)->
Enter Read type (Direct=1, Seq=2)-> 2 2
01
01 VESTRON
VESTRON VIDEOS
VIDEOS OVER
OVER THE
THE SEA
SEA SOMEWHERE
SOMEWHERE IN
IN LONDON
LONDON
02 EMI STUDIOS
02 EMI STUDIOS HOLLYWOOD, CALIFORNIA,
HOLLYWOOD, CALIFORNIA, USA USA
03 BBC WILDLIFE
03 BBC WILDLIFE BUSH
BUSH HOUSE,
HOUSE, LONDON,
LONDON, ENGLAND
ENGLAND
04
04 CBSCBS STUDIOS
STUDIOS HOLLYWOOD,
HOLLYWOOD, CALIFORNIA,
CALIFORNIA, USA
USA
05 YACHTING MONTHLY
05 YACHTING MONTHLY TREE HOUSE, LONDON, ENGLAND
TREE HOUSE, LONDON, ENGLAND
06
06 VIRGIN
VIRGIN VIDEOS
VIDEOS IS
IS THIS
THIS ONE
ONE ALSO
ALSO LOCATED
LOCATED IN
IN ENGLAND
ENGLAND
07 CIC VIDEOS
07 CIC VIDEOS NEW YORK PLAZZA, NEW YORK,
NEW YORK PLAZZA, NEW YORK, USA USA

RUN
RUN OF
OF REL-EG2.EXE
REL-EG2.EXE USING
USING DIRECT
DIRECT READ
READ
Enter
Enter Read type (Direct=1, Seq=2)-> 11
Read type (Direct=1, Seq=2)->
Enter
Enter supplier
supplier key
key (2
(2 digits)->
digits)-> 05
05
05
05 YACHTING
YACHTING MONTHLY
MONTHLY TREE
TREE HOUSE,
HOUSE, LONDON,
LONDON, ENGLAND
ENGLAND
Select and Assign for Relative Files

561
FDs for Relative
Files

562
Relative File Verbs -
OPEN

563
Relative File Verbs -
READ

564
Relative File Verbs - Write and Rewrite

565
Relative File Verbs - DELETE

566
Relative File Verbs -
START

567
Error Handling Using Declaratives.
PROCEDURE
PROCEDURE DIVISION.
DIVISION.
DECLARATIVES.
DECLARATIVES.
SectionOne
SectionOne SECTION.
SECTION.
USE
USE clause for
clause for this
this section.
section.
ParOne1.
ParOne1.
????????????????
????????????????
????????????????
????????????????
ParOne2.
ParOne2.
????????????????
????????????????
????????????????
????????????????

SectionTwo
SectionTwo SECTION.
SECTION.
USE
USE clause
clause for
for this
this section.
section.
ParTwo1.
ParTwo1.
????????????????
????????????????
????????????????
????????????????
ParTwo2.
ParTwo2.
????????????????
????????????????
????????????????
????????????????
END-DECLARATIVES.
END-DECLARATIVES.
Main
Main SECTION.
SECTION.
Begin.
Begin.
Error Handling Using Declaratives.

PROCEDURE
PROCEDURE DIVISION.
DIVISION.
DECLARATIVES.
DECLARATIVES.
FileError
FileError SECTION.
SECTION.
USE
USE AFTER ERROR
AFTER ERROR PROCEDURE
PROCEDURE ON
ON RelativeFile.
RelativeFile.
CheckFileStatus.
CheckFileStatus.
EVALUATE
EVALUATE TRUE
TRUE
WHEN RecordDoesNotExist
WHEN RecordDoesNotExist
DISPLAY
DISPLAY "Record
"Record does
does not
not exist"
exist"
WHEN RecordAlreadyExists
WHEN RecordAlreadyExists
DISPLAY
DISPLAY "Record
"Record already
already exists"
exists"
WHEN FileNotOpen OPEN I-O RelativeFile
WHEN FileNotOpen OPEN I-O RelativeFile
END-EVALUATE.
END-EVALUATE.
END-DECLARATIVES.
END-DECLARATIVES.
Main
Main SECTION.
SECTION.
Begin.
Begin.
Index
ed
Files.
Creating an Indexed File
$$ SET
SET SOURCEFORMAT"FREE"
IDENTIFICATION SOURCEFORMAT"FREE"
DIVISION.
IDENTIFICATION
PROGRAM-ID. DIVISION.
CreateIndexedFromSeq.
*PROGRAM-ID. CreateIndexedFromSeq.
* Creates
Creates anan indexed
indexed file
file from
from aa sequential
sequential file.
file.
ENVIRONMENT
ENVIRONMENT DIVISION.
INPUT-OUTPUT DIVISION.
SECTION.
INPUT-OUTPUT
FILE-CONTROL. SECTION.
FILE-CONTROL.
SELECT
SELECT VideoFile
VideoFile ASSIGN TO
ORGANIZATIONASSIGN
IS TO "VIDEO.DAT"
"VIDEO.DAT"
INDEXED
ORGANIZATION
ACCESS IS INDEXED
ACCESS MODE
RECORD MODE
KEY
IS
ISIS RANDOM
RANDOM
VideoCode
RECORD
ALTERNATEKEY IS VideoCode
ALTERNATE RECORD KEY IS VideoTitle
RECORD
WITH KEY IS
DUPLICATESVideoTitle
FILE WITH DUPLICATES
FILE STATUS
STATUS IS
IS VideoStatus.
VideoStatus.
SELECT
SELECT SeqVideoFile
SeqVideoFile ASSIGN
ASSIGN TOTO "INVIDEO.DAT".
"INVIDEO.DAT".
DATA DIVISION.
DATA
FILE DIVISION.
SECTION.
FILE
FD SECTION.
VideoFile.
FD
01 VideoFile.
01 VideoRecord.
VideoRecord.
02
02 VideoCode PIC
02 VideoCode
VideoTitle PIC 9(5).
PIC 9(5).
X(40).
02
02 VideoTitle PIC X(40).
02 VideoSupplierCode PIC
VideoSupplierCode PIC 99.
99.
FD SeqVideoFile.
FD SeqVideoRecord.
01 SeqVideoFile.
01 88
SeqVideoRecord.
EndOfFile VALUE HIGH-VALUES.
88
02 EndOfFile
SeqVideoCode VALUE HIGH-VALUES.
PIC
02 SeqVideoTitle
02 SeqVideoCode PIC 9(5).
PIC 9(5).
X(40).
02
02 SeqVideoTitle PIC X(40).
02 SeqVideoSupplierCode PIC
SeqVideoSupplierCode PIC 99.
99.
WORKING-STORAGE
WORKING-STORAGE SECTION.
SECTION.
01 VideoStatus PIC
01 VideoStatus PIC X(2).
X(2).
Creating an Indexed
File

PROCEDURE
PROCEDURE DIVISION.
Begin. DIVISION.
Begin.
OPEN INPUT SeqVideoFile.
OPEN
OPEN INPUT SeqVideoFile.
OPEN OUTPUT VideoFile.
OUTPUT VideoFile.
READ SeqVideoFile
READ
AT SeqVideoFile
AT END
END SET
END-READ. SET EndOfFile
EndOfFile TO
TO TRUE
TRUE
END-READ.
PERFORM UNTIL EndOfFile
PERFORM
WRITE UNTIL EndOfFile
VideoRecord FROM SeqVideoRecord
WRITE VideoRecord
INVALID KEY FROM
DISPLAY SeqVideoRecord
"VIDEO STATUS :- ", VideoStatus
INVALID
END-WRITE KEY DISPLAY "VIDEO STATUS :- ", VideoStatus
END-WRITE
READ SeqVideoFile
READ
AT SeqVideoFile
END SET EndOfFile TO TRUE
AT
END-READ END SET EndOfFile TO TRUE
END-READ
END-PERFORM.
END-PERFORM.
CLOSE
CLOSE VideoFile,
VideoFile, SeqVideoFile.
SeqVideoFile.
STOP RUN.
STOP RUN.
Reading an Indexed File - Sequentially.
$$ SET
SET SOURCEFORMAT"FREE"
IDENTIFICATION SOURCEFORMAT"FREE"
DIVISION.
IDENTIFICATION
PROGRAM-ID. DIVISION.
ReadingIndexedFile.
PROGRAM-ID.
** Sequential ReadingIndexedFile.
Sequential reading
reading of
of an
an indexed
indexed file
file
ENVIRONMENT
ENVIRONMENT DIVISION.
INPUT-OUTPUT DIVISION.
SECTION.
INPUT-OUTPUT
FILE-CONTROL. SECTION.
FILE-CONTROL.
SELECT
SELECT VideoFile
VideoFile ASSIGN TO
ORGANIZATION ASSIGN
IS TO "VIDEO.DAT"
"VIDEO.DAT"
INDEXED
ORGANIZATION
ACCESS MODE IS IS INDEXED
DYNAMIC
ACCESS
RECORD MODE
KEY ISIS DYNAMIC
VideoCode
RECORD KEYRECORD
ALTERNATE IS VideoCode
KEY
ALTERNATE
WITH RECORD
DUPLICATESKEY IS
IS VideoTitle
VideoTitle
FILE WITH DUPLICATES
FILE STATUS
STATUS IS
IS VideoStatus.
VideoStatus.
DATA
DATA DIVISION.
FILE DIVISION.
SECTION.
FILE
FD SECTION.
VideoFile
FD
01 VideoFile
01 VideoRecord.
VideoRecord.
88
88 EndOfFile
02 EndOfFile VALUE
VideoCode VALUE HIGH-VALUE.
HIGH-VALUE.
PIC 9(5).
02
02 VideoCode
VideoTitle PIC
PIC 9(5).
X(40).
02 SupplierCode
02 VideoTitle PIC 99.
PIC X(40).
02 SupplierCode PIC 99.
WORKING-STORAGE SECTION.
WORKING-STORAGE
01 VideoStatus SECTION. PIC
01 VideoStatus PIC X(2).
X(2).
01 RequiredSequence PIC 9.
01 88
RequiredSequence
VideoCodeSequence PIC 9.1.
VALUE
88
88 VideoCodeSequence VALUE 2.
1.
88 VideoTitleSequence VALUE
VideoTitleSequence VALUE 2.
01
01 PrnVideoRecord.
PrnVideoRecord.
02
02 PrnVideoCode PIC
02 PrnVideoCode
PrnVideoTitle PIC 9(5).
PIC 9(5).
BBBBX(40).
02
02 PrnVideoTitle
PrnSupplierCode PIC
PIC BBBBX(40).
BBBB99.
02 PrnSupplierCode PIC BBBB99.
Reading an Indexed File - Sequentially.
PROCEDURE DIVISION.
PROCEDURE
Begin. DIVISION.
Begin.
OPEN
OPEN INPUT
INPUT VideoFile.
VideoFile.
DISPLAY "Enter key
DISPLAY
WITH "Enter
NO key :: 1=VideoCode,
ADVANCING. 1=VideoCode, 2=VideoTitle
2=VideoTitle ->"->"
WITH
ACCEPT NO ADVANCING.
ACCEPT RequiredSequence.
RequiredSequence.
IF
IF VideoTitleSequence
VideoTitleSequence
MOVE
MOVE SPACES TO
START SPACES TO VideoTitle
VideoFile VideoTitle
KEY
KEY IS
IS GREATER THAN
START VideoFile
INVALID KEY DISPLAY GREATER
"VIDEO THAN VideoTitle
STATUS VideoTitle
:- ", VideoStatus
INVALID
END-START KEY DISPLAY "VIDEO STATUS :- ", VideoStatus
END-START
END-IF
END-IF
READ VideoFile NEXT
READ
AT VideoFile
END SET NEXT RECORD
EndOfFileRECORD
TO
AT
END-READ.END SET EndOfFile TO TRUE
TRUE
END-READ.
PERFORM UNTIL
PERFORM
MOVE UNTIL EndOfFile
VideoCodeEndOfFile
TO PrnVideoCode
MOVE
MOVE VideoCode
VideoTitle TO
TO PrnVideoCode
PrnVideoTitle
MOVE
MOVE VideoTitle
SupplierCode TOTOPrnVideoTitle
MOVE SupplierCode
DISPLAY TO PrnSupplierCode
PrnVideoRecord PrnSupplierCode
DISPLAY
READ PrnVideoRecord
VideoFile NEXT
READ
AT VideoFile
END SET NEXT RECORD
RECORD
EndOfFile TO
AT
END-READ END SET EndOfFile TO TRUE
TRUE
END-READ
END-PERFORM.
END-PERFORM.
CLOSE VideoFile.
CLOSE
STOP VideoFile.
RUN.
STOP RUN.
Reading an Indexed File - Sequentially.
RUN OF INDEX-EG2.EXE USING VIDEOCODE KEY RUN OF INDEX-EG2 USING VIDEOTITLE KEY
RUN OF INDEX-EG2.EXE USING VIDEOCODE KEY RUN OF INDEX-EG2 USING VIDEOTITLE KEY
Enter key : 1=VideoCode, 2=VideoTitle ->1 Enter key : 1=VideoCode, 2=VideoTitle ->2
Enter key : 1=VideoCode, 2=VideoTitle ->1 Enter key : 1=VideoCode, 2=VideoTitle ->2
00121 FLIGHT OF THE CONDOR, THE 03 17001 ALIEN 07
00121 FLIGHT OF THE CONDOR, THE 03 17001 ALIEN 07
00333 PREDATOR 02 17002 ALIENS 07
00333 PREDATOR 02 17002 ALIENS 07
00444 LIVING EARTH, THE 03 07071 AMONG THE WILD CHIMPANZEES 03
00444 LIVING EARTH, THE 03 07071 AMONG THE WILD CHIMPANZEES 03
01001 COMMANDO 02 09091 BESTSELLER 07
01001 COMMANDO 02 09091 BESTSELLER 07
01100 ROBOCOP 01 01001 COMMANDO 02
01100 ROBOCOP 01 01001 COMMANDO 02
02001 LEOPARD HUNTS IN DARKNESS, A 03 03031 COMPETENT CREW 05
02001 LEOPARD HUNTS IN DARKNESS, A 03 03031 COMPETENT CREW 05
02121 DIRTY DANCING 04 02121 DIRTY DANCING 04
02121 DIRTY DANCING 04 02121 DIRTY DANCING 04
03031 COMPETENT CREW 05 00121 FLIGHT OF THE CONDOR, THE 03
03031 COMPETENT CREW 05 00121 FLIGHT OF THE CONDOR, THE 03
03032 YACHT MASTER 05 17041 GARFIELD TAKES A HIKE 06
03032 YACHT MASTER 05 17041 GARFIELD TAKES A HIKE 06
04041 OPEN OCEAN SAILING 05 06061 HOPE AND GLORY 07
04041 OPEN OCEAN SAILING 05 06061 HOPE AND GLORY 07
04042 PRINCESS BRIDE, THE 06 14032 KNOTTY PROBLEMS FOR SAILORS 05
04042 PRINCESS BRIDE, THE 06 14032 KNOTTY PROBLEMS FOR SAILORS 05
04444 LIFE ON EARTH 03 02001 LEOPARD HUNTS IN DARKNESS, A 03
04444 LIFE ON EARTH 03 02001 LEOPARD HUNTS IN DARKNESS, A 03
05051 OVERBOARD 01 04444 LIFE ON EARTH 03
05051 OVERBOARD 01 04444 LIFE ON EARTH 03
06061 HOPE AND GLORY 07 00444 LIVING EARTH, THE 03
06061 HOPE AND GLORY 07 00444 LIVING EARTH, THE 03
07071 AMONG THE WILD CHIMPANZEES 03 13301 MASSACRE AT MASAI MARA 03
07071 AMONG THE WILD CHIMPANZEES 03 13301 MASSACRE AT MASAI MARA 03
08081 WHALE NATION 03 04041 OPEN OCEAN SAILING 05
08081 WHALE NATION 03 04041 OPEN OCEAN SAILING 05
09091 BESTSELLER 07 05051 OVERBOARD 01
09091 BESTSELLER 07 05051 OVERBOARD 01
10001 WICKED WALTZING 04 19444 PINOCCIO 02
10001 WICKED WALTZING 04 19444 PINOCCIO 02
11111 TERMINATOR, THE 02 00333 PREDATOR 02
11111 TERMINATOR, THE 02 00333 PREDATOR 02
13301 MASSACRE AT MASAI MARA 03 04042 PRINCESS BRIDE, THE 06
13301 MASSACRE AT MASAI MARA 03 04042 PRINCESS BRIDE, THE 06
14032 KNOTTY PROBLEMS FOR SAILORS 05 01100 ROBOCOP 01
14032 KNOTTY PROBLEMS FOR SAILORS 05 01100 ROBOCOP 01
17001 ALIEN 07 18001 SURVIVING THE STORM 05
17001 ALIEN 07 18001 SURVIVING THE STORM 05
17002 ALIENS 07 11111 TERMINATOR, THE 02
17002 ALIENS 07 11111 TERMINATOR, THE 02
17041 GARFIELD TAKES A HIKE 06 08081 WHALE NATION 03
17041 GARFIELD TAKES A HIKE 06 08081 WHALE NATION 03
18001 SURVIVING THE STORM 05 10001 WICKED WALTZING 04
18001 SURVIVING THE STORM 05 10001 WICKED WALTZING 04
19444 PINOCCIO 02 03032 YACHT MASTER 05
19444 PINOCCIO 02 03032 YACHT MASTER 05
Reading an Indexed File - Directly.
IDENTIFICATION DIVISION.
IDENTIFICATION
PROGRAM-ID. DIVISION.
ReadingIndexedFile.
PROGRAM-ID.
** Illustrates ReadingIndexedFile.
Illustrates direct
direct read
read on
on an
an indexed
indexed file
file by
by any
any key
key
ENVIRONMENT
ENVIRONMENT DIVISION.
INPUT-OUTPUT DIVISION.
SECTION.
INPUT-OUTPUT
FILE-CONTROL. SECTION.
FILE-CONTROL.
SELECT VideoFile ASSIGN TO
SELECT VideoFile
ORGANIZATION ISASSIGN
INDEXEDTO "VIDEO.DAT"
"VIDEO.DAT"
ORGANIZATION
ACCESS IS INDEXED
ACCESS MODE IS DYNAMIC
RECORD MODE
KEY ISIS DYNAMIC
VideoCode
RECORD
ALTERNATEKEY IS
RECORDVideoCode
KEY
ALTERNATEWITH
RECORD KEY IS
DUPLICATESIS VideoTitle
VideoTitle
FILE WITH DUPLICATES
FILE STATUS
STATUS IS
IS VideoStatus.
VideoStatus.
DATA
DATA DIVISION.
FILE DIVISION.
SECTION.
FILE
FD SECTION.
VideoFile.
FD VideoRecord.
01 VideoFile.
01 02
VideoRecord.
VideoCode PIC 9(5).
02
02 VideoCode
VideoTitle PIC
PIC 9(5).
X(40).
02 SupplierCode
02 VideoTitle PIC 99.
PIC X(40).
02 SupplierCode PIC 99.
WORKING-STORAGE
WORKING-STORAGE SECTION.
SECTION.
01 VideoStatus PIC X(2).
01 88
VideoStatus
RecordFound PIC
VALUE X(2).
88 RecordFound VALUE "00".
"00".
01 RequiredKey PIC 9.
01 88
RequiredKey
VideoCodeKey PIC 9.1.
VALUE
88
88 VideoCodeKey
VideoTitleKey VALUE 2.
VALUE 1.
88 VideoTitleKey VALUE 2.
01 PrnVideoRecord.
01 02
PrnVideoRecord.
PrnVideoCode PIC 9(5).
02
02 PrnVideoCode
PrnVideoTitle PIC
PIC 9(5).
BBBBX(40).
02 PrnSupplierCode
02 PrnVideoTitle PIC BBBB99.
PIC BBBBX(40).
02 PrnSupplierCode PIC BBBB99.
Reading an Indexed File - Directly.
PROCEDURE DIVISION.
PROCEDURE
Begin. DIVISION.
Begin.
OPEN
OPEN INPUT VideoFile.
DISPLAYINPUT VideoFile.
DISPLAY "Chose key
"Chose VideoCode == 1, VideoTitle == 22 -> ""
keyWITH
VideoCode 1, VideoTitle ->
ACCEPT RequiredKey. WITH NONO ADVANCING.
ADVANCING.
ACCEPT RequiredKey.
IF
IF VideoCodeKey
VideoCodeKey
DISPLAY "Enter
"Enter Video
DISPLAYVideoCode
ACCEPT Video Code
Code (5
(5 digits)
digits) ->
-> "" WITH
WITH NONO ADVANCING
ADVANCING
ACCEPT
READ VideoCode
VideoFile
READ
KEY VideoFile
KEY IS
IS VideoCode
INVALID VideoCode
KEY
INVALID
END-READ KEY DISPLAY
DISPLAY "VIDEO
"VIDEO STATUS
STATUS :-
:- ",
", VideoStatus
VideoStatus
END-READ
END-IF
END-IF
IF
IF VideoTitleKey
VideoTitleKey
DISPLAY "Enter
"Enter Video
DISPLAYVideoTitle
ACCEPT Video Title
Title (40
(40 chars)
chars) ->
-> "" WITH
WITH NONO ADVANCING
ADVANCING
ACCEPT
READ VideoTitle
VideoFile
READ
KEY VideoFile
KEY IS
IS VideoTitle
INVALID VideoTitle
KEY
INVALID
END-READ KEY DISPLAY
DISPLAY "VIDEO
"VIDEO STATUS
STATUS :-
:- ",
", VideoStatus
VideoStatus
END-READ
END-IF
END-IF
IF
IF RecordFound
RecordFound
MOVE VideoCode TO PrnVideoCode
MOVE
MOVE VideoCode
VideoTitle TO
TO PrnVideoCode
PrnVideoTitle
MOVE SupplierCode
MOVE VideoTitle TO TOPrnVideoTitle
PrnSupplierCode
MOVE
DISPLAYSupplierCode TO
PrnVideoRecord PrnSupplierCode
DISPLAY
END-IF. PrnVideoRecord
END-IF.
CLOSE VideoFile.
CLOSERUN.
STOP VideoFile.
STOP RUN.
Reading an Indexed File - Directly.

RUN
RUN OF INDEX-EG3.EXE
OFkey
INDEX-EG3.EXE USING
USING VIDEOCODE
VIDEOCODE = 2 -> 1
Chose VideoCode = 1, VideoTitle
Chose
Enter key
Video VideoCode
Code (5 = 1,
digits) VideoTitle
-> 02121 = 2 -> 1
Enter Video
02121 Code (5 digits) -> 02121
DIRTY
DIRTY DANCING 04
02121 DANCING 04
RUN
RUN OF INDEX-EG3.EXE USING VIDEOCODE
Chose OFkey
INDEX-EG3.EXE
VideoCode = USING
1, VIDEOCODE = 2 -> 1
VideoTitle
Chose
Enter key
Video VideoCode
Code (5 = 1,
digits) VideoTitle
-> 05051 = 2 -> 1
Enter
05051 Video Code
OVERBOARD (5 digits) -> 05051 01
05051 OVERBOARD 01
RUN
RUN OF INDEX-EG3.EXE USING VIDEOTITLE
Chose OFkey
INDEX-EG3.EXE
VideoCode = USING
1, VIDEOTITLE= 2 -> 2
VideoTitle
Chose
Enter key
Video VideoCode
Title (40= 1,
chars)VideoTitle
-> = 2 -> 2
OVERBOARD
Enter
05051 Video Title
OVERBOARD (40 chars) -> OVERBOARD 01
05051 OVERBOARD 01
RUN OF INDEX-EG3.EXE USING VIDEOTITLE
RUN
Chose OF INDEX-EG3.EXE
key VideoCode = USING
1, VIDEOTITLE= 2 -> 2
VideoTitle
Chose Video
Enter key VideoCode
Title (40= chars)
1, VideoTitle
-> DIRTY =DANCING
2 -> 2
Enter
02121 Video Title
DIRTY (40 chars) -> DIRTY DANCING
DIRTY DANCING 04
02121 DANCING 04
RUN
RUN OF INDEX-EG3.EXE USING NON
NON EXISTANT VIDEOCODE
Chose OFkey
INDEX-EG3.EXE
VideoCode = USING
1, EXISTANT
VideoTitle = 2 VIDEOCODE
-> 11
Chose
Enter key VideoCode = 1, VideoTitle = 2 ->
Enter Video
Video Code (5
VIDEO STATUS Code
:- 23(5 digits)
digits) ->-> 44444
44444
VIDEO STATUS :- 23
Select and Assign for Indexed
Files

579
Indexed Files - Primary
Key

Index
Buckets 30 60 99 Level 2

10 20 30 40 50 60 70 80 99 Level 1

Level 0
41 43 44 45 46 49

Data Buckets
Indexed Files - Alternate
Key
Index
Buckets H R Z Level 2

C F H L O R T W Z Level 1

Level 0
Mi Nf Ni Nt Oi Ot

Base Buckets

50 51 54 55 56 59
Ii Ef Bi Nt Jt At

Data Buckets
Indexed Files - Alternate
Key
Index
Buckets H R Z Level 2

C F H L O R T W Z Level 1

Level 0
Mi Nf Ni Nt Oi Ot

Base Buckets

Ot 50 51 54 55 56 59 Nf Mi
45 Ii Ef Bi Nt Jt At 65 71

Data Buckets
FDs for Indexed
Files

583
Indexed File Verbs -
OPEN

584
Indexed File Verbs -
READ

585
Rewrite

586
Indexed File Verbs -
DELETE

587
Indexed File Verbs - START

588
The CALL
Verb
CALL
Syntax

590
Example.
CALL "DateValidate"
USING BY CONTENT TempDate
USING BY REFERENCE DateCheckResult.

IDENTIFICATION DIVISION.
PROGRAM-ID DateValidate IS INITIAL.
DATA DIVISION.
WORKING-STORAGE SECTION.
????????????
LINKAGE SECTION.
01 DateParam PIC X(8).
01 DateResult PIC 9.
PROCEDURE DIVISION USING DateParam, DateResult.
Begin.
????????????
????????????
EXIT PROGRAM.
??????.
????????????
CALL
Parameters

CALL "ProgramName" USING P1, P2, P3, P4.

PROCEDURE DIVISION USING P2, P4, P1, P3.

592
CALL
Parameters

CALL "ProgramName" USING P1, P2, P3, P4.

PROCEDURE DIVISION USING P2, P4, P1, P3.

Positions
Positions Correspond
Correspond -- Not
Not Names
Names
593
Parameter Passing Mechanisms

CALL .. BY CALLed
REFERENCE Program
Parameter Passing
Mechanisms
Address of
Data Item
CALL .. BY CALLed
REFERENCE Direction Program
of Data Flow
Parameter Passing
Mechanisms
Address of
Data Item
CALL .. BY CALLed
REFERENCE Direction Program
of Data Flow

CALL .. BY CALLed
CONTENT Program

Copy of
Data Item
Parameter Passing
Mechanisms
Address of
Data Item
CALL .. BY CALLed
REFERENCE Direction Program
of Data Flow

Direction
CALL .. BY of Data Flow CALLed
CONTENT Program

Data Address of
Item Copy of Copy
Data Item
Avoiding “State Memory” - The IS INITIAL
phrase.

$$ SET
SET SOURCEFORMAT"FREE"
SOURCEFORMAT"FREE"
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION. 12
PROGRAM-ID.
PROGRAM-ID. Steadfast
Steadfast IS
IS INITIAL.
INITIAL
INITIAL.
INITIAL
Total = 62
DATA
DATA DIVISION.
DIVISION.
WORKING-STORAGE
WORKING-STORAGE SECTION.
SECTION.
01
01 RunningTotal
RunningTotal PIC
PIC 9(7)
9(7) VALUE
VALUE 50.
50. 5
LINKAGE
LINKAGE SECTION.
SECTION. Total = 55
01
01 ParamValue
ParamValue PIC
PIC 99.
99.
PROCEDURE
PROCEDURE DIVISION
DIVISION USING
USING ParamValue.
ParamValue. 12
Begin.
Begin.
ADD
ADD ParamValue
ParamValue TO
TO RunningTotal.
RunningTotal. Total = 62
DISPLAY
DISPLAY "Total
"Total == ",
", RunningTotal.
RunningTotal.
EXIT
EXIT PROGRAM.
PROGRAM.
Avoiding “State Memory” - The IS INITIAL phrase.

$$ SET
SET SOURCEFORMAT"FREE"
SOURCEFORMAT"FREE"
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID.
PROGRAM-ID. Fickle.
Fickle. 12
DATA
DATA DIVISION.
DIVISION.
WORKING-STORAGE
WORKING-STORAGE SECTION.
SECTION.
Total = 62
01
01 RunningTotal
RunningTotal PIC PIC 9(7)
9(7) VALUE
VALUE 50.
50.
LINKAGE
LINKAGE SECTION.
SECTION. 5
01
01 ParamValue
ParamValue PIC
PIC 99.
99. Total = 67
PROCEDURE
PROCEDURE DIVISION
DIVISION USING
USING ParamValue.
ParamValue.
Begin.
Begin.
ADD
ADD ParamValue
ParamValue TO
TO RunningTotal.
RunningTotal. 12
DISPLAY
DISPLAY "Total
"Total == ",
", RunningTotal.
RunningTotal.
EXIT
EXIT PROGRAM.
PROGRAM.
Total = 79
The CANCEL
command.
CALL "Fickle" USING BY CONTENT IncValue.
CANCEL "Fickle"
CALL "Fickle" USING BY CONTENT IncValue.

$$ SET
SET SOURCEFORMAT"FREE"
SOURCEFORMAT"FREE"
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID. Fickle.
PROGRAM-ID. Fickle.
DATA
DATA DIVISION.
DIVISION.
12
WORKING-STORAGE
WORKING-STORAGE SECTION.
SECTION.
01
01 RunningTotal PIC
RunningTotal PIC 9(7)
9(7) VALUE
VALUE 50.
50. Total = 62
LINKAGE
LINKAGE SECTION.
SECTION.
01 ParamValue PIC
PIC 99.
01 ParamValue 99. 12
PROCEDURE
PROCEDURE DIVISION
DIVISION USING
USING ParamValue.
ParamValue.
Begin.
Begin. Total = 62
ADD
ADD ParamValue
ParamValue TO
TO RunningTotal.
RunningTotal.
DISPLAY
DISPLAY "Total = ", RunningTotal.
"Total = ", RunningTotal.
EXIT PROGRAM.
EXIT PROGRAM.
Programs
$$ SET
SET SOURCEFORMAT"FREE"
SOURCEFORMAT"FREE"
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID.
PROGRAM-ID. MainProgram.
MainProgram.
?? ?? ?? ?? ?? ?? ?? ?? ??
01
01 TableItem
TableItem IS IS GLOBAL.
GLOBAL
GLOBAL.
GLOBAL
PROCEDURE
PROCEDURE DIVISION.
DIVISION.
?? ?? ?? ?? ?? ?? ?? ?? ??
CALL
CALL PutToTable
PutToTable USING USING BY
BY CONTENT
CONTENT DataItem
DataItem
?? ?? ?? ?? ?? ?? ?? ?? ??
CALL
CALL ReportFromTable.
ReportFromTable.
EXIT PROGRAM.
EXIT PROGRAM.
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID. PutToTable.
PROGRAM-ID. PutToTable.
?? ?? ?? ?? ?? ?? ?? ?? ??
END-PROGRAM
END-PROGRAM PutToTable.
PutToTable.
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID.
PROGRAM-ID. ReportFromTable.
ReportFromTable.
?? ?? ?? ?? ?? ?? ?? ?? ??
END-PROGRAM
END-PROGRAM ReportFromTable.
ReportFromTable.
END-PROGRAM MainProgram.
END-PROGRAM MainProgram.
Programs
$$ SET
SET SOURCEFORMAT"FREE"
SOURCEFORMAT"FREE"
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID.
PROGRAM-ID. MainProgram.
MainProgram.
?? ?? ?? ?? ?? ?? ?? ?? ??
01
01 TableItem
TableItem IS IS GLOBAL.
GLOBAL
GLOBAL.
GLOBAL
PROCEDURE
PROCEDURE DIVISION.
DIVISION.
?? ?? ?? ?? ?? ?? ?? ?? ??
CALL
CALL PutToTable
PutToTable USING USING BY
BY CONTENT
CONTENT DataItem
DataItem
?? ?? ?? ?? ?? ?? ?? ?? ??
CALL
CALL ReportFromTable.
ReportFromTable.
EXIT PROGRAM.
EXIT PROGRAM.
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID. PutToTable.
PROGRAM-ID. PutToTable.
?? ?? ?? ?? ?? ?? ?? ?? ??
END-PROGRAM
END-PROGRAM PutToTable.
PutToTable.
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID.
PROGRAM-ID. ReportFromTable.
ReportFromTable.
?? ?? ?? ?? ?? ?? ?? ?? ??
END-PROGRAM
END-PROGRAM ReportFromTable.
ReportFromTable.
END-PROGRAM MainProgram.
END-PROGRAM MainProgram.
Programs
$$ SET
SET SOURCEFORMAT"FREE"
SOURCEFORMAT"FREE"
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID.
PROGRAM-ID. MainProgram.
MainProgram.
?? ?? ?? ?? ?? ?? ?? ?? ??
01
01 TableItem
TableItem IS IS GLOBAL.
GLOBAL
GLOBAL.
GLOBAL
PROCEDURE
PROCEDURE DIVISION.
DIVISION.
?? ?? ?? ?? ?? ?? ?? ?? ??
CALL
CALL PutToTable
PutToTable USING USING BY
BY CONTENT
CONTENT DataItem
DataItem
?? ?? ?? ?? ?? ?? ?? ?? ??
CALL
CALL ReportFromTable.
ReportFromTable.
EXIT PROGRAM.
EXIT PROGRAM.
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID. PutToTable.
PROGRAM-ID. PutToTable.
?? ?? ?? ?? ?? ?? ?? ?? ??
END-PROGRAM
END-PROGRAM PutToTable.
PutToTable.
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID.
PROGRAM-ID. ReportFromTable.
ReportFromTable.
?? ?? ?? ?? ?? ?? ?? ?? ??
END-PROGRAM
END-PROGRAM ReportFromTable.
ReportFromTable.
END-PROGRAM MainProgram.
END-PROGRAM MainProgram.
The COMMON PROGRAM Phrase
$$ SET
SET SOURCEFORMAT"FREE"
SOURCEFORMAT"FREE"
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID. MainProgram.
PROGRAM-ID. MainProgram.
?? ?? ?? ?? ?? ?? ?? ?? ??
01
01 TableItem
TableItem IS IS GLOBAL.
GLOBAL
GLOBAL.
GLOBAL
PROCEDURE DIVISION.
PROCEDURE DIVISION.
?? ?? ?? ?? ?? ?? ?? ?? ??
EXIT
EXIT PROGRAM.
PROGRAM.
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID. PutToTable.
PROGRAM-ID. PutToTable.
?? ?? ?? ?? ?? ?? ?? ?? ??
CALL
CALL ReportFromTable.
ReportFromTable.
?? ?? ?? ?? ?? ?? ?? ?? ??
END-PROGRAM
END-PROGRAM PutToTable.
PutToTable.
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID.
PROGRAM-ID. ReportFromTable IS
ReportFromTable IS COMMON
COMMON PROGRAM.
PROGRAM.
?? ?? ?? ?? ?? ?? ?? ?? ??
CALL
CALL PutToTable
PutToTable USING USING ????
????
?? ?? ?? ?? ?? ?? ?? ?? ??
END-PROGRAM
END-PROGRAM ReportFromTable.
ReportFromTable.
END-PROGRAM MainProgram.
END-PROGRAM MainProgram.
Phrase
$$ SET
SET SOURCEFORMAT"FREE"
SOURCEFORMAT"FREE"
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID. MainProgram.
PROGRAM-ID. MainProgram.
?? ?? ?? ?? ?? ?? ?? ?? ??
01
01 TableItem
TableItem IS IS GLOBAL.
GLOBAL
GLOBAL.
GLOBAL
PROCEDURE DIVISION.
PROCEDURE DIVISION.
?? ?? ?? ?? ?? ?? ?? ?? ??
EXIT
EXIT PROGRAM.
PROGRAM.
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID. PutToTable.
PROGRAM-ID. PutToTable.
?? ?? ?? ?? ?? ?? ?? ?? ??
CALL
CALL ReportFromTable.
ReportFromTable.
?? ?? ?? ?? ?? ?? ?? ?? ??
END-PROGRAM PutToTable. YES
END-PROGRAM PutToTable.
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID.
PROGRAM-ID. ReportFromTable IS
ReportFromTable IS COMMON
COMMON PROGRAM.
PROGRAM.
?? ?? ?? ?? ?? ?? ?? ?? ??
CALL
CALL PutToTable
PutToTable USING USING ????
????
?? ?? ?? ?? ?? ?? ?? ?? ??
END-PROGRAM
END-PROGRAM ReportFromTable.
ReportFromTable.
END-PROGRAM MainProgram.
END-PROGRAM MainProgram.
Phrase
$$ SET
SET SOURCEFORMAT"FREE"
SOURCEFORMAT"FREE"
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID. MainProgram.
PROGRAM-ID. MainProgram.
?? ?? ?? ?? ?? ?? ?? ?? ??
01
01 TableItem
TableItem IS IS GLOBAL.
GLOBAL
GLOBAL.
GLOBAL
PROCEDURE DIVISION.
PROCEDURE DIVISION.
?? ?? ?? ?? ?? ?? ?? ?? ??
EXIT
EXIT PROGRAM.
PROGRAM.
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID. PutToTable.
PROGRAM-ID. PutToTable.
?? ?? ?? ?? ?? ?? ?? ?? ?? NO
CALL
CALL ReportFromTable.
ReportFromTable.
?? ?? ?? ?? ?? ?? ?? ?? ??
END-PROGRAM PutToTable. YES
END-PROGRAM PutToTable.
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID.
PROGRAM-ID. ReportFromTable IS
ReportFromTable IS COMMON
COMMON PROGRAM.
PROGRAM.
?? ?? ?? ?? ?? ?? ?? ?? ??
CALL
CALL PutToTable
PutToTable USING USING ????
????
?? ?? ?? ?? ?? ?? ?? ?? ??
END-PROGRAM
END-PROGRAM ReportFromTable.
ReportFromTable.
END-PROGRAM MainProgram.
END-PROGRAM MainProgram.
Types?
$$ SET
SET SOURCEFORMAT"FREE"
SOURCEFORMAT"FREE"
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID. Stack.
PROGRAM-ID. Stack.
DATA
DATA DIVISION.
DIVISION.
Main
WORKING-STORAGE
WORKING-STORAGE SECTION.
SECTION.
01 StackHolder
01 02
StackHolder IS
IS GLOBAL.
GLOBAL.
02 StackItem OCCURS 20
StackItem OCCURS 20 TIMES
TIMES PIC
PIC X(10).
X(10).
PROCEDURE
PROCEDURE DIVISION
DIVISION USING
USING ????.
????.
Begin.
Begin. Stack
EVALUATE
EVALUATE TRUE
TRUE
WHEN
WHEN PushStack
PushStack CALL
CALL "Push"
"Push" USING
USING ???
???
WHEN PopStack CALL "Pop" USING
WHEN PopStack CALL "Pop" USING ??? ???
END-EVALUATE.
END-EVALUATE.
EXIT
EXIT PROGRAM.
PROGRAM.
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID.
PROGRAM-ID. Push.
Push. Push
?? ?? ?? ?? ?? ?? ?? ?? ??
END-PROGRAM
END-PROGRAM Push.Push.
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID. Pop. Pop
PROGRAM-ID.
?? ?? ?? ?? ?Pop.
? ?? ?? ?? ??
END-PROGRAM
END-PROGRAM Pop.
Pop.
END-PROGRAM Stack.
END-PROGRAM Stack.
Types?
$$ SET
SET SOURCEFORMAT"FREE"
SOURCEFORMAT"FREE"
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID. Stack.
PROGRAM-ID. Stack.
DATA
DATA DIVISION.
DIVISION.
Main
WORKING-STORAGE
WORKING-STORAGE SECTION.
SECTION.
01 StackHolder
01 02
StackHolder IS
IS GLOBAL.
GLOBAL.
02 StackItem OCCURS 20
StackItem OCCURS 20 TIMES
TIMES PIC
PIC X(10).
X(10).
PROCEDURE
PROCEDURE DIVISION
DIVISION USING
USING ????.
????.
Begin.
Begin. Stack
EVALUATE
EVALUATE TRUE
TRUE
WHEN
WHEN PushStack
PushStack CALL
CALL "Push"
"Push" USING
USING ???
???
WHEN PopStack CALL "Pop" USING
WHEN PopStack CALL "Pop" USING ??? ???
END-EVALUATE.
END-EVALUATE.
EXIT
EXIT PROGRAM.
PROGRAM.
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID.
PROGRAM-ID. Push.
Push. Push
?? ?? ?? ?? ?? ?? ?? ?? ??
END-PROGRAM
END-PROGRAM Push.Push.
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID. Pop. Pop
PROGRAM-ID.
?? ?? ?? ?? ?Pop.
? ?? ?? ?? ??
END-PROGRAM
END-PROGRAM Pop.
Pop.
END-PROGRAM Stack.
END-PROGRAM Stack.
Types?
$$ SET
SET SOURCEFORMAT"FREE"
SOURCEFORMAT"FREE"
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID. Stack.
PROGRAM-ID. Stack.
DATA
DATA DIVISION.
DIVISION.
Main
WORKING-STORAGE
WORKING-STORAGE SECTION.
SECTION.
01 StackHolder
01 02
StackHolder IS
IS GLOBAL.
GLOBAL.
02 StackItem OCCURS 20
StackItem OCCURS 20 TIMES
TIMES PIC
PIC X(10).
X(10).
PROCEDURE
PROCEDURE DIVISION
DIVISION USING
USING ????.
????.
Begin.
Begin. Stack
EVALUATE
EVALUATE TRUE
TRUE
WHEN
WHEN PushStack
PushStack CALL
CALL "Push"
"Push" USING
USING ???
???
WHEN PopStack CALL "Pop" USING
WHEN PopStack CALL "Pop" USING ??? ???
END-EVALUATE.
END-EVALUATE.
EXIT
EXIT PROGRAM.
PROGRAM.
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID.
PROGRAM-ID. Push.
Push. Push
?? ?? ?? ?? ?? ?? ?? ?? ??
END-PROGRAM
END-PROGRAM Push.Push.
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID. Pop. Pop
PROGRAM-ID.
?? ?? ?? ?? ?Pop.
? ?? ?? ?? ??
END-PROGRAM
END-PROGRAM Pop.
Pop.
END-PROGRAM Stack.
END-PROGRAM Stack.
The IS EXTERNAL
phrase.

FD CommonFileArea IS EXTERNAL.

WORKING-STORAGE SECTION.
01 SharedRec IS EXTERNAL.
02 PartA PIC X(4).
02 PartB PIC 9(5).

610
The IS EXTERNAL
phrase.
ProgramA

ProgramB ProgramC ProgramD


01 SharedRec etc 01 SharedRec etc
Mike12345

SharedRec

WORKING-STORAGE SECTION.
01 SharedRec IS EXTERNAL.
02 PartA PIC X(4).
02 PartB PIC 9(5).
The IS EXTERNAL
phrase.
ProgramA

ProgramB ProgramC ProgramD


01 SharedRec etc 01 SharedRec etc
Mike12345

SharedRec
PUT
Mike12345

WORKING-STORAGE SECTION.
01 SharedRec IS EXTERNAL.
02 PartA PIC X(4).
02 PartB PIC 9(5).
The IS EXTERNAL
phrase.
ProgramA

ProgramB ProgramC ProgramD


01 SharedRec etc 01 SharedRec etc
Mike12345 Mike12345

SharedRec
PUT GET
Mike12345

WORKING-STORAGE SECTION.
01 SharedRec IS EXTERNAL.
02 PartA PIC X(4).
02 PartB PIC 9(5).
COPY
Verb
The COPY Verb

 The COPY verb is very different from other COBOL verbs.


 While other COBOL statements are executed at run time the COPY is
executed at compile time.
 The COPY statement allows programs to include frequently used source
code text from a copy file or copy library.
 The COPY can include source code text without change or it can change
the text as it is copied into the client program.

615
The COPY verb2

 The COPY verb is generally used when creating large software systems.

 It allows item descriptions to be kept and updated centrally in a copy Library, often
under the control of a copy librarian.

 A copy library contains COBOL elements that can be reference using a textname.

 Each client program which wants to use items described in the copy library uses the
COPY verb to include the descriptions it requires.

 When more than one copy library is used the OF or IN qualifier is used to indicate
which library is being referenced.

616
Why use the COPY verb?

 Using the COPY verb makes implementation simpler by reducing the amount of
coding required and eliminating transcription errors.

 Using the COPY verb makes some maintenance tasks easier and safer.
The text in the copy library is updated and the affected programs are recompiled.

 Using copy libraries makes it more difficult for programmers to make ad hoc
changes to file and record formats.
Changes generally have to be approved by the COPY librarian.

617
COPY format
TextName  OF LibraryName 
COPY      
ExternalFileNameLiteral  IN
   LibraryNameLiteral 

 == PseudoText1 == == PseudoText2 == 


   Identifier2  
REPLACING   Identifier1    
  BY  
 Literal1   Literal2  

 Word1  Word2  

Example COPY statements.

COPY "CopyFile2.CBL" REPLACING XYZ BY 120.

ExternalFileNameLiteral
COPY Copyfile3 IN "EXLIB".

TextName
COPY "CopyFile3.CBL" IN "EXLIB".
LibraryNameLiteral

ExternalFileNameLiteral
LibraryNameLiteral 618
How the COPY works
 If the REPLACING phrase is not used then the compiler simply copies the
text into the client program without change.

 If the COPY does use the REPLACING phrase then the text is copied and
each properly matched occurrence of Pseudo-Text-1, Identifier-1, Literal-1
and Word-1 in the library text is replaced by the corresponding Pseudo-
Text-2, Identifier-2, Literal-2 or Word-2 in the REPLACING phrase.

 Pseudo-Text is any COBOL text encloded in double equal signs (e.g.


==ADD 1==).

It allows us to replace a series of words or characters as opposed to an


individual identifier, literal or word.

619
How the REPLACING works

 The REPLACING phrase tries to match text-words in the


library text with text-words before the BY in the
REPLACING phase.
If a match is achived then as text is copied from the library it
is replaced by the matching REPLACING phrase text.
 For purposes of matching, each occurrence of a
separator comma
semicolon
space
in pseudo-text-1 or in the library text is considered to be a
single space.
 Each sequence of one or more space separators is considered
to be a single space.
 Comment lines in either the library or REPLACING phrase
text are treated as a single space. 620
Text-Words

 The matching procedure in the REPLACING phrase operates on


text-words.

 A text word is ;
 A literal including opening and closing quotes
 A seperator other than;
A Space
A Pseudo-Text delimiter
A Comma
 Opening and closing parentheses
 Any other sequence of contiguous characters, bounded by separators.

621
Text-Word Examples

 MOVE
1 Text Word

 MOVE Total TO Print-Total


4 Text Words - MOVE Total TO Print-Total

 MOVE Total TO Print-Total.


5 Text Words - MOVE Total TO Print-Total .

 PIC S9(4)V9(6)
9 Text words - PIC S9 ( 4 ) V9 ( 6 )

 “PIC S9(4)V9(6)”
1 Text word - “PIC S9(4)V9(6)”

622
COPY Example 1
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID. COPYEG1.
PROGRAM-ID. COPYEG1.
AUTHOR.
AUTHOR. Michael
Michael Coughlan.
Coughlan.
ENVIRONMENT
ENVIRONMENT DIVISION.
DIVISION.
FILE-CONTROL. 0101 StudentRec.
StudentRec.
FILE-CONTROL.
SELECT
SELECT StudentFile
StudentFile ASSIGN
ASSIGN TO
TO "STUDENTS.DAT"
"STUDENTS.DAT"
ORGANIZATION IS LINE 88
88 EndOfSF
SEQUENTIAL.
EndOfSF VALUE
VALUE HIGH-VALUES.
HIGH-VALUES.
ORGANIZATION IS LINE SEQUENTIAL.
DATA
DATA DIVISION.
DIVISION. 02
02 StudentNumber
StudentNumber PIC
PIC 9(7).
9(7).
FILE SECTION.
FILE SECTION.
FD
FD StudentFile.
StudentFile. 02
02 StudentName
StudentName PIC
PIC X(60).
X(60).
COPY
COPY COPYFILE1.
COPYFILE1.
02
02 CourseCode
CourseCode PIC
PIC X(4).
X(4).
PROCEDURE
PROCEDURE DIVISION. 02
DIVISION. 02 FeesOwed
FeesOwed PIC
PIC 9(4).
9(4).
BeginProg.
BeginProg.
OPEN
OPEN INPUT
INPUT StudentFile
StudentFile 02
READ StudentFile 02 AmountPaid
AmountPaid PIC
PIC 9(4)V99.
9(4)V99.
READ StudentFile
AT
AT END
END SET
SET EndOfSF
EndOfSF TO
TO TRUE
TRUE
END-READ
END-READ
PERFORM
PERFORM UNTIL
UNTIL EndOfSF
EndOfSF
DISPLAY
DISPLAY StudentNumber SPACE
StudentNumber SPACE StudentName
StudentName SPACE
SPACE
CourseCode SPACE FeesOwed SPACE AmountPaid
CourseCode SPACE FeesOwed SPACE AmountPaid
READ StudentFile
READ StudentFile
AT
AT END
END SET
SET EndOfSF
EndOfSF TO
TO TRUE
TRUE
END-READ
END-READ
END-PERFORM
END-PERFORM 623
STOP RUN.
STOP RUN.
COPY Example 2
Copyfile2.cbl

02
02 StudName
StudName PIC
PIC X(20)
X(20) OCCURS
OCCURS XYZ
XYZ TIMES.
TIMES
TIMES.
TIMES

01 NameTable2.
COPY "CopyFile2.CBL" REPLACING XYZ BY 120.

01 NameTable2.
02 StudName PIC X(20) OCCURS 120
TIMES.

624
COPY Example 3
Copyfile3.cbl

02
02 CustOrder
CustOrder PIC
PIC 9(R).
9(R).

01 CopyData.
COPY Copyfile3 REPLACING ==R== BY ==4==.

01 CopyData.
02 CustOrder PIC 9(4).

625
COPY Example 4
Copyfile4.cbl

02
02 CustOrder2
CustOrder2 PIC
PIC 9(6)V99.
9(6)V99.

01 CopyData.

COPY CopyFile4 REPLACING ==V99== BY ====.

01 CopyData.
02 CustOrder2 PIC 9(6).

626
COPY Example 5
Copyfile5.cbl

02
02 CustKey
CustKey PIC
PIC X(3)
X(3) VALUE
VALUE "KEY".
"KEY".

01 CopyData.

COPY CopyFile5 REPLACING "KEY" BY "ABC".

01 CopyData.
02 CustKey PIC X(3) VALUE "ABC".

627
COPY Example 6
Copyfile5.cbl

02
02 CustKey
CustKey PIC
PIC X(3)
X(3) VALUE
VALUE "KEY".
"KEY".

01 CopyData.
COPY CopyFile5 REPLACING "CustKey" BY "Cust".

01 CopyData.
02 CustKey PIC X(3) VALUE "KEY".
No Replacement

628
COPY Example 7
Copyfile5.cbl

02
02 CustKey
CustKey PIC
PIC X(3)
X(3) VALUE
VALUE "KEY".
"KEY".

01 CopyData.

COPY CopyFile5 REPLACING "KEY" BY =="ABC".


02 CustNum PIC 9(8)==.
01 CopyData.
02 CustKey PIC X(3) VALUE "ABC".
02 CustNum PIC 9(8).

629
COPY Example 8
Copyfile5.cbl

02
02 CustKey
CustKey PIC
PIC X(3)
X(3) VALUE
VALUE "KEY".
"KEY".

* the ( is a textword replaced by @


COPY copyfile5 REPLACING ( BY @.
* the 3 between ( and ) is a textword replaced by the textword "three"
COPY copyfile5 REPLACING 3 BY three.
* the ) is a textword replaced by &
COPY copyfile5 REPLACING ) BY &.

02 CustKey PIC X@3) VALUE "KEY".


02 CustKey PIC X(three) VALUE "KEY".
02 CustKey PIC X(3& VALUE "KEY".

630
Copyfile5.cbl
COPY Example 9
02
02 CustKey
CustKey PIC
PIC X(3)
X(3) VALUE
VALUE "KEY".
"KEY".

* the X before (3) is a textword replaced by pseudotext "Replace the X"


COPY copyfile5 REPLACING X
BY ==Replace the X==.
* the pseudotext X(3) is replaced by X(19)
COPY copyfile5 REPLACING ==X(3)==
BY ==X(19)==.
* the series of textwords X ( 3 ) is replaced by the series X ( 19 )
COPY copyfile5 REPLACING X(3) BY X(19).

02 CustKey PIC Replace the X(3) VALUE KEY".


02 CustKey PIC X(19) VALUE "KEY".
02 CustKey PIC X(19) VALUE "KEY".
631
Copyfile5.cbl
COPY Example 10
02
02 CustKey
CustKey PIC
PIC X(3)
X(3) VALUE
VALUE "KEY".
"KEY".

* the textword PIC is replaced by the pseudotext Pic is Replaced


COPY copyfile5 REPLACING PIC
BY ==Pic is Replaced==.
* The P in PIC is not a textword by itself and so is not replaced
COPY copyfile5 REPLACING P BY
==But P in PIC not replaced==.

02 CustKey Pic is Replaced X(3) VALUE "KEY".


02 CustKey PIC X(3) VALUE "KEY".
No Replacement

632
Debug
ging
Menus
PROCO 1 - Menu ALT key PROCO 2 - Alt Menu
PROCO 1 - Menu PROCO 2 - Alt Menu
F1=help F2=edit F3=check F4=animate F1=help F2=screens F7=link F10=CoWriter
F1=help F2=edit F3=check F4=animate F1=help F2=screens F7=link F10=CoWriter
F5=compile F6=run F7=library F8=build
F5=compile F6=run F7=library F8=build
F10=directory CTRL key PROCO 3 - Ctrl Menu
F10=directory PROCO 3 - Ctrl Menu
F1=help F3=update-menu F4=UseUpdatedMenu
F1=help F3=update-menu F4=UseUpdatedMenu
F5=batch-files F7=OS-command F8=config
F5=batch-files F7=OS-command F8=config
F10=user-menu
F10=user-menu

EDIT 1 -Menu ALT key EDIT 2 - Alt Menu


EDIT 1 -Menu EDIT 2 - Alt Menu
F1=help F2=COBOL F3=InsertLine F1=help F2=library F3=load-file F4=save-
F1=help F2=COBOL F3=InsertLine F1=help F2=library F3=load-file F4=save-
F4=DeleteLine F5=RepeatLine F6=RestoreLine file F5=split-line F6=join-line F7=print
F4=DeleteLine F5=RepeatLine F6=RestoreLine file F5=split-line F6=join-line F7=print
F7=RetypeChar F8=RestoreChar F8=calculate F9=untype-word-left
F7=RetypeChar F8=RestoreChar F8=calculate F9=untype-word-left
F9=WordLeft F10=WordRight F10=DeleteWord
F9=WordLeft F10=WordRight F10=DeleteWord
CTRL key EDIT 3 - Ctrl Menu
EDIT 3 - Ctrl Menu
F1=help F2=find F3=block F4=clear
F1=help F2=find F3=block F4=clear
F5=margins F6=draw/forms F7=tags
COBOL menu F5=margins F6=draw/forms F7=tags
COBOL menu F8=WordWrap F9=window F10=scroll
F1=help F2=check/animate F3=cmd-file F8=WordWrap
<-/-> (move in window) F9=window F10=scroll
Home/End (of text) PgUp/PgDn
F1=help F2=check/animate F3=cmd-file <-/-> (move in window) Home/End (of text) PgUp/PgDn
F7=locate-previous F8=locate-next
F7=locate-previous F8=locate-next
F9=locate-current
F9=locate-current
Animate-Menu
Animate-Menu
F1=help F2=view F3=align F4=exchange
F1=help F2=view F3=align F4=exchange
Checker Menu F5=where F6=look-up F9/F10=word-</>
Checker Menu F5=where
Escape F6=look-up
Animate Step Wch Go ZoomF9/F10=word-</>
nx-If Prfm Rst Brk Env
F1=help F2=check/anim F3=pause Escape AnimateQury
Step Find
Wch Locate
Go Zoom
Txtnx-If
Do Prfm Rst Brk Env
F1=help F2=check/anim F3=pause Qury Find Locate Txt Do
F4=list F6=lang F7=ref F9/F10=directives
F4=list F6=lang F7=ref F9/F10=directives
PROCO
Menus
Animate-Menu
F1=help F2=view F3=align F4=exchange F5=where F6=look-up
F9/F10=word-</> Escape
Animate Step Wch Go Zoom nx-If Prfm Rst Brk Env Qury Find Locate Txt
Do

You might also like