You are on page 1of 515

COBOL

Course Details
No.
Name

COBOL

Course Details
Pre-Requisite

None

Target

COBOL

Audience
Mode of
Training
Evaluation
Criteria

Class Room Session

Course Details
Module
No.

Topic

Time(hrs)

1.

Introduction to COBOL

2.

COBOL Basics 1

3.

COBOL Basics 2

4.

Arithmetic and Edited Pictures

5.

The USAGE clause

6.

Conditions

7.

COPY Verb

8.

The PERFORM

9.

Tables and
PERFORM..VARYING

10.

Advanced Tables

Course Details
Module
No.

Topic

Time(hrs)

11.

Searching Tables

12.

Introduction to Sequential Files 4

13.

Processing Sequential Files

14.

Advanced Sequential Files 1

15.

Introduction to Direct Access


Files

16.

Relative Files

17.

Indexed Files

18.

String

19.

Unstring

20

Sort

Introduction to
COBOL

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 idiosyncracies which programmers may find irritating.

COBOL idiosyncracies

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.

The COBOL Metalanguage - Syntax 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 programmers discretion.

Structure of COBOL programs.

Program
Program
Divisions
Section(s)
Paragraph(s)
Sentence(s)
Statement(s)

The Four Divisions.


DIVISIONS are used to identify the principal components
of the program text. There are four DIVISIONS in all.
IDENTIFICATION

DIVISION.

ENVIRONMENT DIVISION.

DATA DIVISION.

PROCEDURE DIVISION.

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.

COBOL Program Text Structure


IDENTIFICATION DIVISION.
Program Details
DATA DIVISION.
Data Descriptions
PROCEDURE DIVISION.
Algorithm Description

NNOTE
OTE

The
Thekeyword
keyword
DIVISION
DIVISIONand
andaa
full-stop
full-stopisisused
usedinin
every
everycase.
case.

IDENTIFICATION DIVISION.

The purpose of the IDENTIFICATION DIVISION is to


provide information about the program to the
programmer and to the compiler.

Most of the entries in the IDENTIFICATION


DIVISION are directed at the programmer and are
treated by the compiler as comments.

An exception to this is the PROGRAM-ID clause.


Every COBOL program must have a PROGRAM-ID.
It is used to enable the compiler to identify the
program.

There are several other informational paragraphs in


the IDENTIFICATION DIVISION but we will ignore
them for the moment.

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.

The IDENTIFICATION DIVISION Syntax.

The IDENTIFICATION DIVISION has the following structure


IDENTIFICATION DIVISION.
PROGRAM-ID. NameOfProgram.
[AUTHOR. YourName.]

IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID.
PROGRAM-ID. FirstProgram.
FirstProgram.
AUTHOR.
AUTHOR. Hari.
Hari.

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.

The DATA DIVISION.

The DATA DIVISION is used to describe most of


the data that a program processes.

The DATA DIVISION is divided into four main


sections;
FILE SECTION.
WORKING-STORAGE SECTION.
LINKAGE SECTION.
REPORT SECTION

The DATA DIVISION.

The FILE SECTION is used to describe most of


the data that is sent to, or comes from, the
computers peripherals.

The WORKING-STORAGE SECTION is used to


describe the general variables used in the
program.

The LINKAGE SECTION is used to describe the


variables passed between programs.

The REPORT SECTION is used to describe the


variables used in the reports (generally not
used).

DATA DIVISION Syntax

The DATA DIVISION has the following structure


DATA DIVISION.
FILE SECTION.

File Section entries.


WORKING-STORAGE SECTION.

WS entries.
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID.
PROGRAM-ID. FirstProgram.
FirstProgram.
AUTHOR.
Hari.
AUTHOR. Hari.
DATA
DATA DIVISION.
DIVISION.
WORKING-STORAGE
WORKING-STORAGE SECTION.
SECTION.
01
PIC
01 Num1
Num1
PIC 99 VALUE
VALUE ZEROS.
ZEROS.
01
Num2
PIC
9
VALUE
ZEROS.
01 Num2
PIC 9 VALUE ZEROS.
01
PIC
01 Result
Result
PIC 99
99 VALUE
VALUE ZEROS.
ZEROS.

The PROCEDURE 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.

Sections

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


paragraphs.

A section begins with the section name and ends


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

A section name consists of a name devised by the


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

Paragraphs

Each section consists of one or more paragraphs.

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


more sentences.

A paragraph begins with the paragraph name and


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

The paragraph name consists of a name devised by


the programmer or defined by the language
followed by a full stop.
PrintFinalTotals.
PROGRAM-ID.

Sentences and Statements.

A paragraph consists of one or more sentences.

A sentence consists of one or more statements and is


terminated by a full stop.
MOVE .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

A Full COBOL program.


IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID.
PROGRAM-ID. FirstProgram.
FirstProgram.
AUTHOR.
AUTHOR. Hari.
Hari.
DATA
DATA DIVISION.
DIVISION.
WORKING-STORAGE
WORKING-STORAGE SECTION.
SECTION.
01
PIC
VALUE
01 Num1
Num1
PIC 99
99
VALUE 10.
10.
01
PIC
VALUE
01 Num2
Num2
PIC 99
99
VALUE 30.
30.
01
Result
PIC
9(03)
VALUE
01 Result
PIC 9(03) VALUE
ZEROS.
ZEROS.
PROCEDURE
PROCEDURE DIVISION.
DIVISION.
CalculateResult.
CalculateResult.
MULTIPLY
MULTIPLY Num1
Num1 BY
BY Num2
Num2 GIVING
GIVING Result.
Result.
DISPLAY
DISPLAY "Result
"Result is
is == ",
", Result.
Result.
GOBACK.
GOBACK.

The minimum COBOL program.

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

COBOL Basics 1

Rules for Coding A Cobol Program


Columns 1- 6

Reserved for line numbers automatically assigned


by the compiler

Columns 7

Used for giving comment sentences in a program


An * put in this column makes the complier ignore
the sentence

Column 8-11

Referred to as Area A. Where all 01 level entries,


paragraph-names, Section headers and Division names
must start

Column 12-72

Referred to as Area B. Where all sentences must start

Column 73 on

Is ignored by the compiler

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.

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. IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID. ProgramFragment.
PROGRAM-ID. ProgramFragment.
** This
This is
is aa comment.
comment. It
It starts
starts
with an asterisk in column 7
with an asterisk in column 7

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, Customer10Rec

All data-names should describe the data they contain.

All paragraph and section names should describe the function


of the paragraph or section.

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.

Data-Names / Variables

A variable is a named location in memory into which


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

A data-name or identifier is the name used to


identify the area of memory reserved for the
variable.

Variables must be described in terms of their type


and size.

Every variable used in a COBOL program must have


a description in the DATA DIVISION.

Using Variables
01 StudentName

PIC X(6) VALUE SPACES.

MOVE "JOHN" TO StudentName.


DISPLAY "My name is ", StudentName.

StudentName

Using Variables
01 StudentName

PIC X(6) VALUE SPACES.

MOVE "JOHN" TO StudentName.


DISPLAY "My name is ", StudentName.

StudentName

O H

Using Variables
01 StudentName

PIC X(6) VALUE SPACES.

MOVE "JOHN" TO StudentName.


DISPLAY "My name is ", StudentName.

StudentName

O H

My name is JOHN

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!

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.

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.

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.

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

The

limit on string values is usually systemdependent.

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

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

000
000

.18
.18

StudentName
StudentName

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

Figurative Constants

COBOL provides its own, special constants called


Figurative Constants.
SPACE
SPACEor
orSPACES
SPACES
ZERO
ZEROor
orZEROS
ZEROSor
orZEROS
ZEROS

==

==

00

QUOTE
QUOTEor
orQUOTES
QUOTES
HIGH-VALUE
HIGH-VALUEor
orHIGH-VALUES
HIGH-VALUES

==

""

==

Max
MaxValue
Value

LOW-VALUE
LOW-VALUEor
orLOW-VALUES
LOW-VALUES
ALL
ALLliteral
literal

==

Min
MinValue
Value

==

Fill
FillWith
WithLiteral
Literal

Figurative Constants - Examples


01
01 GrossPay
GrossPay
ZERO
MOVE
MOVE ZEROS
ZEROES

PIC
PIC 9(5)V99
9(5)V99 VALUE
VALUE 13.5.
13.5.
TO
TO GrossPay.
GrossPay.

GrossPay

0 0 0 1 3 5 0

01
01 StudentName
StudentName

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

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

M I K E

Figurative Constants - Examples


01
01 GrossPay
GrossPay
ZERO
MOVE
MOVE ZEROS
ZEROES

PIC
PIC 9(5)V99
9(5)V99 VALUE
VALUE 13.5.
13.5.
TO
TO GrossPay.
GrossPay.

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

- - - - - - - - - -

COBOL Basics
2

Group Items/Records
WORKING-STORAGE
WORKING-STORAGE SECTION.
SECTION.
01
StudentDetails
PIC
01 StudentDetails
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

Group Items/Records
WORKING-STORAGE
WORKING-STORAGE SECTION.
SECTION.
01
StudentDetails.
01 StudentDetails.
02
PIC
02 StudentName
StudentName
PIC X(10).
X(10).
02
StudentId
PIC
9(7).
02 StudentId
PIC 9(7).
02
PIC
02 CourseCode
CourseCode
PIC X(4).
X(4).
02
Grant
PIC
9(4).
02 Grant
PIC 9(4).
02
Gender
PIC
02 Gender
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

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

StudentId
Initials

CourseCode Grant

Gender

LEVEL Numbers express DATA hierarchy

In COBOL, level numbers are used to decompose a


structure into its 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.

LEVEL Numbers express DATA hierarchy

In COBOL, level numbers are used to decompose a


structure into its 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 StudentDetails.
StudentDetails.
02
02 StudentName.
StudentName.
03
03 Surname
Surname
03
Initials
03
Initials
02
StudentId
02 CourseCode
StudentId
02
02 Grant
CourseCode
02
02 Gender
Grant
02
02 Gender

PIC
PIC X(8).
X(8).
PIC
XX.
PIC
XX.
PIC
9(7).
PIC X(4).
9(7).
PIC
PIC 9(4).
X(4).
PIC
PIC X.
9(4).
PIC
PIC X.

01
01 StudentDetails.
StudentDetails.
05
05 StudentName.
StudentName.
10
Surname
10
Surname
10
Initials
10 Initials
05
StudentId
05 CourseCode
StudentId
05
05 Grant
CourseCode
05
05 Gender
Grant
05
05 Gender

PIC
X(8).
PIC
X(8).
PIC
XX.
PIC 9(7).
XX.
PIC
PIC X(4).
9(7).
PIC
PIC 9(4).
X(4).
PIC
PIC X.
9(4).
PIC
PIC X.

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.

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.

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.

The MOVE Verb


Identifier

MOVE

Literal

TO Identifier ...

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.

MOVEing Data

MOVE
MOVE RYAN
RYAN TO
TO Surname.
Surname.
MOVE
MOVE FITZPATRICK
FITZPATRICK TO
TO Surname.
Surname.

01 Surname

PIC X(8).

C O U G H L A N

MOVEing Data

MOVE
MOVE RYAN
RYAN TO
TO Surname.
Surname.
MOVE
MOVE FITZPATRICK
FITZPATRICK TO
TO Surname.
Surname.

01 Surname

R Y A N

PIC X(8).

MOVEing Data

MOVE
MOVE RYAN
RYAN TO
TO Surname.
Surname.
MOVE
MOVE FITZPATRICK
FITZPATRICK TO
TO Surname.
Surname.

01 Surname

PIC X(8).

F I T Z P A T R I C K

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.

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

01 CountyPop
01 Price

PIC 999.
PIC 999V99.

MOVE 1234 TO CountyPop.

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

MOVE 3552.75 TO Price.

Price

3 5 5 2 7 5

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

The DISPLAY Verb


Identifier

DISPLAY
Literal

Identifier
...

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.

The ACCEPT verb


Format 1. ACCEPT Identifier FROM Mnemonic - name
DATE

DAY

Format 2. ACCEPT Identifier FROM


DAY
OF
WEEK

TIME

01
CurrentDate
01
CurrentDate
* YYMMDD

PIC
PIC 9(6).
9(6).

01
DayOfYear
01
DayOfYear
* YYDDD

PIC
PIC 9(5).
9(5).

01
Day0fWeek
01
Day0fWeek
* D (1=Monday)

PIC
PIC 9.
9.

01
CurrentTime
01
CurrentTime
* HHMMSSss
s = S/100

PIC
PIC 9(8).
9(8).

* YYMMDD
* YYDDD

* D (1=Monday)
* HHMMSSss

s = S/100

Run of Accept and Display program


Enter student details using template below
Enter student details using template below
NNNNNNNNNNSSSSSSSCCCCGGGGS
NNNNNNNNNNSSSSSSSCCCCGGGGS
COUGHLANMS9476532LM511245M
COUGHLANMS9476532LM511245M
Name is MS COUGHLAN
Name is MS COUGHLAN
Date is 24 01 94
Date is 24 01 94
Today is day 024 of the year
Today is day 024 of the year
The time is 22:23
The time is 22:23

$ SET SOURCEFORMAT"FREE"
$ SET SOURCEFORMAT"FREE"
IDENTIFICATION
DIVISION.
IDENTIFICATION
DIVISION.
PROGRAM-ID. AcceptAndDisplay.
PROGRAM-ID.
AcceptAndDisplay.
AUTHOR. Michael Coughlan.
AUTHOR. Michael Coughlan.
DATA DIVISION.
DATA DIVISION. SECTION.
WORKING-STORAGE
WORKING-STORAGE
SECTION.
01
StudentDetails.
0102
StudentDetails.
StudentName.
02 03
StudentName.
Surname
PIC X(8).
03Initials
Surname
PICXX.
X(8).
03
PIC
03
Initials
PIC
XX.
02 StudentId
PIC 9(7).
02
StudentId
PIC
9(7).
02 CourseCode
PIC X(4).
02 Grant
CourseCode
PIC9(4).
X(4).
02
PIC
02
Grant
PIC
9(4).
02 Gender
PIC X.
02 Gender
PIC X.
01 CurrentDate.
0102
CurrentDate.
CurrentYear
PIC 99.
02 CurrentMonth
CurrentYear
PIC99.
99.
02
PIC
02
CurrentMonth
PIC
99.
02 CurrentDay
PIC 99.
02 CurrentDay
PIC 99.
01 DayOfYear.
0102
DayOfYear.
FILLER
PIC 99.
02 YearDay
FILLER
PIC9(3).
99.
02
PIC
02 YearDay
PIC 9(3).
01 CurrentTime.
0102
CurrentTime.
CurrentHour
PIC 99.
02 CurrentMinute
CurrentHour
PIC99.
99.
02
PIC
02
CurrentMinute
PIC
99.
02 FILLER
PIC 9(4).
02 FILLER
PIC 9(4).

PROCEDURE DIVISION.
PROCEDURE DIVISION.
Begin.
Begin.
DISPLAY "Enter student details using template below".
DISPLAY"NNNNNNNNNNSSSSSSSCCCCGGGGS
"Enter student details using template below".
DISPLAY
".
DISPLAY
"NNNNNNNNNNSSSSSSSCCCCGGGGS
".
ACCEPT StudentDetails.
ACCEPT
StudentDetails.
ACCEPT CurrentDate FROM DATE.
ACCEPT DayOfYear
CurrentDate
FROM
DATE.
ACCEPT
FROM
DAY.
ACCEPT
DayOfYear
FROM
DAY.
ACCEPT CurrentTime FROM TIME.
ACCEPT "Name
CurrentTime
FROM TIME.
DISPLAY
is ", Initials
SPACE Surname.
DISPLAY"Date
"Nameis
is"",
Initials SPACE
DISPLAY
CurrentDay
SPACE Surname.
CurrentMonth SPACE CurrentYear.
DISPLAY
"Date
is
"
CurrentDay
SPACE CurrentYear.
DISPLAY "Today is day " YearDaySPACE
" of CurrentMonth
the year".
DISPLAY
"Today
is
day
"
YearDay
"
of
the
year".
DISPLAY "The time is " CurrentHour ":" CurrentMinute.
DISPLAY
STOP
RUN."The time is " CurrentHour ":" CurrentMinute.
STOP RUN.

Arithmetic
and
Edited Pictures

Arithmetic Verb Template


TO

Identifier FROM Identifier

VERB
Identifier
GIVING
Identifier

Literal BY

INTO

ROUNDED

ON SIZE ERROR StatementBlock 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.

The ROUNDED option


Receiving Field Actual Result Truncated Result Rounded Result
PIC 9(3)V9.

123.25

PIC 9(3).

123.25

123.2

123.3

123

123

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.

The ON SIZE ERROR option


Receiving Field
PIC 9(3)V9.
PIC 9(3)V9.

Actual Result
245.96
1245.9

PIC 9(3).

124

PIC 9(3).

1246

PIC 9(3)V9 Not Rounded

124.45

PIC 9(3)V9 Rounded

124.45

PIC 9(3)V9 Rounded

3124.45

SIZE ERROR

Yes
Yes
No
Yes
Yes
No
Yes

A size error condition exists when, after decimal


point alignment, the result is truncated on either
the left or the right hand side.

If an arithmetic statement has a rounded phrase


then a size error only occurs if there is truncation
on the left hand side (most significant digits).

ADD Examples
Before
Before
After
After
Before
Before
After
After
Before
Before
After
After
Before
Before
After
After

ADD
ADD Cash
Cash TO
TO Total.
Total.
33
1000
1000
3

1003

ADD
ADD Cash,
Cash, 20
20 TO
TO Total,
Total, Wage.
Wage.
33
1000
100
1000
100
3
1023
123
ADD
ADD Cash,
Cash, Total
TotalGIVING
GIVINGResult.
Result.
33 1000
1000
0015
3
1003
1000
0015
ADD
ADDMales
MalesTO
TOFemales
FemalesGIVING
GIVING TotalStudents
TotalStudents
1500
1500
1500

0625

0625
0625

1234

21251234

SUBTRACT Examples

Before
Before
After
After

SUBTRACT
SUBTRACT Tax
Tax FROM
FROMGrossPay,
GrossPay,Total.
Total.
120
4000
9120
120
4000
9120
120
3880
9000

Before
Before
After
After

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

Before
Before
After
After

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

MULTIPLY and DIVIDE Examples


MULTIPLY
MULTIPLY Subs
SubsBY
BYMembers
MembersGIVING
GIVINGTotalSubs
TotalSubs
ON
ONSIZE
SIZEERROR
ERRORDISPLAY
DISPLAY"TotalSubs
"TotalSubstoo
toosmall"
small"
END-MULTIPLY.
END-MULTIPLY.
Before
Before
After
After

Before
Before
After
After

Subs
Subs

15.50
15.50
15.50

100
100

0123.45
0123.45

1550.00

MULTIPLY
Magnitude,
Size.
MULTIPLY10
10BY
BY
Magnitude,
Size.
3550
1250
355
125
355
125
9234.55

Before
Before
After
After

100

Members
Members TotalSubs
TotalSubs

100

92.35

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

The Divide Exception


Identifier
Identifier
INTO
GIVING Identifier [ ROUNDED ] REMAINDER Identifier
Literal
Literal

DIVIDE

ON SIZE ERROR

StatementBlock END - DIVIDE


NOT ON SIZE ERROR

Identifier

Identifier

Literal

Literal

DIVIDE

BY

GIVING Identifier [ ROUNDED ] REMAINDER Identifier

ON SIZE ERROR

StatementBlock END - DIVIDE


NOT ON SIZE ERROR

Before
Before
After
After

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

001

The COMPUTE
COMPUTE Identifier [ ROUNDED ] ... = ArithmeticExpression
ON SIZE ERROR


NOT ON SIZE ERROR

StatementBlock END - COMPUTE

Precedence
Precedence Rules.
Rules.
1.
1.
2.
2.
3.
3.

Before
Before
After
After

****
**
//
++
--

==
==
==
==
==

POWER
POWER
MULTIPLY
MULTIPLY
DIVIDE
DIVIDE
ADD
ADD
SUBTRACT
SUBTRACT

NNNN
xx

++
--

Compute
ComputeIrishPrice
IrishPrice==SterlingPrice
SterlingPrice//Rate
Rate ** 100.
100.
1000.50
156.25
87
1000.50
156.25
87
179.59

156.25

87

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

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

Editing Symbols

Edit Symbol

,, B
B 00 //
..
++ -- CR
CR DB
DB $$
++ -- SS
ZZ **

Editing Type
Simple
SimpleInsertion
Insertion
Special
Special Insertion
Insertion
Fixed
FixedInsertion
Insertion
Floating
FloatingInsertion
Insertion
Suppression
Suppressionand
andReplacement
Replacement

Simple Insertion.
Sending
Sending
Picture
Data
Picture
Data
PIC
PIC999999
999999 123456
123456
PIC
000078
PIC9(6)
9(6)
000078
PIC
000078
PIC9(6)
9(6)
000078
PIC
000178
PIC9(6)
9(6)
000178
PIC
002178
PIC9(6)
9(6)
002178
zz
PIC
120183
PIC9(6)
9(6)
120183
PIC
120183
PIC9(6)
9(6)
120183
PIC
001245
PIC9(6)
9(6)
001245

Receiving
Receiving
Picture
Result
Picture
Result
123,456
PIC
999,999
PIC 999,999
000,078
PIC
PIC9(3),9(3)
9(3),9(3)
7
PIC
PICZZZ,ZZZ
ZZZ,ZZZ
8
PIC
****178
PIC***,***
***,***
**2,178
PIC
PIC***,***
***,***
PIC
PIC99B99B99
99B99B99
PIC
PIC99/99/99
99/99/99
PIC
PIC990099
990099

12 01 83
12/01/83
120045

Special Insertion.

Sending
Sending
Picture
Data
Picture
Data
PIC
PIC999V99
999V99 12345
12345

Receiving
Receiving
Picture
Result
Picture
Result
123.45
PIC
PIC999.99
999.99

PIC
PIC999V99
999V99 02345
02345

PIC
PIC999.9
999.9

PIC
PIC999V99
999V99 51234
51234

PIC
PIC99.99
99.99

PIC
PIC999
999

PIC
PIC999.99
999.99

456
456

023.4
12.34
456.00

Fixed Insertion - Plus and Minus.


Sending
Sending
Picture
Data
Picture
Data
PIC
-123
PICS999
S999
-123
PIC
-123
PICS999
S999
-123
PIC
+123
PICS999
S999
+123
PIC
PICS9(5)
S9(5)
PIC
PICS9(3)
S9(3)
PIC
PICS9(3)
S9(3)

Receiving
Receiving
Picture
Result
Picture
Result
-123
PIC
PIC-999
-999
123PIC
PIC 999999PIC
123
PIC-999
-999

+12345
+12345 PIC
PIC+9(5)
+9(5)
-123
PIC
-123
PIC+9(3)
+9(3)
-123
PIC
-123
PIC999+
999+

+12345
-123
123-

Fixed Insertion - Credit, Debit, $


Sending
Sending
Picture
Data
Picture
Data
PIC
+1234
PICS9(4)
S9(4)
+1234
PIC
-1234
PICS9(4)
S9(4)
-1234
PIC
+1234
PICS9(4)
S9(4)
+1234
PIC
-1234
PICS9(4)
S9(4)
-1234
PIC
PIC9(4)
9(4)
PIC
PIC9(4)
9(4)

1234
1234
0000
0000

Receiving
Receiving
Picture
Result
Picture
Result
1234
PIC
PIC9(4)CR
9(4)CR
1234CR
PIC
PIC9(4)CR
9(4)CR
1223
PIC
9(4)DB
PIC 9(4)DB
1234DB
PIC
9(4)DB
PIC 9(4)DB
PIC
PIC$99999
$99999
PIC
PIC$ZZZZZ
$ZZZZZ

$01234
$

Floating Insertion.
Sending
Sending
Picture
Data
Picture
Data
PIC
0000
PIC9(4)
9(4)
0000
PIC
0080
PIC9(4)
9(4)
0080
PIC
0128
PIC9(4)
9(4)
0128
PIC
57397
PIC9(5)
9(5)
57397
PIC
PICS9(4)
S9(4)
PIC
PICS9(4)
S9(4)
PIC
PICS9(4)
S9(4)
PIC
PICS9(5)
S9(5)

--0005
0005
+0080
+0080
--0080
0080
+71234
+71234

Receiving
Receiving
Picture
Result
Picture
Result
$0.00
PIC
PIC$$,$$9.99
$$,$$9.99
$80.00
PIC
$$,$$9.00
PIC $$,$$9.00
$128.00
PIC
PIC$$,$$9.99
$$,$$9.99
$7,397
PIC
PIC$$,$$9
$$,$$9
PIC
PIC++++9
++++9
PIC
PIC++++9
++++9
PIC
PIC-- ------ 99
PIC
PIC-- ------ 99

-5
+80
-80
1234

Suppression and Replacement

Sending
Sending
Picture
Data
Picture
Data
PIC
12345
PIC9(5)
9(5)
12345
PIC
01234
PIC9(5)
9(5)
01234
PIC
00123
PIC9(5)
9(5)
00123
PIC
00012
PIC9(5)
9(5)
00012
PIC
05678
PIC9(5)
9(5)
05678
PIC
00567
PIC9(5)
9(5)
00567
PIC
00000
PIC9(5)
9(5)
00000

Receiving
Receiving
Picture
Result
Picture
Result
PIC
12,345
PICZZ,999
ZZ,999
1,234
PIC
PICZZ,999
ZZ,999
123
PIC
ZZ,999
PIC ZZ,999
012
PIC
ZZ,999
PIC ZZ,999
*5,678
PIC
PIC**,**9
**,**9
***567
PIC
******
PIC**,**9
**,**9
PIC
PIC**,***
**,***

The
USAGE
clause

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 !!

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.

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.

Why use the USAGE clause?

The USAGE clause is used for purposes of


optimisation - both speed and storage.

The USAGE clause controls the way data items


(normally numeric) are stored in memory.

USAGE Syntax

01 Num1
01 Num2

PIC 9(5)V99 USAGE IS COMP.


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.

USAGE IS COMP

COMP items are held in memory as pure binary


two's complement numbers.

Number of Digits

Storage Required.

1 TO 4

HALF WORD (2 Bytes)

5 TO 9

FULL WORD (4 Bytes)

10 TO 18

DOUBLE WORD (8 Bytes)

01 Total-Count PIC 9(7) USAGE IS COMP.


Takes 4 bytes (1 LONGWORD) of storage

USAGE IS COMP-1

COMP-1 items are represented as one word floating


point numbers. No Picture clause is specified for a
COMP-1 variables

Number of Digits

Storage Required.

It can accommodate a maximum of 4 bytes


01 Total-Count

USAGE IS COMP-1.

01 WS-COMP-1 COMP-1.

USAGE IS COMP-2

COMP-2 items are represented as two word floating


point numbers. No Picture clause is specified for a
COMP-2 variables

Number of Digits

Storage Required.

It can accommodate a maximum of 8 bytes


01 Total-Count

USAGE IS COMP- 2.

01 WS-COMP- 2 COMP- 2.

USAGE IS COMP-3

COMP-3 items are represented in the packed


decimal form but each digit takes only half a byte.
The sign is stored in the rightmost half byte. A
picture clause is specified for COMP-3.

Number of Digits

Storage Required.

It can accommodate a maximum of 10 bytes


01 Total-Count

PIC 9(9) USAGE IS COMP- 3.


( 9 + 1 / 2)
( 5 BYTES)
01 WS-COMP- 2 PIC 9(14) COMP- 3.
(14 + 1 / 2)
( 8 BYTES)
( LENGTH +1 / 2 ) Rounded to the nearest integer

COMP - Storage Requirements


2 Bytes can represent any 4 digit number.
32768 16384 8192 4096 2048 1024 512 256 128 64

32

16

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

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
VALUE +5

PIC S9(2)
VALUE -32

PIC S9(3)
VALUE +262

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
Word1

Number

Word2

Word3

The SYNCHRONIZED Clause


COMP SYNC (1 TO 4 Digits)
COMP SYNC (5 TO 9 Digits)
COMP SYNC (10 TO 18 Digits)
INDEX

= 2 Byte boundary
= 4 Byte boundary
= 8 Byte boundary
= 4 Byte boundary

01 ThreeBytes PIC XXX VALUE "DOG".


01 TwoBytes
PIC 9(4) COMP SYNC.

D O G
Word1

Word2

Number
Word3

The SYNCHRONIZED Clause


COMP SYNC (1 TO 4 Digits)
COMP SYNC (5 TO 9 Digits)
COMP SYNC (10 TO 18 Digits)
INDEX

01 FiveBytes
01 FourBytes

PIC XXXXX VALUE "FROGS".


PIC S9(5) COMP.

F R O G S
Word1

= 2 Byte boundary
= 4 Byte boundary
= 8 Byte boundary
= 4 Byte boundary

NumberNumber
Word2

Word3

The SYNCHRONIZED Clause


COMP SYNC (1 TO 4 Digits)
COMP SYNC (5 TO 9 Digits)
COMP SYNC (10 TO 18 Digits)
INDEX

01 FiveBytes
01 FourBytes

PIC XXXXX VALUE "FROGS".


Aligns
PIC S9(5) COMP SYNC.
Alignsalong
alongaa

44byte
byteboundary
boundary

F R O G S
Word1

= 2 Byte boundary
= 4 Byte boundary
= 8 Byte boundary
= 4 Byte boundary

NumberNumber
Word2

Word3

Conditions

IF Syntax.
StatementBlock

IF Condition THEN
NEXT
SENTENCE

StatementBlock

END - IF
ELSE
NEXT
SENTENCE

CONDITION TYPES

Simple
SimpleConditions
Conditions
Relation
Relation
Conditions
Conditions
Class Conditions
Class Conditions
Sign Conditions
Sign Conditions

Complex
ComplexConditions
Conditions

Condition
ConditionNames
Names

Relation Conditions
NOT GREATER THAN

NOT >

NOT
NOT
NOT
NOT

Identifier

Literal
IS
ArithmeticExpression

LESS THAN

<

EQUAL TO

Identifier

Literal

ArithmeticExpression

GREATER THAN OR EQUAL TO


>=

LESS
THAN
OR
EQUAL
TO

<=

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

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.

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.

Complex conditions have precedence rules too.


Precedence
Precedence Rules.
Rules.
1.
1.
2.
2.

NOT
NOT
AND
AND

==
==

****
**or
or//

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
) THEN
IF ( Row > 0) AND( Row < 26
DISPLAY On Screen
END-IF
) OR( VarA NOT = VarF
)
IF ( VarA > VarC ) OR( VarC = VarD
DISPLAY Done
END-IF

Implied 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
IF Grade=A OR B+ OR B THEN
Implied
ImpliedSubjects
Subjects
IF VarA > VarB AND VarC AND VarD
TotalAmt
TotalAmt
DISPLAY VarA is the Greatest
Grade
Grade==
END-IF
VarA
VarA>>

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
33 T
33 T
33 T
F
13
13

44 T
44 T
44 F
44 T

15
15
15
15
33
15
15

14
14 T
F
15
15
14
14
14
14

DISPLAY
DISPLAY
First
Second
Third
Third

Condition Names.
IF Var A GREATER THAN Var B THEN Action
Condition is either
TRUE or FALSE

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

Defining Condition Names.


Literal

VALUE

THROUGH


88 ConditionName
HighValue
VALUES LowValue
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.

01
01 CityCode
CityCode
88
88 Dublin
Dublin
88
88 Limerick
Limerick
88
88 Cork
Cork
88
88 Galway
Galway
88
88 Sligo
Sligo
88
88 Waterford
Waterford
88
88 UniversityCity
UniversityCity
IF
IF Limerick
Limerick
DISPLAY
DISPLAY "Hey,
"Hey, we're
we're home."
home."
END-IF
END-IF
IF
IF UniversityCity
UniversityCity
PERFORM
PERFORM CalcRentSurcharge
CalcRentSurcharge
END-IF
END-IF

PIC
PIC 99
VALUE
VALUE
VALUE
VALUE
VALUE
VALUE
VALUE
VALUE
VALUE
VALUE
VALUE
VALUE
VALUE
VALUE

VALUE
VALUE 5.
5.
1.
1.
2.
2.
3.
3.
4.
4.
5.
5.
6.
6.
11 THRU
THRU 4.
4.

City Code

5
Dublin
Limerick
Cork
Galway
Sligo
Waterford
UniversityCity

FALSE
FALSE
FALSE
FALSE

TRUE

FALSE
FALSE

01
01 CityCode
CityCode
88
88 Dublin
Dublin
88
88 Limerick
Limerick
88
88 Cork
Cork
88
88 Galway
Galway
88
88 Sligo
Sligo
88
88 Waterford
Waterford
88
88 UniversityCity
UniversityCity
IF
IF Limerick
Limerick
DISPLAY
DISPLAY "Hey,
"Hey, we're
we're home."
home."
END-IF
END-IF
IF
IF UniversityCity
UniversityCity
PERFORM
PERFORM CalcRentSurcharge
CalcRentSurcharge
END-IF
END-IF

PIC
PIC 99
VALUE
VALUE
VALUE
VALUE
VALUE
VALUE
VALUE
VALUE
VALUE
VALUE
VALUE
VALUE
VALUE
VALUE

VALUE
VALUE 5.
5.
1.
1.
2.
2.
3.
3.
4.
4.
5.
5.
6.
6.
11 THRU
THRU 4.
4.

City Code

2
Dublin
Limerick
Cork
Galway
Sligo
Waterford
UniversityCity

FALSE

TRUE

FALSE
FALSE
FALSE
FALSE

TRUE

01
01 CityCode
CityCode
88
88 Dublin
Dublin
88
88 Limerick
Limerick
88
88 Cork
Cork
88
88 Galway
Galway
88
88 Sligo
Sligo
88
88 Waterford
Waterford
88
88 UniversityCity
UniversityCity
IF
IF Limerick
Limerick
DISPLAY
DISPLAY "Hey,
"Hey, we're
we're home."
home."
END-IF
END-IF
IF
IF UniversityCity
UniversityCity
PERFORM
PERFORM CalcRentSurcharge
CalcRentSurcharge
END-IF
END-IF

PIC
PIC 99
VALUE
VALUE
VALUE
VALUE
VALUE
VALUE
VALUE
VALUE
VALUE
VALUE
VALUE
VALUE
VALUE
VALUE

VALUE
VALUE 5.
5.
1.
1.
2.
2.
3.
3.
4.
4.
5.
5.
6.
6.
11 THRU
THRU 4.
4.

City Code

6
Dublin
Limerick
Cork
Galway
Sligo
Waterford
UniversityCity

FALSE
FALSE
FALSE
FALSE
FALSE

TRUE

FALSE

01
PIC
01 InputChar
InputChar
PIC X.
X.
88
VALUE
88 Vowel
Vowel
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
VALUE
88 Digit
Digit
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
DISPLAY
DISPLAY "Input
"Input OK."
OK."
END-IF
END-IF
IF
IF LowerCase
LowerCase
DISPLAY
DISPLAY "Not
"Not Upper
Upper Case"
Case"
END-IF
END-IF
IF
IF Vowel
Vowel
Display
Display "Vowel
"Vowel entered."
entered."
END-IF
END-IF

Input Char

E
Vowel
Consonant
Digit
LowerCase
ValidChar

TRUE
FALSE
FALSE
FALSE

TRUE

01
PIC
01 InputChar
InputChar
PIC X.
X.
88
VALUE
88 Vowel
Vowel
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
VALUE
88 Digit
Digit
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
DISPLAY
DISPLAY "Input
"Input OK."
OK."
END-IF
END-IF
IF
IF LowerCase
LowerCase
DISPLAY
DISPLAY "Not
"Not Upper
Upper Case"
Case"
END-IF
END-IF
IF
IF Vowel
Vowel
Display
Display "Vowel
"Vowel entered."
entered."
END-IF
END-IF

Input Char

4
Vowel
Consonant
Digit
LowerCase
ValidChar

FALSE
FALSE

TRUE

FALSE

TRUE

01
PIC
01 InputChar
InputChar
PIC X.
X.
88
VALUE
88 Vowel
Vowel
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
VALUE
88 Digit
Digit
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
DISPLAY
DISPLAY "Input
"Input OK."
OK."
END-IF
END-IF
IF
IF LowerCase
LowerCase
DISPLAY
DISPLAY "Not
"Not Upper
Upper Case"
Case"
END-IF
END-IF
IF
IF Vowel
Vowel
Display
Display "Vowel
"Vowel entered."
entered."
END-IF
END-IF

Input Char

g
Vowel
Consonant
Digit
LowerCase
ValidChar

FALSE
FALSE
FALSE

TRUE

FALSE

EndOfFileFlag
01
01 EndOfFileFlag
EndOfFileFlag
88
88 EndOfFile
EndOfFile

PIC
PIC 99 VALUE
VALUE 0.
0.
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

EndOfFileFlag
01
01 EndOfFileFlag
EndOfFileFlag
88
88 EndOfFile
EndOfFile

PIC
PIC 99 VALUE
VALUE 0.
0.
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

Using the SET verb.


FILLER
01
PIC
01 FILLER
FILLER
PIC 99 VALUE
VALUE 0.
0.
88
VALUE
88 EndOfFile
EndOfFile
VALUE 1.
1.
88
88 NotEndOfFile
NotEndOfFile VALUE
VALUE 0.
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 TO
TO TRUE
TRUE
END-READ
END-READ
END-PERFORM
END-PERFORM
Set
Set NotEndOfFile
NotEndOfFile TO
TO TRUE.
TRUE.

Using the SET verb.


FILLER
01
PIC
01 FILLER
FILLER
PIC 99 VALUE
VALUE 0.
0.
88
VALUE
88 EndOfFile
EndOfFile
VALUE 1.
1.
88
88 NotEndOfFile
NotEndOfFile VALUE
VALUE 0.
0.

1
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 TO
TO TRUE
TRUE
END-READ
END-READ
END-PERFORM
END-PERFORM
Set
Set NotEndOfFile
NotEndOfFile TO
TO TRUE.
TRUE.

Using the SET verb.


FILLER
01
PIC
01 FILLER
FILLER
PIC 99 VALUE
VALUE 0.
0.
88
VALUE
88 EndOfFile
EndOfFile
VALUE 1.
1.
88
88 NotEndOfFile
NotEndOfFile VALUE
VALUE 0.
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 TO
TO TRUE
TRUE
END-READ
END-READ
END-PERFORM
END-PERFORM
Set
Set NotEndOfFile
NotEndOfFile TO
TO TRUE.
TRUE.

FD
FD StudentFile.
StudentFile.
01
StudentDetails.
01 StudentDetails.
88
88 EndOfFile
EndOfFile VALUE
VALUE HIGH-VALUES.
HIGH-VALUES.
02
StudentId
PIC
02 StudentId
PIC 9(7).
9(7).
02
StudentName.
02 StudentName.
03
PIC
03 Surname
Surname
PIC X(8).
X(8).
03
Initials
PIC
XX.
03 Initials
PIC XX.
02
DateOfBirth.
02 DateOfBirth.
03
PIC
03 YOBirth
YOBirth
PIC 9(2).
9(2).
03
MOBirth
PIC
9(2).
03 MOBirth
PIC 9(2).
03
DOBirth
PIC
03 DOBirth
PIC 9(2).
9(2).
02
CourseCode
PIC
X(4).
02 CourseCode
PIC X(4).
02
Grant
PIC
02 Grant
PIC 9(4).
9(4).
02
Gender
PIC
X.
02 Gender
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
StudentId
DISPLAY StudentId SPACE
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.

The Evaluate
Identifier

Literal

CondExpression

EVALUATE

ArithExpression
TRUE

FALSE

ANY

Condition


WHEN TRUE

FALSE


Identifier

NOT
Literal


ArithExpression

WHEN OTHER StatementBlock


END - EVALUATE

Identifier

THRU

Literal

THROUGH

ArithExpression

StatementBlock

10

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

Decision Table Implementation.


Gender
M
F
M
F
Age
<20 <20 20-40 20-40
Service Any Any <10
<10
% Bonus 5
10
12
13
EVALUATE Gender
WHEN
"M"
WHEN
"F"
WHEN
"M"
WHEN
"F"
WHEN
"M"
WHEN
"F"
:
:
:
:
WHEN
"F"
END-EVALUATE

TRUE
Age<20
Age<20
Age>19 AND <41
Age>19 AND <41
Age>40
Age>40
:
:
ANY

M
40>
<10
20

F
40>
<10
15

TRUE
ANY
ANY
Service<10
Service<10
Service<10
Service<10
:
:
Service>20

M
F
20-40 20-40 etc
10-20 10-20 etc
14
23

MOVE 5 TO Bonus
MOVE 10 TO Bonus
MOVE 12 TO Bonus
MOVE 13 TO Bonus
MOVE 20 TO Bonus
MOVE 15 TO Bonus
:
:
MOVE 25 TO Bonus

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.

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.

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.

COPY format
TextName
OF
COPY

ExternalFileNameLiteral
IN

LibraryName


LibraryNameLiteral

== PseudoText1 ==
== PseudoText2 ==

Identifier2

Identifier1

REPLACING
BY

Literal1
Literal2

Word1

Word2

Example COPY statements.


COPY "CopyFile2.CBL" REPLACING XYZ BY 120.
ExternalFileNameLiteral

COPY Copyfile3 IN "d:\visocd\examples\EGLIB".


TextName

LibraryNameLiteral

COPY "CopyFile3.CBL" IN "d:\visocd\examples\EGLIB".


ExternalFileNameLiteral

LibraryNameLiteral

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

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.

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.

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 (

PIC S9(4)V9(6)

4 ) V9 ( 6 )

1 Text word - PIC S9(4)V9(6)

COPY Example 1
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID.
COPYEG1.
PROGRAM-ID. COPYEG1.
AUTHOR.
AUTHOR. Michael
Michael Coughlan.
Coughlan.
ENVIRONMENT
ENVIRONMENT DIVISION.
DIVISION.
01
FILE-CONTROL.
01 StudentRec.
StudentRec.
FILE-CONTROL.
SELECT
SELECT StudentFile
StudentFile ASSIGN
ASSIGN TO
TO "STUDENTS.DAT"
"STUDENTS.DAT"
88
ORGANIZATION
IS
LINE
SEQUENTIAL.
88 EndOfSF
EndOfSF
ORGANIZATION IS LINE SEQUENTIAL.
DATA
DATA DIVISION.
DIVISION.
FILE
SECTION.
FILE SECTION.
FD
FD StudentFile.
StudentFile.
COPY
COPY COPYFILE1.
COPYFILE1.

VALUE
VALUE HIGH-VALUES.
HIGH-VALUES.

02
02 StudentNumber
StudentNumber

PIC
PIC 9(7).
9(7).

02
02 StudentName
StudentName

PIC
PIC X(60).
X(60).

02
02 CourseCode
CourseCode

PIC
PIC X(4).
X(4).

02
PIC
PROCEDURE
02 FeesOwed
FeesOwed
PIC 9(4).
9(4).
PROCEDURE DIVISION.
DIVISION.
BeginProg.
BeginProg.
OPEN
02
PIC
OPEN INPUT
INPUT StudentFile
StudentFile
02 AmountPaid
AmountPaid
PIC 9(4)V99.
9(4)V99.
READ
StudentFile
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
StudentNumber
DISPLAY StudentNumber SPACE
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
GOBACK.
GOBACK.

COPY Example 2
Copyfile2.cbl

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

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

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

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

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

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

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

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
02 CustNum

PIC X(3) VALUE "ABC".


PIC 9(8).

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
02
02

CustKey
CustKey
CustKey

PIC
PIC
PIC

X@3) VALUE "KEY".


X(three) VALUE "KEY".
X(3& VALUE "KEY".

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
02
02

CustKey
CustKey
CustKey

PIC
PIC
PIC

Replace the
X(19) VALUE
X(19) VALUE

X(3) VALUE KEY".


"KEY".
"KEY".

COPY Example 10
Copyfile5.cbl

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
02 CustKey

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


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

The
PERFORM

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.

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

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.

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
ofProcessRecord
ProcessRecordis
is
delimited
delimitedby
bythe
theoccurrence
occurrencethe
the
paragraph
paragraphname
nameProduceOutput.
ProduceOutput.

Format 1 Syntax.

THRU

EndProc
PERFORM 1stProc
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.

Format 1 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
Startingto
torun
runprogram"
program"
PERFORM
PERFORM OneLevelDown
OneLevelDown
DISPLAY
"Back
DISPLAY "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
TwoLevelsDown
PERFORM 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
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
TwoLevelsDown
PERFORM 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
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
OneLevelDown
PERFORM OneLevelDown
DISPLAY
DISPLAY "Back
"Back in
in TopLevel.".
TopLevel.".
GOBACK.
GOBACK.
TwoLevelsDown.
TwoLevelsDown.
DISPLAY
DISPLAY ">>>>>>>>
">>>>>>>> Now
Now in
in TwoLevelsDown."
TwoLevelsDown."

OneLevelDown.
OneLevelDown.
DISPLAY
DISPLAY">>>>
">>>> Now
Now in
in OneLevelDown"
OneLevelDown"
PERFORM
PERFORM
DISPLAY
DISPLAY

TwoLevelsDown
TwoLevelsDown
">>>>
">>>> 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
OneLevelDown
PERFORM OneLevelDown
DISPLAY
DISPLAY "Back
"Back in
in TopLevel.".
TopLevel.".
GOBACK.
GOBACK.
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
OneLevelDown
PERFORM OneLevelDown
DISPLAY
DISPLAY "Back
"Back in
in TopLevel.".
TopLevel.".
GOBACK.
GOBACK.

TwoLevelsDown.
TwoLevelsDown.
DISPLAY
DISPLAY">>>>>>>>
">>>>>>>> Now
Now in
inTwoLevelsDown."
TwoLevelsDown."
OneLevelDown.
OneLevelDown.
DISPLAY
DISPLAY ">>>>
">>>> Now
Now in
in OneLevelDown"
OneLevelDown"
PERFORM
TwoLevelsDown
PERFORM 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
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
OneLevelDown
PERFORM OneLevelDown
DISPLAY
DISPLAY "Back
"Back in
in TopLevel.".
TopLevel.".
GOBACK.
GOBACK.
TwoLevelsDown.
TwoLevelsDown.
DISPLAY
DISPLAY ">>>>>>>>
">>>>>>>> Now
Now in
in TwoLevelsDown."
TwoLevelsDown."

OneLevelDown.
OneLevelDown.
DISPLAY
DISPLAY
PERFORM
PERFORM

">>>>
">>>> Now
Now in
in OneLevelDown"
OneLevelDown"
TwoLevelsDown
TwoLevelsDown

DISPLAY
DISPLAY">>>>
">>>> Back
Back in
inOneLevelDown".
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
PERFORM
PERFORM

"In
"In TopLevel.
TopLevel. Starting
Starting to
to run
run program"
program"
OneLevelDown
OneLevelDown

DISPLAY
DISPLAY"Back
"Backin
in TopLevel.".
TopLevel.".
GOBACK.
GOBACK.

TwoLevelsDown.
TwoLevelsDown.
DISPLAY
DISPLAY ">>>>>>>>
">>>>>>>> Now
Now in
in TwoLevelsDown."
TwoLevelsDown."
OneLevelDown.
OneLevelDown.
DISPLAY
DISPLAY ">>>>
">>>> Now
Now in
in OneLevelDown"
OneLevelDown"
PERFORM
TwoLevelsDown
PERFORM TwoLevelsDown
DISPLAY
DISPLAY ">>>>
">>>> Back
Back in
in OneLevelDown".
OneLevelDown".

Why use the PERFORM Thru?


PROCEDURE
PROCEDURE DIVISION.
DIVISION.
Begin.
Begin.
PERFORM
PERFORM SumSales
SumSales
GOBACK.
GOBACK.
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
GOBACK.
GOBACK.
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

EndProc
PERFORM 1stProc
THROUGH

RepeatCount TIMES

StatementBlock END - PERFORM


PROCEDURE
PROCEDUREDIVISION.
DIVISION.
Begin.
Begin.
Statements

PERFORM DisplayName 4 TIMES


Statements

GOBACK.
DisplayName.
DisplayName.
DISPLAY Tom Ryan.

Format 2 Example
$$ SET
SET SOURCEFORMAT"FREE"
SOURCEFORMAT"FREE"
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID.
PerformExample2.
PROGRAM-ID. PerformExample2.
AUTHOR.
AUTHOR. CGI.
CGI.
DATA
DATA DIVISION.
DIVISION.
WORKING-STORAGE
WORKING-STORAGE SECTION.
SECTION.
01
NumofTimes
PIC
01 NumofTimes
PIC 99 VALUE
VALUE 5.
5.

Run of PerformExample2
Starting to run program
Starting to run program
>>>>This is an in line Perform
>>>>This is an in line Perform
>>>>This is an in line Perform
>>>>Thisis
isan
anin
inline
line Perform
Perform
>>>>This
>>>>This is an in line Perform
Finished in line Perform
Finished in line Perform
>>>> This is an out of line Perform
>>>> This is an out of line Perform
>>>> This is an out of line Perform
>>>> This is an out of line Perform
>>>> This is an out of line Perform
>>>> This is an out of line Perform
>>>> This is an out of line Perform
>>>> 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
Back in Begin. About to Stop

PROCEDURE
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
OutOfLineEG
NumOfTimes
PERFORM OutOfLineEG NumOfTimes TIMES
TIMES
DISPLAY
"Back
in
Begin.
About
to
DISPLAY "Back in Begin. About to Stop".
Stop".
GOBACK.
GOBACK.

OutOfLineEG.
OutOfLineEG.
DISPLAY
DISPLAY ">>>>
">>>> This
This is
is an
an out
out of
of line
line Perform".
Perform".

Format 3 Syntax

THRU

BEFORE
EndProc WITH TEST

PERFORM 1stProc
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.

PERFORM
PERFORMWITH
WITH
TEST
TESTBEFORE
BEFORE==
WHILE
WHILE...
...DO
DO

PERFORM
PERFORMWITH
WITH
TEST
TESTAFTER
AFTER==
REPEAT
REPEAT...
...UNTIL
UNTIL

Loop Body

test

False

True

Next Statement

Loop Body

test

False

True

Next Statement

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.

The READ 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.

Reading a Sequential 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!

RUN OF SeqRead
9456789
9456789 COUGHLANMS
COUGHLANMS LM51
LM51
9367892
TG
9367892 RYAN
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
StudentId
SPACE
StudentName
DISPLAY StudentId SPACE StudentName SPACE
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
GOBACK.
GOBACK.

Tables
and

PERFORM..VARYING

TaxTotal
Variable = Named location in memory
PAYENum CountyNum

The program to
calculate the total
taxes paid for the
country is easy to
write.
BUT.
What do we do if we
want to calculate the
taxes paid in each
county?

TaxPaid

PROCEDURE DIVISION.
Begin.
OPEN INPUT TaxFile
READ TaxFile
AT END SET EndOfTaxFile TO TRUE
END-READ
PERFORM UNTIL EndOfTaxFile
ADD TaxPaid TO TaxTotal
READ TaxFile
AT END SET EndOfTaxFile TO TRUE
END-READ
END-PERFORM.
DISPLAY "Total taxes are ", TaxTotal
CLOSE TaxFile
GOBACK.

County1
TaxTotal

County2
TaxTotal

County3
TaxTotal

County4
TaxTotal

County5
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

: 24 Statements

DISPLAY "County 26 total is ", County26TaxTotal


CLOSE TaxFile
GOBACK.
SumCountyTaxes.
IF CountyNum = 1 ADD TaxPaid TO County1TaxTotal
END-IF
IF CountyNum = 26 ADD TaxPaid TO County26TaxTotal
END-IF
READ TaxFile
AT END SET EndOfTaxFile TO TRUE
58 Statements
END-READ

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

10
1

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

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

10

55
1

MOVE 10 TO CountyTax(5)
55

ADD TaxPaid TO CountyTax(CountyNum)


ADD TaxPaid TO CountyTax(CountyNum + 2)

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

55
1

55

10

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

ADD TaxPaid TO CountyTax(CountyNum + 2)

Tables/Arrays
AAtable
tableis
isaacontiguous
contiguoussequence
sequenceof
ofmemory
memorylocations
locations
called
name
calledelements
elements, ,which
whichall
allhave
havethe
thesame
samename,
name,
andare
are
name and
uniquely
uniquelyidentified
identifiedby
bythat
thatname
nameand
andby
bytheir
theirposition
positionin
in
the
subscript
thesequence.
sequence.The position index is called a subscript.
CountyTax

55
1

55
3

MOVE 10 TO CountyTax(5)

10
5
Subscript

ADD TaxPaid TO CountyTax(CountyNum)


ADD TaxPaid TO CountyTax(CountyNum + 2)

CountyTax

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
Subscript
END-PERFORM.
PERFORM VARYING Idx FROM 1 BY 1
UNTIL Idx GREATER THAN 26
DISPLAY "County ", CountyNum
" tax total is " CountyTax(Idx)
END-PERFORM
CLOSE TaxFile
9 Statements
GOBACK.

TaxRecord.
PAYENum

CountyName

TaxPaid

A-89432

CLARE

7894.55

CountyTax

IF CountyName = "CARLOW"
ADD TaxPaid TO CountyTax(1)
END-IF
IF CountyName = "CAVAN"
ADD TaxPaid TO CountyTax(2)
END-IF

:
:

:
:

:
:
:
:
24 TIMES

:
:

TaxRecord.
PAYENum

A-89432

CountyName

CLARE

TaxPaid

Idx

7894.55

County

CARLOW

CAVAN

CLARE

CORK

1000.00
3

745.55
4

DONEGAL DUBLIN
5

CountyTax

500.50
1

125.75
2

345.23
5

PERFORM VARYING Idx FROM 1 BY 1


UNTIL County(Idx) = CountyName
END-PERFORM
ADD TaxPaid TO CountyTax(Idx)

123.45
6

TaxRecord.
PAYENum

A-89432

CountyName

CLARE

TaxPaid

Idx

7894.55

County

CARLOW

CAVAN

CLARE

CORK

1000.00
3

745.55
4

DONEGAL DUBLIN
5

CountyTax

500.50
1

125.75
2

345.23
5

PERFORM VARYING Idx FROM 1 BY 1


UNTIL County(Idx) = CountyName
END-PERFORM
ADD TaxPaid TO CountyTax(Idx)

123.45
6

TaxRecord.
PAYENum

A-89432

CountyName

CLARE

TaxPaid

Idx

7894.55

County

CARLOW

CAVAN

CLARE

CORK

1000.00
3

745.55
4

DONEGAL DUBLIN
5

CountyTax

500.50
1

125.75
2

345.23
5

PERFORM VARYING Idx FROM 1 BY 1


UNTIL County(Idx) = CountyName
END-PERFORM
ADD TaxPaid TO CountyTax(Idx)

123.45
6

TaxRecord.
PAYENum

A-89432

CountyName

CLARE

TaxPaid

Idx

7894.55

County

CARLOW

CAVAN

CLARE

CORK

8894.55
3

745.55
4

DONEGAL DUBLIN
5

CountyTax

500.50
1

125.75
2

345.23
5

PERFORM VARYING Idx FROM 1 BY 1


UNTIL County(Idx) = CountyName
END-PERFORM
ADD TaxPaid TO CountyTax(Idx)

123.45
6

Declaring Tables.

TaxTotals
CountyTax

000000 000000
1
2

01

000000
3

TaxTotals.
02 CountyTax

000000
4

000000 000000
5
6

PIC 9(10)V99
OCCURS 26 TIMES.

or
02
e.g.

CountyTax

OCCURS 26 TIMES
PIC 9(10)V99.

MOVE ZEROS TO TaxTotals.


MOVE 20 TO CountyTax(5).

TaxTotals

Group Items as Elements.


25

000000

CountyTax

67
3

000000

PayerCount

CountyTaxDetails
01

TaxTotals.
02 CountyTaxDetails
03 CountyTax
03 PayerCount

e.g.

OCCURS 26 TIMES.
PIC 9(10)V99.
PIC 9(7).

MOVE 25 TO PayerCount(2).
MOVE 67 TO CountyTax(5).
MOVE ZEROS TO CountyTaxDetails(3).

PERFORM..VARYING Syntax

THRU

BEFORE
PERFORM 1stProc
EndProc
WITH
TEST



THROUGH
AFTER

Identifier 2
Identifer1

VARYING
FROM
IndexName
2

IndexName1
Literal

Identifier3
BY
UNTIL Condition1
Literal

AFTER

Identifier 5
Identifier4

FROM
IndexName
4

IndexName3
Literal

Identifier6

BY
UNTIL
Condition2

Literal

StatementBlock END - PERFORM

PERFORM VARYING Idx1 FROM 1 BY 1 UNTIL


Idx1 EQUAL TO 3
DISPLAY Idx1
END-PERFORM.
Idx1
Move 1 to Idx1

Idx1 = 3

True

False

Loop Body
Inc Idx1

Next Statement

PERFORM VARYING Idx1 FROM 1 BY 1 UNTIL


Idx1 EQUAL TO 3
DISPLAY Idx1
END-PERFORM.
Idx1
Move 1 to Idx1

Idx1 = 3

True

False

Loop Body
Inc Idx1

Next Statement

PERFORM VARYING Idx1 FROM 1 BY 1 UNTIL


Idx1 EQUAL TO 3
DISPLAY Idx1
END-PERFORM.
Idx1
Move 1 to Idx1

Idx1 = 3

True

Next Statement

False

Loop Body
Inc Idx1

PERFORM VARYING Idx1 FROM 1 BY 1 UNTIL


Idx1 EQUAL TO 3
DISPLAY Idx1
END-PERFORM.
Idx1
Move 1 to Idx1

Idx1 = 3

True

Next Statement

False

Loop Body
Inc Idx1

PERFORM VARYING Idx1 FROM 1 BY 1 UNTIL


Idx1 EQUAL TO 3
DISPLAY Idx1
END-PERFORM.
Idx1
Move 1 to Idx1

Idx1 = 3

True

Next Statement

False

Loop Body
Inc Idx1

PERFORM VARYING Idx1 FROM 1 BY 1 UNTIL


Idx1 EQUAL TO 3
DISPLAY Idx1
END-PERFORM.
Idx1
Move 1 to Idx1

Idx1 = 3

True

Next Statement

False

Loop Body
Inc Idx1

1
2

PERFORM VARYING Idx1 FROM 1 BY 1 UNTIL


Idx1 EQUAL TO 3
DISPLAY Idx1
END-PERFORM.
Idx1
Move 1 to Idx1

Idx1 = 3

True

Next Statement

False

Loop Body
Inc Idx1

1
2

PERFORM VARYING Idx1 FROM 1 BY 1 UNTIL


Idx1 EQUAL TO 3
DISPLAY Idx1
END-PERFORM.
Idx1
Move 1 to Idx1

Idx1 = 3

True

Next Statement

False

Loop Body
Inc Idx1

1
2
Exit value = 3

PERFORM IterationCount VARYING


UNTIL
AFTER
UNTIL

Idx1
Idx1
Idx2
Idx2

FROM 1 BY 2
EQUAL TO 5
FROM 6 BY -1
LESS THAN 4

Move 1 to Idx1
Move 6 to Idx2

Idx1 = 5

T Idx1 Idx2

Next Statement

N
Y
Idx2 < 4
N

IterationCount
Dec Idx2

Move 6 to Idx2
Inc Idx1

x =5

=6

Advanced Tables.

One Dimension Table.

01 JeansTable.

One Dimension Table.

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

One Dimension Table.

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.

01 JeansTable.
02 Province OCCURS 4 TIMES.

Two Dimension Table.

1
1

2
2

3
2

4
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

01 JeansTable.
02 Province OCCURS 4 TIMES.

Three Dimension Table.


1
1

2
2

3
2

4
2

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

Three Dimension Table.


1
1
1 2 3

2
2

3
2

4
2

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
1
1 2 3

2
2

3
2

4
2

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

SalesValue

309

Colour

NumSold

Record Elements.
1
1

2
2

1 2 3 1 2 3

3
2

1 2 3 1 2 3

4
2

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

.3

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

The Redefines Clause.


Rates

.4

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

The Redefines Clause.


Rates

.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

USDay USMonth
USDate

1983
USYear

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

Creating Pre-filled Tables

01 LetterTable.
02 TableValues.

Creating Pre-filled Tables

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

Creating Pre-filled Tables

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

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
1

50 75

2
3

90

3
3

75 85 95

4
3

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.

COBOL 85 Table 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.

Searching Tables.

Creating Pre-filled Tables

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

Creating Pre-filled Tables

01
01 LetterTable.
LetterTable.
02
02 TableValues.
TableValues.
03
03 FILLER
FILLER PIC
PIC X(13)
X(13)
VALUE
ABCDEFGHIJKLM
VALUE ""ABCDEFGHIJKLM".
ABCDEFGHIJKLM".
ABCDEFGHIJKLM
03
03 FILLER
FILLER PIC
PIC X(13)
X(13)
VALUE
NOPQRSTUVWXYZ
VALUE ""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

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

SET Syntax

Searching a Table
A

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
FILLER
03 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 TO
TO 1.
1.
SEARCH
Letter
SEARCH Letter
AT
AT END
END DISPLAY
DISPLAY "Letter
"Letter
WHEN
WHEN Letter(LetterIdx)
Letter(LetterIdx)
DISPLAY
DISPLAY LetterIn,
LetterIn,
END-SEARCH.
END-SEARCH.

not
not found!"
found!"
== LetterIn
LetterIn
"is
"is in
in position
position ",
", Idx
Idx

Searching a Two Dimension Table.


1

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

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
VALUE "NOPQRSTUVWXYZ".
"NOPQRSTUVWXYZ".
02
FILLER
REDEFINES
02 FILLER REDEFINES TableValues.
TableValues.
03
Letter
PIC
X
OCCURS
03 Letter PIC X OCCURS 26
26 TIMES
TIMES
ASCENDING
KEY
ASCENDING KEY IS
IS Letter
Letter
INDEXED
BY
LetterIdx.
INDEXED BY LetterIdx.
SEARCH
SEARCH ALL
ALL Letter
Letter
WHEN
WHEN Letter(LetterIdx)
Letter(LetterIdx) == LetterIn
LetterIn
DISPLAY
LetterIn,
"is
DISPLAY LetterIn, "is in
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

9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

Lower

Upper

Middle

26

13

ALGORITHM.

Letter(Middle)

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

9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

Lower

Upper

Middle

14

26

13

ALGORITHM.

Letter(Middle)

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

9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

Lower

Upper

Middle

14

26

20

ALGORITHM.

Letter(Middle)

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

9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

Lower

Upper

Middle

14

19

20

ALGORITHM.

Letter(Middle)

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

9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

Lower

Upper

Middle

14

19

16

ALGORITHM.

Letter(Middle)

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

9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

Lower

Upper

Middle

17

19

16

ALGORITHM.

Letter(Middle)

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

9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

Lower

Upper

Middle

17

19

18

ALGORITHM.

Letter(Middle)

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

9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

Lower

Upper

Middle

17

17

18

ALGORITHM.

Letter(Middle)

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

9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

Lower

Upper

Middle

17

17

18

ALGORITHM.

Letter(Middle)

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

9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

Lower

Upper

Middle

17

17

18

ALGORITHM.

Letter(Middle)

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 50
50 TIMES
TIMES
ASCENDING
ASCENDING KEY
KEY IS
IS StateName
StateName
INDEXED
INDEXED BY
BY StateIdx.
StateIdx.
04
PIC
04 PostCode
PostCode
PIC X(6).
X(6).
04
StateName
PIC
X(14).
04 StateName
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) TO
TO PrintPostCode
PrintPostCode
END-SEARCH.
END-SEARCH.

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

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.

Files, Records, Fields.


STUDENTS.DAT
StudId
StudId StudName
StudName DateOfBirth
DateOfBirth
9723456
9723456 COUGHLAN
COUGHLAN
9724567
RYAN
9724567 RYAN
9534118
9534118 COFFEY
COFFEY
9423458
O'BRIEN
9423458 O'BRIEN
9312876
9312876 SMITH
SMITH

10091961
10091961
31121976
31121976
23061964
23061964
03111979
03111979
12121976
12121976

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

occurrences

Record Type
(Template)
(Structure)

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 computers memory
at once.

Files are processed by reading them into the


computers memory one record at a time.

Record Buffers

To process a file records are read from the file into


the computers 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.

Record Buffers
Program

DISK
STUDENTS.DAT

Record Instance

IDENTIFICATION DIVISION.
etc.
ENVIRONMENT DIVISION.
etc.
DATA DIVISION.
FILE SECTION.
RecordBuffer
Declaration

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

Creating a Student Record


Student Details.
01
01StudentDetails.
StudentDetails.

02
Student
StudentId.
Id.
02 StudentId
StudentId

Student
StudentName.
Name.

Surname
Surname
Initials
Initials

Date
Dateof
ofBirth
Birth

Year
YearofofBirth
Birth
Month
MonthofofBirth
Birth
Day
DayofofBirth
Birth

Course
CourseCode
Code

Value of grant

Value of grant

Gender
Gender

PIC
PIC 9(7).
9(7).

02
02 StudentName.
StudentName.
03
03 Surname
SurnamePIC
PIC X(8).
X(8).
03
PIC
03 Initials
Initials
PIC XX.
XX.
02
02 DateOfBirth.
DateOfBirth.
03
03 YOBirth
YOBirthPIC
PIC 99.
99.
03
03 MOBirth
MOBirthPIC
PIC 99.
99.
03
03 DOBirth
DOBirthPIC
PIC 99.
99.

02
02 CourseCode
CourseCode PIC
PIC X(4).
X(4).
02
02 Grant
Grant PIC
PIC 9(4).
9(4).
02
02 Gender
Gender PIC
PIC X.
X.

Describing the record buffer in COBOL


DATA
DIVISION.
DATA
DIVISION.
FILE
SECTION.
FILE
SECTION.
FD
StudentFile.
FD StudentDetails.
StudentFile.
01
01 02
StudentDetails.
StudentId
02
StudentId
02
StudentName.
02 03
StudentName.
Surname
03
Surname
03
Initials
03 Initials
02
DateOfBirth.
02 03
DateOfBirth.
YOBirth
03
YOBirth
03
MOBirth
03 DOBirth
MOBirth
03
03 DOBirth
02
CourseCode
02 Grant
CourseCode
02
02 Gender
Grant
02
02 Gender

PIC
PIC 9(7).
9(7).
PIC
X(8).
PIC
X(8).
PIC
XX.
PIC XX.
PIC
9(2).
PIC
9(2).
PIC
9(2).
PIC 9(2).
9(2).
PIC
PIC X(4).
9(2).
PIC
PIC 9(4).
X(4).
PIC
PIC X.
9(4).
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.

The Select and Assign Clause.

DISK
STUDENTS.DAT

ENVIRONMENT
DIVISION.
ENVIRONMENT
DIVISION.
INPUT-OUTPUT
SECTION.
INPUT-OUTPUT
SECTION.
FILE-CONTROL.
FILE-CONTROL.
SELECT
StudentFile
SELECT
StudentFile
ASSIGN
ASSIGN TO
TO STUDENTS.DAT.
STUDENTS.DAT.
DATA
DIVISION.
DATA
DIVISION.
FILE
SECTION.
FILE
SECTION.
FD
StudentFile.
FD StudentDetails.
StudentFile.
01
01 02
StudentDetails.
StudentId
PIC
9(7).
02
StudentId
PIC
9(7).
02
StudentName.
02 03
StudentName.
Surname
PIC
X(8).
03
Surname
PIC
X(8).
03
Initials
PIC
XX.
03 Initials
PIC XX.
02
DateOfBirth.
02 03
DateOfBirth.
YOBirth
PIC
9(2).
03
YOBirth
PIC
9(2).
03
MOBirth
PIC
9(2).
03 DOBirth
MOBirth
PIC 9(2).
9(2).
03
PIC
03 DOBirth
PIC X(4).
9(2).
02
CourseCode
PIC
02 Grant
CourseCode
PIC 9(4).
X(4).
02
PIC
02 Gender
Grant
PIC X.
9(4).
02
PIC
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.

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.

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.

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.

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.

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.

How the READ works


StudentRecord
StudentID
9 3 3 4 5 6 7

9
9
9
9

3
3
3
3

3
8
4
7

4
3
7
8

5
7
2
8

Course.

StudentName

6
1
9
1

7
5
2
1

F r a n k

F
T
T
B

r
h
o
i

a
o
n
l

C u r t a i n

n k
C u
ma s
H
y
O B
l y
D o

r
e
r
w

t
a
i
n

a
l
a
e

i n
y
n
s

L M 0 5 1

L
L
L
L

EOF
PERFORM UNTIL StudentRecord = HIGH-VALUES
READ StudentRecords
AT END MOVE HIGH-VALUES TO StudentRecord
END-READ
END-PERFORM.

M
M
M
M

0
0
0
0

5
6
5
2

1
8
1
1

How the READ works


StudentRecord
StudentID
9 3 8 3 7 1 5

9
9
9
9

3
3
3
3

3
8
4
7

4
3
7
8

5
7
2
8

Course.

StudentName

6
1
9
1

7
5
2
1

T h o ma s

F
T
T
B

r
h
o
i

a
o
n
l

H e a l y

n k
C u
ma s
H
y
O B
l y
D o

r
e
r
w

t
a
i
n

a
l
a
e

i n
y
n
s

L M 0 6 8

L
L
L
L

EOF
PERFORM UNTIL StudentRecord = HIGH-VALUES
READ StudentRecords
AT END MOVE HIGH-VALUES TO StudentRecord
END-READ
END-PERFORM.

M
M
M
M

0
0
0
0

5
6
5
2

1
8
1
1

How the READ works


StudentRecord
StudentID
9 3 4 7 2 9 2

9
9
9
9

3
3
3
3

3
8
4
7

4
3
7
8

5
7
2
8

Course.

StudentName

6
1
9
1

7
5
2
1

T o n y

F
T
T
B

r
h
o
i

a
o
n
l

O B r i a n

n k
C u
ma s
H
y
O B
l y
D o

r
e
r
w

t
a
i
n

a
l
a
e

i n
y
n
s

L M 0 5 1

L
L
L
L

EOF
PERFORM UNTIL StudentRecord = HIGH-VALUES
READ StudentRecords
AT END MOVE HIGH-VALUES TO StudentRecord
END-READ
END-PERFORM.

M
M
M
M

0
0
0
0

5
6
5
2

1
8
1
1

How the READ works


StudentRecord
StudentID
9 3 7 8 8 1 1

9
9
9
9

3
3
3
3

3
8
4
7

4
3
7
8

5
7
2
8

Course.

StudentName

6
1
9
1

7
5
2
1

B i l l y

F
T
T
B

r
h
o
i

a
o
n
l

n
m
y
l

k
a s
O
y

D o w n e s

C u
H
B
D o

r
e
r
w

t
a
i
n

a
l
a
e

i n
y
n
s

L M 0 2 1

L
L
L
L

EOF
PERFORM UNTIL StudentRecord = HIGH-VALUES
READ StudentRecords
AT END MOVE HIGH-VALUES TO StudentRecord
END-READ
END-PERFORM.

M
M
M
M

0
0
0
0

5
6
5
2

1
8
1
1

How the READ works


StudentRecord
StudentID

Course.

StudentName

HIGH-VALUES
9
9
9
9

3
3
3
3

3
8
4
7

4
3
7
8

5
7
2
8

6
1
9
1

7
5
2
1

F
T
T
B

r
h
o
i

a
o
n
l

n k
C u
ma s
H
y
O B
l y
D o

r
e
r
w

t
a
i
n

a
l
a
e

i n
y
n
s

L
L
L
L

EOF
PERFORM UNTIL StudentRecord = HIGH-VALUES
READ StudentRecords
AT END MOVE HIGH-VALUES TO StudentRecord
END-READ
END-PERFORM.

M
M
M
M

0
0
0
0

5
6
5
2

1
8
1
1

WRITE Syntax.
WRITE RecordName FROM Identifier

LINE

AdvanceNum

LINES


BEFORE


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.

How the WRITE works


OPEN
OPEN OUTPUT
OUTPUT StudentFile.
StudentFile.
MOVE
"9334567Frank
MOVE "9334567Frank Curtain
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
9 3 3 4 5 6 7

StudentName
F r a n k

C u r t a i n

Course.
L M 0 5 1

Students.Dat
9 3 3 4 5 6 7 F r a n k

EO
F

C u r t a i n

L M 0 5 1

How the WRITE works


OPEN
OPEN OUTPUT
OUTPUT StudentFile.
StudentFile.
MOVE
"9334567Frank
MOVE "9334567Frank Curtain
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
9 3 8 3 7 1 5

StudentName
T h o ma s

H e a l y

Course.
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
9 3 8 3 7 1 5 T h o ma s
H e a l y

EO
F

L M 0 5 1
L M 0 6 8

$ 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.
DIVISION.
INPUT-OUTPUT
INPUT-OUTPUT
FILE-CONTROL. SECTION.
FILE-CONTROL.
SELECT StudentFile ASSIGN TO "STUDENTS.DAT"
SELECT
StudentFile
TO "STUDENTS.DAT"
ORGANIZATION
IS ASSIGN
LINE SEQUENTIAL.
ORGANIZATION IS LINE SEQUENTIAL.
DATA DIVISION.
DATASECTION.
DIVISION.
FILE
FILE
SECTION.
FD
StudentFile.
FD
StudentFile.
01 StudentDetails.
0102
StudentDetails.
StudentId
PIC 9(7).
02
StudentId
PIC 9(7).
02 StudentName.
02 03
StudentName.
Surname
PIC X(8).
03Initials
Surname
PICXX.
X(8).
03
PIC
03
Initials
PIC
XX.
02 DateOfBirth.
02 03
DateOfBirth.
YOBirth
PIC 9(2).
03MOBirth
YOBirth
PIC9(2).
9(2).
03
PIC
03
MOBirth
PIC
9(2).
03 DOBirth
PIC 9(2).
03
DOBirth
PIC
9(2).
02 CourseCode
PIC X(4).
02
CourseCode
PIC
X(4).
02 Grant
PIC 9(4).
02
Grant
PIC
9(4).
02 Gender
PIC X.
02 Gender
PIC X.
PROCEDURE DIVISION.
PROCEDURE DIVISION.
Begin.
Begin.
OPEN OUTPUT StudentFile.
OPEN OUTPUT
StudentFile.
DISPLAY
"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
WRITE
PERFORM StudentDetails
GetStudentDetails
PERFORM GetStudentDetails
END-PERFORM.
END-PERFORM.
CLOSE
StudentFile.
CLOSE
StudentFile.
STOP
RUN.
STOP RUN.
GetStudentDetails.
GetStudentDetails.
DISPLAY "NNNNNNNSSSSSSSSIIYYMMDDCCCCGGGGS".
DISPLAYStudentDetails.
"NNNNNNNSSSSSSSSIIYYMMDDCCCCGGGGS".
ACCEPT
ACCEPT StudentDetails.

$ SET SOURCEFORMAT"FREE"
$ SET SOURCEFORMAT"FREE"
IDENTIFICATION
DIVISION.
IDENTIFICATION
DIVISION.
PROGRAM-ID. SeqRead.
PROGRAM-ID.
SeqRead.
AUTHOR. Michael Coughlan.
AUTHOR. Michael Coughlan.
ENVIRONMENT DIVISION.
ENVIRONMENT SECTION.
DIVISION.
INPUT-OUTPUT
INPUT-OUTPUT
FILE-CONTROL. SECTION.
FILE-CONTROL.
SELECT StudentFile ASSIGN TO STUDENTS.DAT
SELECT
StudentFile
TO STUDENTS.DAT
ORGANIZATION
IS ASSIGN
LINE SEQUENTIAL.
ORGANIZATION IS LINE SEQUENTIAL.
DATA DIVISION.
DATASECTION.
DIVISION.
FILE
FILE
SECTION.
FD StudentFile.
FD
StudentFile.
01 StudentDetails.
0102
StudentDetails.
StudentId
PIC 9(7).
02 StudentName.
StudentId
PIC 9(7).
02
02 03
StudentName.
Surname
PIC X(8).
03Initials
Surname
PICXX.
X(8).
03
PIC
03
Initials
PIC
XX.
02 DateOfBirth.
02 03
DateOfBirth.
YOBirth
PIC 9(2).
03MOBirth
YOBirth
PIC9(2).
9(2).
03
PIC
03
MOBirth
PIC
9(2).
03 DOBirth
PIC 9(2).
03 DOBirth
PICX(4).
9(2).
02 CourseCode
PIC
02 Grant
CourseCode
PIC9(4).
X(4).
02
PIC
02
Grant
PIC
9(4).
02 Gender
PIC X.
02 Gender
PIC X.
PROCEDURE DIVISION.
PROCEDURE DIVISION.
Begin.
Begin.
OPEN INPUT StudentFile
OPENStudentFile
INPUT StudentFile
READ
READ
StudentFile
AT END
MOVE HIGH-VALUES TO StudentDetails
AT END MOVE HIGH-VALUES TO StudentDetails
END-READ
END-READ
PERFORM
UNTIL StudentDetails = HIGH-VALUES
PERFORMStudentId
UNTIL StudentDetails
= HIGH-VALUES
DISPLAY
SPACE StudentName
SPACE CourseCode
DISPLAY
StudentId
SPACE
StudentName
SPACE CourseCode
READ StudentFile
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
StudentFile
STOP
RUN.
STOP RUN.

Processin
g
Sequential
Files

$ SET SOURCEFORMAT"FREE"
$ SET SOURCEFORMAT"FREE"
IDENTIFICATION
DIVISION.
IDENTIFICATION
DIVISION.
PROGRAM-ID. SeqWrite.
PROGRAM-ID.
SeqWrite.
Enter student details using template below. AUTHOR.
Press CRMichael
to end.
Coughlan.
Enter
student
details
using
template
below.
Press
CR
to
end.
AUTHOR.
Michael
Coughlan.
NNNNNNNSSSSSSSSIIYYMMDDCCCCGGGGS
NNNNNNNSSSSSSSSIIYYMMDDCCCCGGGGS
ENVIRONMENT DIVISION.
9456789COUGHLANMS580812LM510598M
ENVIRONMENT SECTION.
DIVISION.
INPUT-OUTPUT
9456789COUGHLANMS580812LM510598M
NNNNNNNSSSSSSSSIIYYMMDDCCCCGGGGS
INPUT-OUTPUT
SECTION.
FILE-CONTROL.
NNNNNNNSSSSSSSSIIYYMMDDCCCCGGGGS
FILE-CONTROL.
9367892RYAN
TG521210LM601222F
SELECT StudentFile ASSIGN TO "STUDENTS.DAT"
9367892RYAN
TG521210LM601222F
SELECT
StudentFile
TO "STUDENTS.DAT"
NNNNNNNSSSSSSSSIIYYMMDDCCCCGGGGS
ORGANIZATION
IS ASSIGN
LINE SEQUENTIAL.
NNNNNNNSSSSSSSSIIYYMMDDCCCCGGGGS
ORGANIZATION
IS
LINE
SEQUENTIAL.
9368934WILSON HR520323LM610786M
9368934WILSON HR520323LM610786M
DATA DIVISION.
NNNNNNNSSSSSSSSIIYYMMDDCCCCGGGGS
DATASECTION.
DIVISION.
FILE
NNNNNNNSSSSSSSSIIYYMMDDCCCCGGGGS
CarriageReturn
FILE
SECTION.
FD
StudentFile.
CarriageReturn
FDStudentDetails.
StudentFile.
01
0102
StudentDetails.
StudentId
PIC 9(7).
02 StudentName.
StudentId
PIC 9(7).
02
02 03
StudentName.
Surname
PIC X(8).
03Initials
Surname
PICXX.
X(8).
03
PIC
03 Initials
PIC XX.
02 DateOfBirth.
02 03
DateOfBirth.
YOBirth
PIC 9(2).
03MOBirth
YOBirth
PIC9(2).
9(2).
03
PIC
03
MOBirth
PIC
9(2).
03 DOBirth
PIC 9(2).
03 DOBirth
PICX(4).
9(2).
02 CourseCode
PIC
02 Grant
CourseCode
PIC9(4).
X(4).
02
PIC
02
Grant
PIC
9(4).
02 Gender
PIC X.
PROCEDURE DIVISION.
02 Gender
PIC X.

Run of SeqWrite

PROCEDURE DIVISION.
Begin.
Begin.
OPEN OUTPUT StudentFile
OPEN OUTPUT
StudentFile
DISPLAY
"Enter
student details using template below. Press CR to end.".
DISPLAY
"Enter
student details using template below. Press CR to end.".
PERFORM GetStudentDetails
PERFORMUNTIL
GetStudentDetails
PERFORM
StudentDetails = SPACES
PERFORM
StudentDetails = SPACES
WRITE UNTIL
StudentDetails
WRITE
StudentDetails
PERFORM GetStudentDetails
PERFORM GetStudentDetails
END-PERFORM
END-PERFORM
CLOSE StudentFile
CLOSE
StudentFile
STOP
RUN.
STOP RUN.
GetStudentDetails.
GetStudentDetails.
DISPLAY "NNNNNNNSSSSSSSSIIYYMMDDCCCCGGGGS".
DISPLAYStudentDetails.
"NNNNNNNSSSSSSSSIIYYMMDDCCCCGGGGS".
ACCEPT
ACCEPT StudentDetails.

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

$ SET SOURCEFORMAT"FREE"
$ SET SOURCEFORMAT"FREE"
IDENTIFICATION
DIVISION.
IDENTIFICATION
DIVISION.
PROGRAM-ID.
SeqRead.
PROGRAM-ID.
SeqRead.
AUTHOR. Michael Coughlan.
AUTHOR. Michael Coughlan.
ENVIRONMENT DIVISION.
ENVIRONMENT SECTION.
DIVISION.
INPUT-OUTPUT
INPUT-OUTPUT SECTION.
FILE-CONTROL.
FILE-CONTROL.
SELECT StudentFile ASSIGN TO "STUDENTS.DAT"
SELECT
StudentFile
TO "STUDENTS.DAT"
ORGANIZATION
IS ASSIGN
LINE SEQUENTIAL.
ORGANIZATION IS LINE SEQUENTIAL.
DATA DIVISION.
DATASECTION.
DIVISION.
FILE
FILE
SECTION.
FD StudentFile.
FDStudentDetails.
StudentFile.
01
0102
StudentDetails.
StudentId
PIC 9(7).
02 StudentName.
StudentId
PIC 9(7).
02
02 03
StudentName.
Surname
PIC X(8).
03Initials
Surname
PICXX.
X(8).
03
PIC
03
Initials
PIC
XX.
02 DateOfBirth.
02 03
DateOfBirth.
YOBirth
PIC 9(2).
03MOBirth
YOBirth
PIC9(2).
9(2).
03
PIC
03
MOBirth
PIC
9(2).
03 DOBirth
PIC 9(2).
03
DOBirth
PIC
9(2).
02 CourseCode
PIC X(4).
02 Grant
CourseCode
PIC9(4).
X(4).
02
PIC
02 Gender
Grant
PICX.
9(4).
02
PIC
02 Gender
PIC X.

PROCEDURE DIVISION.
PROCEDURE DIVISION.
Begin.
Begin.
OPEN INPUT StudentFile
OPENStudentFile
INPUT StudentFile
READ
READ
AT StudentFile
END MOVE HIGH-VALUES TO StudentDetails
AT END MOVE HIGH-VALUES TO StudentDetails
END-READ
END-READ
PERFORM
UNTIL StudentDetails = HIGH-VALUES
PERFORM
UNTIL
StudentDetails
= HIGH-VALUES
DISPLAY
StudentId
SPACE StudentName
SPACE CourseCode
DISPLAY
StudentId
SPACE
StudentName
SPACE CourseCode
READ StudentFile
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
StudentFile
STOP
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.

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.

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.

Adding records to unordered files


Transaction
File

PROGRAM

RecordF
RecordF

FILE
FILE SECTION.
SECTION.
PROGRAM

RecordP
RecordP
RecordW
RecordW

TFRec
UFRec

PROCEDURE
PROCEDURE DIVISION.
DIVISION.
OPEN
OPEN EXTEND
EXTEND UF.
UF.

OPEN
OPEN INPUT
INPUT TF.
TF.
READ
READ TF.
TF.
MOVE
TFRec
MOVE TFRec TO
TO UFRec.
UFRec.
WRITE
WRITE UFRec.
UFRec.

Unordered
File
RecordM
RecordM
RecordH
RecordH
RecordB
RecordB
RecordN
RecordN
RecordA
RecordA
RecordK
RecordK
RecordG
RecordG

Adding records to unordered files


Transaction
File
RecordF
RecordF
RecordP
RecordP
RecordW
RecordW

PROGRAM
FILE
FILE SECTION.
SECTION.
PROGRAM

RecordF
RecordF

PROCEDURE
PROCEDURE DIVISION.
DIVISION.
OPEN
OPEN EXTEND
EXTEND UF.
UF.

OPEN
OPEN INPUT
INPUT TF.
TF.
READ
READ TF.
TF.
MOVE
TFRec
MOVE TFRec TO
TO UFRec.
UFRec.
WRITE
WRITE UFRec.
UFRec.

Unordered
File
RecordM
RecordM
RecordH
RecordH
RecordB
RecordB
RecordN
RecordN
RecordA
RecordA
RecordK
RecordK
RecordG
RecordG
RecordF
RecordF

Adding records to unordered files


Transaction
File

Unordered
File

RecordF
RecordF
RecordP
RecordP

RecordM
RecordM

RecordW
RecordW

RecordB
RecordB

RecordH
RecordH
RecordN
RecordN

RESULT

RecordA
RecordA
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

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?

Deleting records from unordered files?


Transaction File
RecordB
RecordB
RecordM
RecordM
RecordK
RecordK

New File
Delete UF
Record?

Unordered File
RecordM
RecordM
RecordH
RecordH
RecordB
RecordB
RecordN
RecordN
RecordA
RecordA
RecordK
RecordK

RecordM
RecordM

NO

Deleting records from unordered files?


Transaction File
RecordB
RecordB
RecordM
RecordM
RecordK
RecordK

New File
Delete UF
Record?

Unordered File
RecordM
RecordM
RecordH
RecordH
RecordB
RecordB
RecordN
RecordN
RecordA
RecordA
RecordK
RecordK

RecordM
RecordM

NO

RecordH
RecordH

Deleting records from unordered files?


Transaction File
RecordB
RecordB
RecordM
RecordM
RecordK
RecordK

New File
Delete UF
Record?

Unordered File
RecordM
RecordM
RecordH
RecordH
RecordB
RecordB
RecordN
RecordN
RecordA
RecordA
RecordK
RecordK

RecordM
RecordM

YES

RecordH
RecordH

Deleting records from unordered files?


Transaction File
RecordB
RecordB
RecordM
RecordM
RecordK
RecordK

New File
Delete UF
Record?

Unordered File
RecordM
RecordM
RecordH
RecordH
RecordB
RecordB
RecordN
RecordN
RecordA
RecordA
RecordK
RecordK

RecordM
RecordM

NO

RecordH
RecordH
RecordN
RecordN

But wait...
We should have deleted
RecordM. Too late. Its
already been written to the
new file.

Deleting records from an ordered file


Transaction File
RecordB
RecordB
RecordK
RecordK
RecordM
RecordM
Ordered File
RecordA
RecordA
RecordB
RecordB
RecordG
RecordG
RecordH
RecordH
RecordK
RecordK
RecordM
RecordM
RecordN
RecordN

PROGRAM
FILE
FILE SECTION.
SECTION.

TFRec
OFRec
NFRec
PROCEDURE
PROCEDURE DIVISION.
DIVISION.
OPEN
INPUT
OPEN INPUT TF.
TF.
OPEN
INPUT
OF
OPEN INPUT OF
OPEN
OPEN OUTPUT
OUTPUT NF.
NF.
READ
TF.
READ TF.
READ
READ OF.
OF.
IF
TFKey
IF TFKey NOT
NOT == OFKey
OFKey
MOVE
OFRec
TO
MOVE OFRec TO NFRec
NFRec
WRITE
NFRec
WRITE NFRec
READ
READ OF
OF
ELSE
ELSE
READ
READ TF
TF
READ
OF
READ OF
END-IF.
END-IF.

New File

Deleting records from an ordered file


Transaction File
RecordB
RecordB
RecordK
RecordK
RecordM
RecordM
Ordered File
RecordA
RecordA
RecordB
RecordB
RecordG
RecordG
RecordH
RecordH
RecordK
RecordK
RecordM
RecordM
RecordN
RecordN

PROGRAM
FILE
FILE SECTION.
SECTION.

RecordB

New File

RecordA
RecordA

RecordA
RecordA
PROCEDURE
PROCEDURE DIVISION.
DIVISION.
OPEN
INPUT
OPEN INPUT TF.
TF.
OPEN
INPUT
OF
OPEN INPUT OF
OPEN
OPEN OUTPUT
OUTPUT NF.
NF.
READ
TF.
READ TF.
READ
READ OF.
OF.
IF
TFRec
IF TFRec NOT
NOT == OFRec
OFRec
MOVE
OFRec
TO
MOVE OFRec TO NFRec
NFRec
WRITE
NFRec
WRITE NFRec
READ
READ OF
OF
ELSE
ELSE
READ
READ TF
TF
READ
OF
READ OF
END-IF.
END-IF.

Problem !!

How can we
recognize which
record we want to
delete?
By its Key Field

Deleting records from an ordered file


Transaction File
RecordB
RecordB
RecordK
RecordK
RecordM
RecordM
Ordered File
RecordA
RecordA
RecordB
RecordB
RecordG
RecordG
RecordH
RecordH
RecordK
RecordK
RecordM
RecordM
RecordN
RecordN

PROGRAM
FILE
FILE SECTION.
SECTION.

RecordB
RecordB
RecordA
PROCEDURE
PROCEDURE DIVISION.
DIVISION.
OPEN
INPUT
OPEN INPUT TF.
TF.
OPEN
INPUT
OF
OPEN INPUT OF
OPEN
OPEN OUTPUT
OUTPUT NF.
NF.
READ
TF.
READ TF.
READ
READ OF.
OF.
IF
TFKey
IF TFKey NOT
NOT == OFKey
OFKey
MOVE
OFRec
TO
MOVE OFRec TO NFRec
NFRec
WRITE
NFRec
WRITE NFRec
READ
READ OF
OF
ELSE
ELSE
READ
READ TF
TF
READ
OF
READ OF
END-IF.
END-IF.

New File

RecordA
RecordA

Deleting records from an ordered file


Transaction File
RecordB
RecordB
RecordK
RecordK
RecordM
RecordM
Ordered File
RecordA
RecordA
RecordB
RecordB
RecordG
RecordG
RecordH
RecordH
RecordK
RecordK
RecordM
RecordM
RecordN
RecordN

PROGRAM
FILE
FILE SECTION.
SECTION.

RecordK
RecordG
RecordG
PROCEDURE
PROCEDURE DIVISION.
DIVISION.
OPEN
INPUT
OPEN INPUT TF.
TF.
OPEN
INPUT
OF
OPEN INPUT OF
OPEN
OPEN OUTPUT
OUTPUT NF.
NF.
READ
TF.
READ TF.
READ
READ OF.
OF.
IF
TFKey
IF TFKey NOT
NOT == OFKey
OFKey
MOVE
OFRec
TO
MOVE OFRec TO NFRec
NFRec
WRITE
NFRec
WRITE NFRec
READ
READ OF
OF
ELSE
ELSE
READ
READ TF
TF
READ
OF
READ OF
END-IF.
END-IF.

New File

RecordA
RecordA
RecordG
RecordG

Deleting records from an ordered file


Transaction File

New File

RecordB
RecordB
RecordK
RecordK

RecordA
RecordA
RecordG
RecordG

RecordM
RecordM
Ordered File
RecordA
RecordA
RecordB
RecordB
RecordG
RecordG
RecordH
RecordH
RecordK
RecordK
RecordM
RecordM
RecordN
RecordN

RecordH
RecordH

RESULT

RecordN
RecordN

Updating records in an ordered file


Transaction File
RecordB
RecordB
RecordH
RecordH
RecordK
RecordK
Ordered File
RecordA
RecordA
RecordB
RecordB
RecordG
RecordG
RecordH
RecordH
RecordK
RecordK
RecordM
RecordM
RecordN
RecordN

PROGRAM
FILE
FILE SECTION.
SECTION.

TFRec
OFRec
NFRec
PROCEDURE
PROCEDURE DIVISION.
DIVISION.
OPEN
INPUT
OPEN INPUT TF.
TF.
OPEN
INPUT
OF
OPEN INPUT OF
OPEN
OPEN OUTPUT
OUTPUT NF.
NF.
READ
TF.
READ TF.
READ
READ OF.
OF.
IF
TFKey
IF TFKey == OFKey
OFKey
Update
OFRec
Update OFRec with
with TFRec
TFRec
MOVE
OFRec+
TO
NFRec
MOVE OFRec+ TO NFRec
WRITE
WRITE NFRec
NFRec
READ
TF
READ TF
READ
READ OF
OF
ELSE
ELSE
MOVE
MOVE OFRec
OFRec TO
TO NFRec
NFRec
WRITE
NFRec
WRITE NFRec
READ
READ OF
OF
END-IF.
END-IF.

New File

Updating records in an ordered file


Transaction File
RecordB
RecordB
RecordH
RecordH
RecordK
RecordK
Ordered File
RecordA
RecordA
RecordB
RecordB
RecordG
RecordG
RecordH
RecordH
RecordK
RecordK
RecordM
RecordM
RecordN
RecordN

PROGRAM
FILE
FILE SECTION.
SECTION.

RecordB
RecordA
RecordA
PROCEDURE
PROCEDURE DIVISION.
DIVISION.
OPEN
INPUT
OPEN INPUT TF.
TF.
OPEN
INPUT
OF
OPEN INPUT OF
OPEN
OPEN OUTPUT
OUTPUT NF.
NF.
READ
TF.
READ TF.
READ
READ OF.
OF.
IF
TFKey
IF TFKey == OFKey
OFKey
Update
OFRec
Update OFRec with
with TFRec
TFRec
MOVE
OFRec+
TO
NFRec
MOVE OFRec+ TO NFRec
WRITE
WRITE NFRec
NFRec
READ
TF
READ TF
READ
READ OF
OF
ELSE
ELSE
MOVE
MOVE OFRec
OFRec TO
TO NFRec
NFRec
WRITE
NFRec
WRITE NFRec
READ
READ OF
OF
END-IF.
END-IF.

New File
RecordA
RecordA

Updating records in an ordered file


Transaction File
RecordB
RecordB
RecordH
RecordH
RecordK
RecordK
Ordered File
RecordA
RecordA
RecordB
RecordB
RecordG
RecordG
RecordH
RecordH
RecordK
RecordK
RecordM
RecordM
RecordN
RecordN

PROGRAM
FILE
FILE SECTION.
SECTION.

RecordB
RecordB
RecordB+
PROCEDURE
PROCEDURE DIVISION.
DIVISION.
OPEN
INPUT
OPEN INPUT TF.
TF.
OPEN
INPUT
OF
OPEN INPUT OF
OPEN
OPEN OUTPUT
OUTPUT NF.
NF.
READ
TF.
READ TF.
READ
READ OF.
OF.
IF
TFKey
IF TFKey == OFKey
OFKey
Update
OFRec
Update OFRec with
with TFRec
TFRec
MOVE
OFRec+
TO
NFRec
MOVE OFRec+ TO NFRec
WRITE
WRITE NFRec
NFRec
READ
TF
READ TF
READ
READ OF
OF
ELSE
ELSE
MOVE
MOVE OFRec
OFRec TO
TO NFRec
NFRec
WRITE
NFRec
WRITE NFRec
READ
READ OF
OF
END-IF.
END-IF.

New File
RecordA
RecordA
RecordB+
RecordB+

Updating records in an ordered file


Transaction File
RecordB
RecordB
RecordH
RecordH
RecordK
RecordK
Ordered File
RecordA
RecordA
RecordB
RecordB
RecordG
RecordG
RecordH
RecordH
RecordK
RecordK
RecordM
RecordM
RecordN
RecordN

PROGRAM
FILE
FILE SECTION.
SECTION.

RecordH
RecordG
RecordG
PROCEDURE
PROCEDURE DIVISION.
DIVISION.
OPEN
INPUT
OPEN INPUT TF.
TF.
OPEN
INPUT
OF
OPEN INPUT OF
OPEN
OPEN OUTPUT
OUTPUT NF.
NF.
READ
TF.
READ TF.
READ
READ OF.
OF.
IF
TFKey
IF TFKey == OFKey
OFKey
Update
OFRec
Update OFRec with
with TFRec
TFRec
MOVE
OFRec+
TO
NFRec
MOVE OFRec+ TO NFRec
WRITE
WRITE NFRec
NFRec
READ
TF
READ TF
READ
READ OF
OF
ELSE
ELSE
MOVE
MOVE OFRec
OFRec TO
TO NFRec
NFRec
WRITE
NFRec
WRITE NFRec
READ
READ OF
OF
END-IF.
END-IF.

New File
RecordA
RecordA
RecordB+
RecordB+
RecordG
RecordG

Inserting records into an ordered file


Transaction File
RecordC
RecordC
RecordF
RecordF
RecordP
RecordP
Ordered File
RecordA
RecordA
RecordB
RecordB
RecordG
RecordG
RecordH
RecordH
RecordK
RecordK
RecordM
RecordM
RecordN
RecordN

PROGRAM
FILE
FILE SECTION.
SECTION.

TFRec
OFRec
NFRec
PROCEDURE
PROCEDURE DIVISION.
DIVISION.
OPEN
INPUT
OPEN INPUT TF.
TF.
OPEN
INPUT
OF
OPEN INPUT OF
OPEN
OPEN OUTPUT
OUTPUT NF.
NF.
READ
TF.
READ TF.
READ
READ OF.
OF.
IF
TFKey
IF TFKey << OFKey
OFKey
MOVE
TFRec
MOVE TFRec TO
TO NFRec
NFRec
WRITE
NFRec
WRITE NFRec
READ
READ TF
TF
ELSE
ELSE
MOVE
MOVE OFRec
OFRec TO
TO NFRec
NFRec
WRITE
NFRec
WRITE NFRec
READ
READ OF
OF
END-IF.
END-IF.

New File

Inserting records into an ordered file


Transaction File
RecordC
RecordC
RecordF
RecordF
RecordP
RecordP
Ordered File
RecordA
RecordA
RecordB
RecordB
RecordG
RecordG
RecordH
RecordH
RecordK
RecordK
RecordM
RecordM
RecordN
RecordN

PROGRAM
FILE
FILE SECTION.
SECTION.

RecordC
RecordA
RecordA
PROCEDURE
PROCEDURE DIVISION.
DIVISION.
OPEN
INPUT
OPEN INPUT TF.
TF.
OPEN
INPUT
OF
OPEN INPUT OF
OPEN
OPEN OUTPUT
OUTPUT NF.
NF.
READ
TF.
READ TF.
READ
READ OF.
OF.
IF
TFKey
IF TFKey << OFKey
OFKey
MOVE
TFRec
MOVE TFRec TO
TO NFRec
NFRec
WRITE
NFRec
WRITE NFRec
READ
READ TF
TF
ELSE
ELSE
MOVE
MOVE OFRec
OFRec TO
TO NFRec
NFRec
WRITE
NFRec
WRITE NFRec
READ
READ OF
OF
END-IF.
END-IF.

New File
RecordA
RecordA

Inserting records into an ordered file


Transaction File
RecordC
RecordC
RecordF
RecordF
RecordP
RecordP
Ordered File
RecordA
RecordA
RecordB
RecordB
RecordG
RecordG
RecordH
RecordH
RecordK
RecordK
RecordM
RecordM
RecordN
RecordN

PROGRAM
FILE
FILE SECTION.
SECTION.

RecordC
RecordB
RecordB
PROCEDURE
PROCEDURE DIVISION.
DIVISION.
OPEN
INPUT
OPEN INPUT TF.
TF.
OPEN
INPUT
OF
OPEN INPUT OF
OPEN
OPEN OUTPUT
OUTPUT NF.
NF.
READ
TF.
READ TF.
READ
READ OF.
OF.
IF
TFKey
IF TFKey << OFKey
OFKey
MOVE
TFRec
MOVE TFRec TO
TO NFRec
NFRec
WRITE
NFRec
WRITE NFRec
READ
READ TF
TF
ELSE
ELSE
MOVE
MOVE OFRec
OFRec TO
TO NFRec
NFRec
WRITE
NFRec
WRITE NFRec
READ
READ OF
OF
END-IF.
END-IF.

New File
RecordA
RecordA
RecordB
RecordB

Inserting records into an ordered file


Transaction File
RecordC
RecordC
RecordF
RecordF
RecordP
RecordP
Ordered File
RecordA
RecordA
RecordB
RecordB
RecordG
RecordG
RecordH
RecordH
RecordK
RecordK
RecordM
RecordM
RecordN
RecordN

PROGRAM
FILE
FILE SECTION.
SECTION.

RecordC
RecordG
RecordC
PROCEDURE
PROCEDURE DIVISION.
DIVISION.
OPEN
INPUT
OPEN INPUT TF.
TF.
OPEN
INPUT
OF
OPEN INPUT OF
OPEN
OPEN OUTPUT
OUTPUT NF.
NF.
READ
TF.
READ TF.
READ
READ OF.
OF.
IF
TFKey
IF TFKey << OFKey
OFKey
MOVE
TFRec
MOVE TFRec TO
TO NFRec
NFRec
WRITE
NFRec
WRITE NFRec
READ
READ TF
TF
ELSE
ELSE
MOVE
MOVE OFRec
OFRec TO
TO NFRec
NFRec
WRITE
NFRec
WRITE NFRec
READ
READ OF
OF
END-IF.
END-IF.

New File
RecordA
RecordA
RecordB
RecordB
RecordC
RecordC

Inserting records into an ordered file


Transaction File
RecordC
RecordC
RecordF
RecordF
RecordP
RecordP
Ordered File
RecordA
RecordA
RecordB
RecordB
RecordG
RecordG
RecordH
RecordH
RecordK
RecordK
RecordM
RecordM
RecordN
RecordN

PROGRAM
FILE
FILE SECTION.
SECTION.

RecordF
RecordG
RecordF
PROCEDURE
PROCEDURE DIVISION.
DIVISION.
OPEN
INPUT
OPEN INPUT TF.
TF.
OPEN
INPUT
OF
OPEN INPUT OF
OPEN
OPEN OUTPUT
OUTPUT NF.
NF.
READ
TF.
READ TF.
READ
READ OF.
OF.
IF
TFKey
IF TFKey << OFKey
OFKey
MOVE
TFRec
MOVE TFRec TO
TO NFRec
NFRec
WRITE
NFRec
WRITE NFRec
READ
READ TF
TF
ELSE
ELSE
MOVE
MOVE OFRec
OFRec TO
TO NFRec
NFRec
WRITE
NFRec
WRITE NFRec
READ
READ OF
OF
END-IF.
END-IF.

New File
RecordA
RecordA
RecordB
RecordB
RecordC
RecordC
RecordF
RecordF

Inserting records into an ordered file


Transaction File
RecordC
RecordC
RecordF
RecordF
RecordP
RecordP
Ordered File
RecordA
RecordA
RecordB
RecordB
RecordG
RecordG
RecordH
RecordH
RecordK
RecordK
RecordM
RecordM
RecordN
RecordN

PROGRAM
FILE
FILE SECTION.
SECTION.

RecordP
RecordG
RecordG
PROCEDURE
PROCEDURE DIVISION.
DIVISION.
OPEN
INPUT
OPEN INPUT TF.
TF.
OPEN
INPUT
OF
OPEN INPUT OF
OPEN
OPEN OUTPUT
OUTPUT NF.
NF.
READ
TF.
READ TF.
READ
READ OF.
OF.
IF
TFKey
IF TFKey << OFKey
OFKey
MOVE
TFRec
MOVE TFRec TO
TO NFRec
NFRec
WRITE
NFRec
WRITE NFRec
READ
READ TF
TF
ELSE
ELSE
MOVE
MOVE OFRec
OFRec TO
TO NFRec
NFRec
WRITE
NFRec
WRITE NFRec
READ
READ OF
OF
END-IF.
END-IF.

New File
RecordA
RecordA
RecordB
RecordB
RecordC
RecordC
RecordF
RecordF
RecordG
RecordG

Advanced
Sequential
Files 1.

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.

Multiple Record Type 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.

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

Describing multiple record files

To describe 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.

Multiple record descriptions - One record buffer


DATA DIVISION.
FILE SECTION.
FD TransactionFile.
01 InsertionRec.
02 StudentId
02 StudentName.
03 Surname
03 Initials
02 DateOfBirth.
03 YOBirth
03 MOBirth
03 DOBirth
02 CourseCode
02 Grant
02 Gender

PIC 9(7).
PIC X(8).
PIC XX.
PIC
PIC
PIC
PIC
PIC
PIC

What is not
obvious from this
description is that
COBOL continues to
create just a single
record buffer for
the file!

And this record


buffer is only able
to store a single
record at a time!

9(2).
9(2).
9(2).
X(4).
9(4).
X.

01 DeleteRec.
02 StudentId

PIC 9(7).

01 UpdateRec.
02 StudentId
02 OldCourseCode
02 NewCourseCode

PIC 9(7).
PIC X(4).
PIC X(4).

Multiple record descriptions in a file are IMPLICITLY


redefinitions of the single record buffer.

TransactionFile Buffer

9 2 3 0 1 6 5 H E N N E S SYR M 7 1 0 9 1 5 LM 5 1 0 5 5 0 F

Multiple record descriptions in a file are IMPLICITLY


redefinitions of the single record buffer.

TransactionFile Buffer
InsertionRec
StudentId StudentName

DateOfBirth CourseCode

Grant Gender

9 2 3 0 1 6 5 H E N N E S SYR M 7 1 0 9 1 5 LM 5 1 0 5 5 0 F

Multiple record descriptions in a file are IMPLICITLY


redefinitions of the single record buffer.

TransactionFile Buffer
InsertionRec
StudentId StudentName

DateOfBirth CourseCode

Grant Gender

9 2 3 0 1 6 5 H E N N E S SYR M 7 1 0 9 1 5 LM 5 1 0 5 5 0 F
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

9 2 3 0 1 6 5 H E N N E S SYR M 7 1 0 9 1 5 LM 5 1 0 5 5 0 F
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

9 2 3 0 1 6 5 H E N N E S SYR M 7 1 0 9 1 5 LM 5 1 0 5 5 0 F
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.

The Revised FD.

DATA DIVISION.
FILE SECTION.
FD TransactionFile.
01 InsertionRec.
02 TransCode
02 StudentId
02 StudentName.
03 Surname
03 Initials
02 DateOfBirth.
03 YOBirth
03 MOBirth
03 DOBirth
02 CourseCode
02 Grant
02 Gender

PIC X.
PIC 9(7).

PIC X(8).
PIC XX.

PIC
PIC
PIC
PIC
PIC
PIC

9(2).
9(2).
9(2).
X(4).
9(4).
X.

01 DeleteRec.
02 TransCode
02 StudentId

PIC X.
PIC 9(7).

01 UpdateRec.
02 TransCode
02 StudentId
02 OldCourseCode
02 NewCourseCode

PIC
PIC
PIC
PIC

X.
9(7).
X(4).
X(4).

TransCode occurs in all


the record descriptions.
How can we refer to the
one in DeleteRec?
MOVE TransCode OF
DeleteRec TO TCode.
But TransCode really
only needs to be defined
in one record.
Since all the records
map on to the same area
of storage the TransCode
defined for the
InsertionRec can be
used no matter which
record type is actually in
the buffer .

The Final FD.


DATA DIVISION.
FILE SECTION.
FD TransactionFile.
01 InsertionRec.
88 EndOfTransFile
02 TransCode
88 Insertion
88 Deletion
88 Update
02 StudentId
02 StudentName.
03 Surname
03 Initials
02 DateOfBirth.
03 YOBirth
03 MOBirth
03 DOBirth
02 CourseCode
02 Grant
02 Gender

VALUE HIGH-VALUES.
PIC X.
VALUE "I".
VALUE "D".
VALUE "U".
PIC 9(7).

TransCode and
StudentId have the
same description
and are in the same
location in all three
records.

So they are defined


only in the
InsertionRec.

In the other records


the area occupied
by these two items
is defined using
FILLER.

PIC X(8).
PIC XX.
PIC
PIC
PIC
PIC
PIC
PIC

9(2).
9(2).
9(2).
X(4).
9(4).
X.

01 DeleteRec.
02 FILLER

PIC X(8).

01 UpdateRec.
02 FILLER
02 OldCourseCode
02 NewCourseCode

PIC X(8).
PIC X(4).
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

I 9 2 3 0 1 6 5 H E N N E S SYR M 7 1 0 9 1 5 LM 5 1 0 5 5 0 F
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

U 9 3 1 5 6 8 2 LM 6 1 LM 5 1 R M 7 1 0 9 1 5 LM 5 1 0 5 5 0 F
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?

Report Print Lines.

Page Heading.

Page Footing.

Student Id. Student Name Gender Course

Student Detail Line.

Page : PageNum

Column Headings.

UL Student Details Report

StudentId. StudentName Gender CourseCode

Report Footing.

*** End of Student Details Report ***

Describing Print Lines.


01

PageHeading.
02 FILLER
PIC X(7) VALUE SPACES.
02 FILLER
PIC X(25)
VALUE "UL Student Details Report".

01

PageFooting.
02 FILLER
02 FILLER
02 FILLER

01

ColumnHeadings PIC X(36)


VALUE " StudentId StudentName Gender Course".

01

StudentDetailLine.
02 PrnStudId
PIC
02 PrnStudName PIC
02 PrnGender
PIC
02 PrnCourse
PIC

01

ReportFooting
PIC X(38)
VALUE "*** End of Student Details Report ***".

PIC X(19) VALUE SPACES.


PIC X(7) VALUE "Page : ".
PIC 99.

BB9(7).
BBX(10).
BBBBX.
BBBBX(4).

The Print Lines are all different record types!

The File 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


with the physical device by
means of a Select and
Assign clause.

ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT Printer
ASSIGN TO LPT1.
DATA DIVISION.
FILE SECTION.
FD Printer.
01 PrintLine.
????????????????

In previous
lectures we saw
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?

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

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.

ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT ReportFile ASSIGN TO STUDENTS.RPT.
DATA DIVISION.
FILE SECTION.
FD ReportFile.
01 PrintLine
PIC X(38).
DISK
WORKING-STORAGE SECTION.
01 PageHeading.
STUDENTS.RPT
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 ***".

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.
WRITE RecordName FROM Identifier

BEFORE

AFTER

LINE
AdvanceNum

LINES

ADVANCING MnemonicName

PAGE

ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT ReportFile ASSIGN TO "STUDENTS.RPT"
ORGANIZATION IS LINE SEQUENTIAL.
DATA DIVISION.
FILE SECTION.
FD ReportFile.
01 PrintLine
PIC X(40).
WORKING-STORAGE SECTION.
01 HeadingLine
PIC X(21) VALUE " Record Count
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
MOVE MaleCount
TO
MOVE FemaleCount TO
WRITE PrintLine FROM
WRITE PrintLine FROM
WRITE PrintLine FROM
WRITE PrintLine FROM

PrnStudentCount
PrnMaleCount
PrnFemaleCount
HeadingLine
StudentTotalLine
MaleTotalLine
FemaleTotalLine

AFTER
AFTER
AFTER
AFTER

DISK
STUDENTS.RPT

Report".
= ".
= ".
= ".

ADVANCING
ADVANCING
ADVANCING
ADVANCING

PAGE
2 LINES
2 LINES
2 LINES.

Introduction to
Direct Access
Files.

Sequential Files - Adding a Record


Ordered

Rec001
Rec005
Rec045
Rec090
Rec100
Rec150
Rec300
Rec325
^Z

Rec085

Unordered

Rec300
Rec150
Rec005
Rec090
Rec045
Rec100
Rec001
Rec325
^Z

Sequential Files - Adding a Record


New-Ordered

Rec001
Rec005
Rec045
Rec085
Rec090
Rec100
Rec150
Rec300
Rec325
^Z

Rec085

Extend-Unordered

Rec300
Rec150
Rec005
Rec090
Rec045
Rec100
Rec001
Rec325
Rec085
^Z

Sequential Files - Deleting a Record


Ordered

Rec001
Rec005
Rec045
Rec090
Rec100
Rec150
Rec300
Rec325
^Z

Rec150

Unordered

Rec300
Rec150
Rec005
Rec090
Rec045
Rec100
Rec001
Rec325
^Z

Sequential Files - Deleting a Record


New-Ordered

Rec001
Rec005
Rec045
Rec090
Rec100
Rec300
Rec325
^Z

Rec150

New-Unordered

Rec300
Rec005
Rec090
Rec045
Rec100
Rec001
Rec325
^Z

Sequential Files - Amending a Record


Ordered

Rec001
Rec005
Rec045
Rec090
Rec100
Rec150
Rec300
Rec325
^Z

Rec045

Unordered

Rec300
Rec150
Rec005
Rec090
Rec045
Rec100
Rec001
Rec325
^Z

Sequential Files - Amending a Record


New-Ordered

Rec001
Rec005
Rec045
Rec090
Rec100
Rec150
Rec300
Rec325
^Z

Rec045

New-Unordered

Rec300
Rec150
Rec005
Rec090
Rec045
Rec100
Rec001
Rec325
^Z

Relative Files - Organization


1
2
3
Relative
Record
Number

4
5
6
7

325
326
327
328

Rec001
free
Rec003
Rec004
free
free
Rec007
Rec325
Rec326
free
Rec328

Relative Files - Adding a Record


1
2
3
Relative
Record
Number

4
5
6
7

325
326
327
328

Rec001
free
Rec003
Rec004
free
free
Rec007
Rec325
Rec326
free
Rec328

Rec327

Relative Files - Adding a Record


1
2
3
Relative
Record
Number

4
5
6
7

325
326
327
328

Rec001
free
Rec003
Rec004
free
free
Rec007
Rec325
Rec326
Rec327
Rec328

Rec327

Relative Files - Deleting a Record


1
2
3
Relative
Record
Number

4
5
6
7

325
326
327
328

Rec001
free
Rec003
Rec004
free
free
Rec007
Rec325
Rec326
free
Rec328

Rec325

Relative Files - Deleting a Record


1
2
3
Relative
Record
Number

4
5
6
7

325
326
327
328

Rec001
free
Rec003
Rec004
free
free
Rec007
deleted/free
Rec326
free
Rec328

Rec325

Relative Files - Amending a Record


1
2
3
Relative
Record
Number

4
5
6
7

325
326
327
328

Rec001
free
Rec003
Rec004
free
free
Rec007
Rec325
Rec326
free
Rec328

Rec007

Relative Files - Amending a Record


1
2
3
Relative
Record
Number

4
5
6
7

325
326
327
328

Rec001
free
Rec003
Rec004
free
free
Rec007
Rec325
Rec326
free
Rec328

Rec007

Indexed Files - Organization


H R Z
Index Records

C F H

L O R

Mi Nf Ni Nt Oi Ot

Data Records

T W Z

Indexed Files - Reading Record Ni


H R Z
Index Records

C F H

L O R

Mi Nf Ni Nt Oi Ot

Data Records

T W Z

Indexed Files - Reading Record Ni


H R Z
Index Records

C F H

L O R

Mi Nf Ni Nt Oi Ot

Data Records

T W Z

Indexed Files - Reading Record Ni


H R Z
Index Records

C F H

L O R

Mi Nf Ni Nt Oi Ot

Data Records

T W Z

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.

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.

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.

Can partially recover space from deleted records.

Relative
Files.

Creating a Relative 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
KEY
IS
RELATIVE KEY IS SupplierKey
SupplierKey
FILE
FILE STATUS
STATUS IS
IS SupplierStatus.
SupplierStatus.
SELECT
SELECT SupplierFileSeq
SupplierFileSeq ASSIGN
ASSIGN TO
TO "INSUPP.DAT".
"INSUPP.DAT".
DATA
DATA DIVISION.
DIVISION.
FILE
SECTION.
FILE SECTION.
FD
FD SupplierFile.
SupplierFile.
01
SupplierRecord.
01 SupplierRecord.
02
PIC
02 SupplierCode
SupplierCode
PIC 99.
99.
02
SupplierName
PIC
X(20).
02 SupplierName
PIC X(20).
02
PIC
02 SupplierAddress
SupplierAddress
PIC X(60).
X(60).
FD
FD SupplierFileSeq.
SupplierFileSeq.
01
SupplierRecordSeq.
01 SupplierRecordSeq.
88
VALUE
88 EndOfFile
EndOfFile
VALUE HIGH-VALUES.
HIGH-VALUES.
02
SupplierCodeSeq
PIC
02 SupplierCodeSeq
PIC 99.
99.
02
SupplierNameSeq
PIC
X(20).
02 SupplierNameSeq
PIC X(20).
02
PIC
02 SupplierAddressSeq
SupplierAddressSeq
PIC X(60).
X(60).
WORKING-STORAGE
WORKING-STORAGE SECTION.
SECTION.
01
SupplierStatus
PIC
01 SupplierStatus
PIC X(2).
X(2).
01
SupplierKey
PIC
99.
01 SupplierKey
PIC 99.

Creating a Relative 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
KEY
IS
RELATIVE KEY IS SupplierKey
SupplierKey
FILE
SupplierStatus
FILE STATUS
STATUS IS
IS SupplierStatus.
SupplierStatus.
SupplierStatus
SELECT
SupplierFileSeq
SELECT SupplierFileSeq ASSIGN
ASSIGN TO
TO "INSUPP.DAT".
"INSUPP.DAT".
DATA
DATA DIVISION.
DIVISION.
FILE
SECTION.
FILE SECTION.
FD
FD SupplierFile.
SupplierFile.
01
SupplierRecord.
01 SupplierRecord.
02
PIC
02 SupplierCode
SupplierCode
PIC 99.
99.
02
SupplierName
PIC
X(20).
02 SupplierName
PIC X(20).
02
PIC
02 SupplierAddress
SupplierAddress
PIC X(60).
X(60).
FD
FD SupplierFileSeq.
SupplierFileSeq.
01
SupplierRecordSeq.
01 SupplierRecordSeq.
88
VALUE
88 EndOfFile
EndOfFile
VALUE HIGH-VALUES.
HIGH-VALUES.
02
SupplierCodeSeq
PIC
02 SupplierCodeSeq
PIC 99.
99.
02
SupplierNameSeq
PIC
X(20).
02 SupplierNameSeq
PIC X(20).
02
PIC
02 SupplierAddressSeq
SupplierAddressSeq
PIC X(60).
X(60).
WORKING-STORAGE
WORKING-STORAGE SECTION.
SECTION.
01
SupplierStatus
PIC
01 SupplierStatus
PIC X(2).
X(2).
01
SupplierKey
PIC
99.
01 SupplierKey
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
END
AT END SET
SET EndOfFile
EndOfFile TO
TO TRUE
TRUE
END-READ
END-READ
PERFORM
PERFORM UNTIL
UNTIL EndOfFile
EndOfFile
MOVE
SupplierCodeSeq
MOVE SupplierCodeSeq TO
TO SupplierKey
SupplierKey
MOVE
SupplierRecordSeq
TO
MOVE SupplierRecordSeq TO SupplierRecord
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
END
AT END SET
SET EndOfFile
EndOfFile TO
TO TRUE
TRUE
END-READ
END-READ
END-PERFORM.
END-PERFORM.
CLOSE
CLOSE SupplierFile,
SupplierFile, SupplierFileSeq.
SupplierFileSeq.
STOP
RUN.
STOP RUN.

Reading a Relative 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 in
in 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
PIC
02 SupplierCode
PIC 99.
99.
02
PIC
02 SupplierName
SupplierName
PIC X(20).
X(20).
02
SupplierAddress
PIC
X(60).
02 SupplierAddress
PIC X(60).
WORKING-STORAGE
WORKING-STORAGE SECTION.
SECTION.
01
PIC
01 SupplierStatus
SupplierStatus
PIC X(2).
X(2).
88
RecordFound
VALUE
88 RecordFound
VALUE "00".
"00".
01
SupplierKey
PIC
99.
01 SupplierKey
PIC 99.
01
PrnSupplierRecord.
01 PrnSupplierRecord.
02
PIC
02 PrnSupplierCode
PrnSupplierCode
PIC BB99.
BB99.
02
PIC
02 PrnSupplierName
PrnSupplierName
PIC BBX(20).
BBX(20).
02
PrnSupplierAddress
PIC
BBX(50).
02 PrnSupplierAddress
PIC BBX(50).
01
ReadType
PIC
01 ReadType
PIC 9.
9.
88
DirectRead
VALUE
88 DirectRead
VALUE 1.
1.
88
SequentialRead
VALUE
2.
88 SequentialRead
VALUE 2.

Reading a Relative File.


PROCEDURE
DIVISION.
PROCEDURE
DIVISION.
BEGIN.
BEGIN.
OPEN
SupplierFile.
OPEN INPUT
INPUT
SupplierFile.
DISPLAY
"Enter
Read
type
(Direct=1,
Seq=2)->
"" WITH
NO
ADVANCING.
DISPLAY
"Enter
Read
type
(Direct=1,
Seq=2)->
WITH
NO
ADVANCING.
ACCEPT
ACCEPT ReadType.
ReadType.
IF
IF DirectRead
DirectRead
DISPLAY
"Enter
DISPLAYSupplierKey
"Enter supplier
supplier key
key (2
(2 digits)->
digits)-> "" WITH
WITH NO
NO ADVANCING
ADVANCING
ACCEPT
ACCEPT
SupplierKey
READ
SupplierFile
READINVALID
SupplierFile
KEY
DISPLAY
"SUPP
STATUS
:-",
SupplierStatus
INVALID
KEY
DISPLAY
"SUPP
STATUS
:-",
SupplierStatus
END-READ
END-READ
PERFORM
PERFORM DisplayRecord
DisplayRecord
END-IF
END-IF
IF
IF SequentialRead
SequentialRead
READ
SupplierFile
NEXT
READAT
SupplierFile
NEXT RECORD
RECORD
END
SET
EndOfFile
AT END SET EndOfFile TO
TO TRUE
TRUE
END-READ
END-READ
PERFORM
UNTIL
EndOfFile
PERFORM
UNTIL
EndOfFile
PERFORM
DisplayRecord
PERFORM
DisplayRecord
READ
SupplierFile
NEXT
RECORD
READAT
SupplierFile
NEXT
RECORD
END
SET
EndOfFile
TO
AT
END
SET
EndOfFile
TO TRUE
TRUE
END-READ
END-READ
END-PERFORM
END-PERFORM
END-IF
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
TO
PrnSupplierName
MOVE SupplierAddress
SupplierName TO TO
PrnSupplierName
MOVE
MOVE
SupplierAddress
TO PrnSupplierAddress
PrnSupplierAddress
DISPLAY
PrnSupplierRecord
DISPLAY
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)->
2
Enter Read type (Direct=1, Seq=2)-> 2
01
OVER
01 VESTRON
VESTRON VIDEOS
VIDEOS
OVER THE
THE SEA
SEA SOMEWHERE
SOMEWHERE IN
IN LONDON
LONDON
02
HOLLYWOOD,
02 EMI
EMI STUDIOS
STUDIOS
HOLLYWOOD, CALIFORNIA,
CALIFORNIA, USA
USA
03
BUSH
03 BBC
BBC WILDLIFE
WILDLIFE
BUSH HOUSE,
HOUSE, LONDON,
LONDON, ENGLAND
ENGLAND
04
HOLLYWOOD,
04 CBS
CBS STUDIOS
STUDIOS
HOLLYWOOD, CALIFORNIA,
CALIFORNIA, USA
USA
05
YACHTING
MONTHLY
TREE
HOUSE,
LONDON,
ENGLAND
05 YACHTING MONTHLY
TREE HOUSE, LONDON, ENGLAND
06
VIRGIN
VIDEOS
IS
06 VIRGIN VIDEOS
IS THIS
THIS ONE
ONE ALSO
ALSO LOCATED
LOCATED IN
IN ENGLAND
ENGLAND
07
NEW
07 CIC
CIC VIDEOS
VIDEOS
NEW YORK
YORK PLAZZA,
PLAZZA, NEW
NEW YORK,
YORK, USA
USA
RUN
RUN OF
OF REL-EG2.EXE
REL-EG2.EXE USING
USING DIRECT
DIRECT READ
READ
Enter
Enter Read
Read type
type (Direct=1,
(Direct=1, Seq=2)->
Seq=2)-> 11
Enter
Enter supplier
supplier key
key (2
(2 digits)->
digits)-> 05
05
05
TREE
05 YACHTING
YACHTING MONTHLY
MONTHLY
TREE HOUSE,
HOUSE, LONDON,
LONDON, ENGLAND
ENGLAND

Select and Assign for Relative Files

FDs for Relative Files

Relative File Verbs - OPEN

Relative File Verbs - READ

Relative File Verbs - Write and Rewrite

Relative File Verbs - DELETE

Relative File Verbs - START

Error Handling Using Declaratives.


PROCEDURE
PROCEDURE DIVISION.
DIVISION.
DECLARATIVES.
DECLARATIVES.
SectionOne
SectionOne SECTION.
SECTION.
USE
USE clause
clause for
for this
this section.
section.
ParOne1.
ParOne1.
????????????????
????????????????
????????????????
????????????????
ParOne2.
ParOne2.
????????????????
????????????????
????????????????
????????????????
SectionTwo
SectionTwo SECTION.
SECTION.
USE
clause
USE 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
AFTER
USE AFTER ERROR
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.

Indexed
Files.

Creating an Indexed File


$$ SET
SOURCEFORMAT"FREE"
SET
SOURCEFORMAT"FREE"
IDENTIFICATION
DIVISION.
IDENTIFICATION
DIVISION.
PROGRAM-ID.
CreateIndexedFromSeq.
PROGRAM-ID.
CreateIndexedFromSeq.
** Creates
Creates an
an indexed
indexed file
file from
from aa sequential
sequential file.
file.
ENVIRONMENT
DIVISION.
ENVIRONMENT
DIVISION.
INPUT-OUTPUT
INPUT-OUTPUT SECTION.
SECTION.
FILE-CONTROL.
FILE-CONTROL.
SELECT
ASSIGN
TO
"VIDEO.DAT"
SELECT VideoFile
VideoFile
ASSIGN
TO
"VIDEO.DAT"
ORGANIZATION
IS
INDEXED
ORGANIZATION
IS
INDEXED
ACCESS
MODE
IS
RANDOM
ACCESS
MODE
IS
RANDOM
RECORD
KEY
IS
VideoCode
RECORD
KEY
IS
VideoCode
ALTERNATE
RECORD
KEY
ALTERNATE RECORD
KEY IS
IS VideoTitle
VideoTitle
WITH
DUPLICATES
WITH
DUPLICATES
FILE
FILE STATUS
STATUS IS
IS VideoStatus.
VideoStatus.
SELECT
SeqVideoFile
ASSIGN
SELECT SeqVideoFile ASSIGN TO
TO "INVIDEO.DAT".
"INVIDEO.DAT".
DATA
DATA DIVISION.
DIVISION.
FILE
SECTION.
FILE
SECTION.
FD
VideoFile.
FD
VideoFile.
01
01 VideoRecord.
VideoRecord.
02
PIC
02 VideoCode
VideoCode
PIC 9(5).
9(5).
02
VideoTitle
PIC
X(40).
02
VideoTitle
PIC
X(40).
02
VideoSupplierCode
PIC
99.
02 VideoSupplierCode
PIC 99.
FD
SeqVideoFile.
FD SeqVideoRecord.
SeqVideoFile.
01
01 88
SeqVideoRecord.
88 EndOfFile
EndOfFile VALUE
VALUE HIGH-VALUES.
HIGH-VALUES.
02
SeqVideoCode
PIC
9(5).
02
SeqVideoCode
PIC
9(5).
02
SeqVideoTitle
PIC
X(40).
02 SeqVideoSupplierCode
SeqVideoTitle
PIC 99.
X(40).
02
PIC
02 SeqVideoSupplierCode
PIC 99.
WORKING-STORAGE
SECTION.
WORKING-STORAGE
SECTION.
01
VideoStatus
PIC
01
VideoStatus
PIC X(2).
X(2).

Creating an Indexed File


PROCEDURE
PROCEDURE DIVISION.
DIVISION.
Begin.
Begin.
OPEN
INPUT
SeqVideoFile.
OPEN
INPUT
SeqVideoFile.
OPEN
OUTPUT
OPEN OUTPUT VideoFile.
VideoFile.
READ
SeqVideoFile
READ
SeqVideoFile
AT
AT END
END SET
SET EndOfFile
EndOfFile TO
TO TRUE
TRUE
END-READ.
END-READ.
PERFORM
UNTIL
EndOfFile
PERFORM
UNTIL
EndOfFile
WRITE
VideoRecord
FROM
SeqVideoRecord
WRITE
VideoRecord
FROM
SeqVideoRecord
INVALID
KEY
DISPLAY
"VIDEO
STATUS
:",
VideoStatus
INVALID
KEY
DISPLAY
"VIDEO
STATUS
:",
VideoStatus
END-WRITE
END-WRITE
READ
SeqVideoFile
READ
SeqVideoFile
AT
END
SET
EndOfFile
TO
TRUE
AT
END
SET
EndOfFile
TO
TRUE
END-READ
END-READ
END-PERFORM.
END-PERFORM.
CLOSE
VideoFile,
CLOSERUN.
VideoFile, SeqVideoFile.
SeqVideoFile.
STOP
STOP RUN.

Reading an Indexed File - Sequentially.


$$ SET
SOURCEFORMAT"FREE"
SET
SOURCEFORMAT"FREE"
IDENTIFICATION
DIVISION.
IDENTIFICATION
DIVISION.
PROGRAM-ID.
ReadingIndexedFile.
PROGRAM-ID.
ReadingIndexedFile.
** Sequential
Sequential reading
reading of
of an
an indexed
indexed file
file
ENVIRONMENT
ENVIRONMENT DIVISION.
DIVISION.
INPUT-OUTPUT
SECTION.
INPUT-OUTPUT
SECTION.
FILE-CONTROL.
FILE-CONTROL.
SELECT
TO
SELECT VideoFile
VideoFile ASSIGN
ASSIGN
TO "VIDEO.DAT"
"VIDEO.DAT"
ORGANIZATION
IS
INDEXED
ORGANIZATION
IS
INDEXED
ACCESS
IS
DYNAMIC
ACCESS MODE
MODE
IS
DYNAMIC
RECORD
KEY
IS
VideoCode
RECORD
KEY
IS
VideoCode
ALTERNATE
RECORD
ALTERNATE
RECORD KEY
KEY IS
IS VideoTitle
VideoTitle
WITH
DUPLICATES
WITH
DUPLICATES
FILE
FILE STATUS
STATUS IS
IS VideoStatus.
VideoStatus.
DATA
DATA DIVISION.
DIVISION.
FILE
SECTION.
FILE
SECTION.
FD
VideoFile
FD VideoRecord.
VideoFile
01
01 88
VideoRecord.
88 EndOfFile
EndOfFile VALUE
VALUE HIGH-VALUE.
HIGH-VALUE.
02
VideoCode
PIC
02
VideoCode
PIC 9(5).
9(5).
02
VideoTitle
PIC
X(40).
02
VideoTitle
PIC
X(40).
02
SupplierCode
PIC
99.
02 SupplierCode
PIC 99.
WORKING-STORAGE
SECTION.
WORKING-STORAGE
SECTION.
01
VideoStatus
PIC
01 VideoStatus
PIC X(2).
X(2).
01
RequiredSequence
PIC
9.
01 88
RequiredSequence
PIC 9.1.
VideoCodeSequence
VALUE
88
VideoCodeSequence
VALUE 2.
1.
88
VideoTitleSequence
VALUE
88 VideoTitleSequence
VALUE 2.
01
PrnVideoRecord.
01 02
PrnVideoRecord.
PIC
02 PrnVideoCode
PrnVideoCode
PIC 9(5).
9(5).
02
PrnVideoTitle
PIC
BBBBX(40).
02
PrnVideoTitle
PIC
BBBBX(40).
02
PIC
02 PrnSupplierCode
PrnSupplierCode
PIC BBBB99.
BBBB99.

Reading an Indexed File - Sequentially.


PROCEDURE
PROCEDURE DIVISION.
DIVISION.
Begin.
Begin.
OPEN
OPEN INPUT
INPUT VideoFile.
VideoFile.
DISPLAY
"Enter
key
:: 1=VideoCode,
2=VideoTitle
->"
DISPLAY
"Enter
key
1=VideoCode,
2=VideoTitle
->"
WITH
NO
ADVANCING.
WITH NO ADVANCING.
ACCEPT
ACCEPT RequiredSequence.
RequiredSequence.
IF
IF VideoTitleSequence
VideoTitleSequence
MOVE
TO
MOVE SPACES
SPACES
TO VideoTitle
VideoTitle
START
VideoFile
KEY
IS
GREATER
THAN
VideoTitle
START
VideoFile
KEY
IS
GREATER
THAN
VideoTitle
INVALID
KEY
DISPLAY
"VIDEO
STATUS
INVALID KEY DISPLAY "VIDEO STATUS ::- ",
", VideoStatus
VideoStatus
END-START
END-START
END-IF
END-IF
READ
VideoFile
NEXT
RECORD
READ
VideoFile
NEXT
RECORD
AT
END
SET
EndOfFile
AT END SET EndOfFile TO
TO TRUE
TRUE
END-READ.
END-READ.
PERFORM
UNTIL
EndOfFile
PERFORM
UNTIL
EndOfFile
MOVE
VideoCode
PrnVideoCode
MOVE VideoTitle
VideoCode TO
TO
PrnVideoCode
MOVE
TO
PrnVideoTitle
MOVE
VideoTitle
TO
PrnVideoTitle
MOVE
SupplierCode
TO
PrnSupplierCode
MOVE
SupplierCode
TO
PrnSupplierCode
DISPLAY
PrnVideoRecord
DISPLAY
PrnVideoRecord
READ
VideoFile
NEXT
READ
VideoFile
NEXT RECORD
RECORD
AT
END
SET
EndOfFile
TO
TRUE
AT
END
SET
EndOfFile
TO
TRUE
END-READ
END-READ
END-PERFORM.
END-PERFORM.
CLOSE
VideoFile.
CLOSERUN.
VideoFile.
STOP
STOP RUN.

Reading an Indexed File - Sequentially.


RUN OF INDEX-EG2.EXE USING VIDEOCODE KEY
RUN OF INDEX-EG2.EXE USING VIDEOCODE KEY
Enter key : 1=VideoCode, 2=VideoTitle ->1
Enter key : 1=VideoCode, 2=VideoTitle ->1
00121 FLIGHT OF THE CONDOR, THE
03
00121 FLIGHT OF THE CONDOR, THE
03
00333 PREDATOR
02
00333 PREDATOR
02
00444 LIVING EARTH, THE
03
00444 LIVING EARTH, THE
03
01001 COMMANDO
02
01001 COMMANDO
02
01100 ROBOCOP
01
01100 ROBOCOP
01
02001 LEOPARD HUNTS IN DARKNESS, A 03
02001 LEOPARD HUNTS IN DARKNESS, A 03
02121 DIRTY DANCING
04
02121 DIRTY DANCING
04
03031 COMPETENT CREW
05
03031 COMPETENT CREW
05
03032 YACHT MASTER
05
03032 YACHT MASTER
05
04041 OPEN OCEAN SAILING
05
04041 OPEN OCEAN SAILING
05
04042 PRINCESS BRIDE, THE
06
04042 PRINCESS BRIDE, THE
06
04444 LIFE ON EARTH
03
04444 LIFE ON EARTH
03
05051 OVERBOARD
01
05051 OVERBOARD
01
06061 HOPE AND GLORY
07
06061 HOPE AND GLORY
07
07071 AMONG THE WILD CHIMPANZEES
03
07071 AMONG THE WILD CHIMPANZEES
03
08081 WHALE NATION
03
08081 WHALE NATION
03
09091 BESTSELLER
07
09091 BESTSELLER
07
10001 WICKED WALTZING
04
10001 WICKED WALTZING
04
11111 TERMINATOR, THE
02
11111 TERMINATOR, THE
02
13301 MASSACRE AT MASAI MARA
03
13301 MASSACRE AT MASAI MARA
03
14032 KNOTTY PROBLEMS FOR SAILORS
05
14032 KNOTTY PROBLEMS FOR SAILORS
05
17001 ALIEN
07
17001 ALIEN
07
17002 ALIENS
07
17002 ALIENS
07
17041 GARFIELD TAKES A HIKE
06
17041 GARFIELD TAKES A HIKE
06
18001 SURVIVING THE STORM
05
18001 SURVIVING THE STORM
05
19444 PINOCCIO
02
19444 PINOCCIO
02

RUN OF INDEX-EG2 USING VIDEOTITLE KEY


RUN OF INDEX-EG2 USING VIDEOTITLE KEY
Enter key : 1=VideoCode, 2=VideoTitle ->2
Enter key : 1=VideoCode, 2=VideoTitle ->2
17001 ALIEN
07
17001 ALIEN
07
17002 ALIENS
07
17002 ALIENS
07
07071 AMONG THE WILD CHIMPANZEES
03
07071 AMONG THE WILD CHIMPANZEES
03
09091 BESTSELLER
07
09091 BESTSELLER
07
01001 COMMANDO
02
01001 COMMANDO
02
03031 COMPETENT CREW
05
03031 COMPETENT CREW
05
02121 DIRTY DANCING
04
02121 DIRTY DANCING
04
00121 FLIGHT OF THE CONDOR, THE
03
00121 FLIGHT OF THE CONDOR, THE
03
17041 GARFIELD TAKES A HIKE
06
17041 GARFIELD TAKES A HIKE
06
06061 HOPE AND GLORY
07
06061 HOPE AND GLORY
07
14032 KNOTTY PROBLEMS FOR SAILORS
05
14032 KNOTTY PROBLEMS FOR SAILORS
05
02001 LEOPARD HUNTS IN DARKNESS, A 03
02001 LEOPARD HUNTS IN DARKNESS, A 03
04444 LIFE ON EARTH
03
04444 LIFE ON EARTH
03
00444 LIVING EARTH, THE
03
00444 LIVING EARTH, THE
03
13301 MASSACRE AT MASAI MARA
03
13301 MASSACRE AT MASAI MARA
03
04041 OPEN OCEAN SAILING
05
04041 OPEN OCEAN SAILING
05
05051 OVERBOARD
01
05051 OVERBOARD
01
19444 PINOCCIO
02
19444 PINOCCIO
02
00333 PREDATOR
02
00333 PREDATOR
02
04042 PRINCESS BRIDE, THE
06
04042 PRINCESS BRIDE, THE
06
01100 ROBOCOP
01
01100 ROBOCOP
01
18001 SURVIVING THE STORM
05
18001 SURVIVING THE STORM
05
11111 TERMINATOR, THE
02
11111 TERMINATOR, THE
02
08081 WHALE NATION
03
08081 WHALE NATION
03
10001 WICKED WALTZING
04
10001 WICKED WALTZING
04
03032 YACHT MASTER
05
03032 YACHT MASTER
05

Reading an Indexed File - Directly.


IDENTIFICATION
DIVISION.
IDENTIFICATION
DIVISION.
PROGRAM-ID.
ReadingIndexedFile.
PROGRAM-ID.
ReadingIndexedFile.
** Illustrates
Illustrates direct
direct read
read on
on an
an indexed
indexed file
file by
by any
any key
key
ENVIRONMENT
DIVISION.
ENVIRONMENT DIVISION.
INPUT-OUTPUT
INPUT-OUTPUT SECTION.
SECTION.
FILE-CONTROL.
FILE-CONTROL.
SELECT
VideoFile
ASSIGN
TO
SELECT
VideoFileIS
ASSIGN
TO "VIDEO.DAT"
"VIDEO.DAT"
ORGANIZATION
INDEXED
ORGANIZATION
IS
INDEXED
ACCESS
MODE
IS
DYNAMIC
ACCESS
MODE
IS
DYNAMIC
RECORD
KEY
IS
VideoCode
RECORD KEYRECORD
IS VideoCode
ALTERNATE
KEY
ALTERNATEWITH
RECORD
KEY IS
IS VideoTitle
VideoTitle
DUPLICATES
WITH
DUPLICATES
FILE
FILE STATUS
STATUS IS
IS VideoStatus.
VideoStatus.
DATA
DATA DIVISION.
DIVISION.
FILE
SECTION.
FILE
SECTION.
FD
VideoFile.
FD
VideoFile.
01
01 VideoRecord.
VideoRecord.
02
PIC
02 VideoCode
VideoCode
PIC 9(5).
9(5).
02
VideoTitle
PIC
X(40).
02
VideoTitle
PIC
X(40).
02
SupplierCode
PIC
99.
02 SupplierCode
PIC 99.
WORKING-STORAGE
SECTION.
WORKING-STORAGE SECTION.
01
PIC
01 VideoStatus
VideoStatus
PIC X(2).
X(2).
88
RecordFound
VALUE
88 RecordFound
VALUE "00".
"00".
01
RequiredKey
PIC
9.
01 88
RequiredKey
PIC 9.1.
VideoCodeKey
VALUE
88
VideoCodeKey
VALUE 2.
1.
88
VALUE
88 VideoTitleKey
VideoTitleKey
VALUE 2.
01
01 PrnVideoRecord.
PrnVideoRecord.
02
PIC
02 PrnVideoCode
PrnVideoCode
PIC 9(5).
9(5).
02
PrnVideoTitle
PIC
BBBBX(40).
02
PrnVideoTitle
PIC
BBBBX(40).
02
PrnSupplierCode
PIC
BBBB99.
02 PrnSupplierCode
PIC BBBB99.

Reading an Indexed File - Directly.


PROCEDURE
PROCEDURE DIVISION.
DIVISION.
Begin.
Begin.
OPEN
INPUT
VideoFile.
OPEN
INPUT
VideoFile.
DISPLAY
"Chose
VideoCode
== 1,
DISPLAY "Chose key
keyWITH
VideoCode
1, VideoTitle
VideoTitle == 22 ->
-> ""
NO
ADVANCING.
WITH NO ADVANCING.
ACCEPT
ACCEPT RequiredKey.
RequiredKey.
IF
IF VideoCodeKey
VideoCodeKey
DISPLAY
"Enter
Video
Code
(5
digits)
->
"" WITH
NO
ADVANCING
DISPLAY
"Enter
Video
Code
(5
digits)
->
WITH
NO
ADVANCING
ACCEPT
VideoCode
ACCEPT
VideoCode
READ
VideoFile
READ
VideoFile
KEY
IS
VideoCode
KEY
IS
VideoCode
INVALID
INVALID KEY
KEY DISPLAY
DISPLAY "VIDEO
"VIDEO STATUS
STATUS ::- ",
", VideoStatus
VideoStatus
END-READ
END-READ
END-IF
END-IF
IF
IF VideoTitleKey
VideoTitleKey
DISPLAY
"Enter
DISPLAYVideoTitle
"Enter Video
Video Title
Title (40
(40 chars)
chars) ->
-> "" WITH
WITH NO
NO ADVANCING
ADVANCING
ACCEPT
ACCEPT
VideoTitle
READ
VideoFile
READ
VideoFile
KEY
IS
KEY
IS VideoTitle
VideoTitle
INVALID
KEY
DISPLAY
"VIDEO
STATUS
:",
VideoStatus
INVALID
KEY
DISPLAY
"VIDEO
STATUS
:",
VideoStatus
END-READ
END-READ
END-IF
END-IF
IF
IF RecordFound
RecordFound
MOVE
PrnVideoCode
MOVE VideoCode
VideoCode TO
TO
PrnVideoCode
MOVE
VideoTitle
TO
PrnVideoTitle
MOVE
VideoTitle
TO
PrnVideoTitle
MOVE
SupplierCode
TO
PrnSupplierCode
MOVE
SupplierCode
TO
PrnSupplierCode
DISPLAY
PrnVideoRecord
DISPLAY PrnVideoRecord
END-IF.
END-IF.
CLOSE
VideoFile.
CLOSERUN.
VideoFile.
STOP
STOP RUN.

Reading an Indexed File - Directly.


RUN
OF
INDEX-EG3.EXE
USING
VIDEOCODE
RUN
OF
INDEX-EG3.EXE
USING
VIDEOCODE = 2 -> 1
Chose
key
VideoCode
=
1,
VideoTitle
Chose Video
key VideoCode
= 1, VideoTitle
= 2 -> 1
Enter
Code
(5
digits)
->
02121
Enter
Video
Code
(5
digits)
->
02121
02121
DIRTY
02121
DIRTY DANCING
DANCING

04
04

RUN
OF
INDEX-EG3.EXE
USING
VIDEOCODE
RUN
OF
INDEX-EG3.EXE
USING
VIDEOCODE = 2 -> 1
Chose
key
VideoCode
=
1,
VideoTitle
Chose Video
key VideoCode
= 1, VideoTitle
= 2 -> 1
Enter
Code
(5
digits)
->
05051
Enter
Video
Code
(5
digits)
->
05051
05051
OVERBOARD
05051
OVERBOARD

01
01

RUN
INDEX-EG3.EXE
USING
VIDEOTITLE
RUN OF
OF
INDEX-EG3.EXE
USING
VIDEOTITLE= 2 -> 2
Chose
key
VideoCode
=
1,
VideoTitle
Chose
key
VideoCode
=
1,
VideoTitle
= 2 -> 2
Enter
Video
Title
(40
chars)
->
OVERBOARD
Enter Video
Title (40 chars) -> OVERBOARD
05051
OVERBOARD
05051
OVERBOARD

01
01

RUN
INDEX-EG3.EXE
USING
VIDEOTITLE
RUN OF
OF
INDEX-EG3.EXE
USING
VIDEOTITLE= 2 -> 2
Chose
key
VideoCode
=
1,
VideoTitle
Chose
key
VideoCode
=
1,
VideoTitle
=DANCING
2 -> 2
Enter
Video
Title
(40
chars)
->
DIRTY
Enter
Video
Title
(40
chars)
->
DIRTY
DANCING
02121
DIRTY
02121
DIRTY DANCING
DANCING

04
04

RUN
OF
INDEX-EG3.EXE
USING
NON
EXISTANT
VIDEOCODE
RUN
OF
INDEX-EG3.EXE
USING
NON
EXISTANT
VIDEOCODE
Chose
key
VideoCode
=
1,
VideoTitle
=
2
Chose Video
key VideoCode
= 1, VideoTitle
= 2 ->
-> 11
Enter
Code
(5
digits)
->
44444
Enter STATUS
Video Code
(5 digits) -> 44444
VIDEO
:23
VIDEO STATUS :- 23

Select and Assign for Indexed Files

Indexed Files - Primary Key


Index
Buckets

30 60 99

10 20 30

40 50 60

Level 2

70 80 99

Level 1

Level 0
41 43 44 45 46 49

Data Buckets

Indexed Files - Alternate Key


Index
Buckets

C F H

H R Z

L O R

Level 2

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

C F H

L O R

Level 2

T W Z

Level 1

Level 0
Mi Nf Ni Nt Oi Ot

Base Buckets

Ot
45

Data Buckets

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

Nf
65

Mi
71

FDs for Indexed Files

Indexed File Verbs - OPEN

Indexed File Verbs - READ

Indexed File Verbs - Write and Rewrite

Indexed File Verbs - DELETE

Indexed File Verbs - START

STRING

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.

STRING Example 1
01 DayStr

PIC XX.

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
", "
MonthStr
", "
YearStr
INTO DateStr
END-STRING.

- - - - - - - -

DELIMITED
DELIMITED
DELIMITED
DELIMITED
DELIMITED

BY
BY
BY
BY
BY

SPACES
SIZE
SPACES
SIZE
SIZE

STRING Example 1
01 DayStr

PIC XX.

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
", "
MonthStr
", "
YearStr
INTO DateStr
END-STRING.

- - - - - - - -

DELIMITED
DELIMITED
DELIMITED
DELIMITED
DELIMITED

BY
BY
BY
BY
BY

SPACES
SIZE
SPACES
SIZE
SIZE

STRING Example 1
01 DayStr

PIC XX.

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
", "
MonthStr
", "
YearStr
INTO DateStr
END-STRING.

- - - - - - - -

DELIMITED
DELIMITED
DELIMITED
DELIMITED
DELIMITED

BY
BY
BY
BY
BY

SPACES
SIZE
SPACES
SIZE
SIZE

STRING Example 1
01 DayStr

PIC XX.

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
", "
MonthStr
", "
YearStr
INTO DateStr
END-STRING.

- - - - - - - -

DELIMITED
DELIMITED
DELIMITED
DELIMITED
DELIMITED

BY
BY
BY
BY
BY

SPACES
SIZE
SPACES
SIZE
SIZE

STRING Example 1
01 DayStr

PIC XX.

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
", "
MonthStr
", "
YearStr
INTO DateStr
END-STRING.

- - - - - - - -

DELIMITED
DELIMITED
DELIMITED
DELIMITED
DELIMITED

BY
BY
BY
BY
BY

SPACES
SIZE
SPACES
SIZE
SIZE

STRING Example 1
01 DayStr

PIC XX.

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
", "
MonthStr
", "
YearStr
INTO DateStr
END-STRING.

DELIMITED
DELIMITED
DELIMITED
DELIMITED
DELIMITED

BY
BY
BY
BY
BY

SPACES
SIZE
SPACES
SIZE
SIZE

STRING Example 2
01 StrPtr

PIC 99.

01 DayStr

PIC XX.

01 MonthStr PIC X(9).

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

01 MonthStr PIC X(9).

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

01 MonthStr PIC X(9).

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

01 MonthStr PIC X(9).

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

UNSTRING

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.

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.

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.

The UNSTRING clauses 2.

WITH POINTER
The Pointer#i holds the position of the next nondelimiter 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.

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
PIC XX.

1 9

01 MonthStr PIC XX.

- 0

01 DayStr

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

01 DayStr

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

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

01 DayStr

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
PIC XX.

1 9

01 MonthStr PIC XX.

0 5

01 DayStr

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
PIC XX.

1 9

01 MonthStr PIC XX.

0 5

01 YearStr

PIC XX.

8 0

01 DateStr

PIC X(8).

01 DayStr

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
PIC XX.

1 9

01 MonthStr PIC XX.

0 5

01 DayStr

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

01 DayStr

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

01 DayStr

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

80
80

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

01 DayStr

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

80
80

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

01 DayStr

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"
END-UNSTRING.

Chars
Chars Left
Left

UNSTRING Example 7
01 OldName

Tim

PIC X(80).

John

Roberts

01 TempName.
02 NameInitial PIC
02 FILLER
PIC
01 NewName
PIC
01 Pointers.
02 StrPtr
PIC
02 UnstrPtr
PIC
88 NameProcessed

X.
X(15).
X(30).
99 VALUE 1.
99 VALUE 1.
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

Tim

PIC X(80).

John

Roberts

01 TempName.
02 NameInitial PIC
02 FILLER
PIC
01 NewName
PIC
01 Pointers.
02 StrPtr
PIC
02 UnstrPtr
PIC
88 NameProcessed

T im
X.
X(15).
X(30).
99 VALUE 1.
99 VALUE 1.
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

Tim

PIC X(80).

John

Roberts

01 TempName.
02 NameInitial PIC
02 FILLER
PIC
01 NewName
PIC
01 Pointers.
02 StrPtr
PIC
02 UnstrPtr
PIC
88 NameProcessed

J ohn
X.
X(15).
X(30).
99 VALUE 1.
99 VALUE 1.
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

Tim

PIC X(80).

John

Roberts

01 TempName.
02 NameInitial PIC
02 FILLER
PIC
01 NewName
PIC
01 Pointers.
02 StrPtr
PIC
02 UnstrPtr
PIC
88 NameProcessed

R oberts
X.
X(15).
X(30).
99 VALUE 1.
99 VALUE 1.
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

TempName

John

Roberts

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

TempName
NewName

John

Roberts

T im
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

TempName
NewName

John

Roberts

J ohn
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

TempName
NewName

John

Roberts

J ohn
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

TempName
NewName

John

Roberts

R oberts
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

TempName
NewName

John

Roberts

R oberts
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.

The CALL Verb

CALL Syntax

CALL 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
01 DateResult

PIC X(8).
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.

CALL Parameters

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

PROCEDURE DIVISION USING P2, P4, P1, P3.

Positions
Positions Correspond
Correspond -- Not
Not Names
Names

Parameter Passing Mechanisms

CALL .. BY
REFERENCE

CALLed
Program

Parameter Passing Mechanisms


Address of
Data Item

CALL .. BY
REFERENCE

Direction
of Data Flow

CALLed
Program

Parameter Passing Mechanisms


Address of
Data Item

CALL .. BY
REFERENCE

Direction
of Data Flow

CALL .. BY
CONTENT

CALLed
Program

CALLed
Program

Copy of
Data Item

Parameter Passing Mechanisms


Address of
Data Item

CALL .. BY
REFERENCE

Direction
of Data Flow

Direction
of Data Flow

CALL .. BY
CONTENT
Data
Item

Copy of
Data Item

CALLed
Program

CALLed
Program
Address of
Copy

Avoiding State Memory - The IS INITIAL phrase.


$$ SET
SET SOURCEFORMAT"FREE"
SOURCEFORMAT"FREE"
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID.
INITIAL
PROGRAM-ID. Steadfast
Steadfast IS
IS INITIAL.
INITIAL.
INITIAL

12

DATA
Total = 62
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.
01
PIC
01 ParamValue
ParamValue
PIC 99.
99.

Total = 55

PROCEDURE
PROCEDURE DIVISION
DIVISION USING
USING ParamValue.
ParamValue.
12
Begin.
Begin.
ADD
ADD ParamValue
ParamValue TO
TO RunningTotal.
RunningTotal.
Total = 62
DISPLAY
"Total
=
",
RunningTotal.
DISPLAY "Total = ", RunningTotal.
EXIT
EXIT PROGRAM.
PROGRAM.

Avoiding State Memory - The IS INITIAL phrase.


$$ SET
SET SOURCEFORMAT"FREE"
SOURCEFORMAT"FREE"
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID.
12
PROGRAM-ID. Fickle.
Fickle.
DATA
DATA DIVISION.
DIVISION.
Total = 62
WORKING-STORAGE
SECTION.
WORKING-STORAGE SECTION.
01
01 RunningTotal
RunningTotal PIC
PIC 9(7)
9(7) VALUE
VALUE 50.
50.
LINKAGE
LINKAGE SECTION.
SECTION.
01
PIC
01 ParamValue
ParamValue
PIC 99.
99.

Total = 67

PROCEDURE
PROCEDURE DIVISION
DIVISION USING
USING ParamValue.
ParamValue.
12
Begin.
Begin.
ADD
ADD ParamValue
ParamValue TO
TO RunningTotal.
RunningTotal.
DISPLAY
DISPLAY "Total
"Total == ",
", RunningTotal.
RunningTotal. Total = 79
EXIT
EXIT PROGRAM.
PROGRAM.

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.
WORKING-STORAGE
WORKING-STORAGE SECTION.
SECTION.
01
RunningTotal
01 RunningTotal PIC
PIC 9(7)
9(7) VALUE
VALUE 50.
50.
LINKAGE
LINKAGE SECTION.
SECTION.
01
ParamValue
PIC
01 ParamValue
PIC 99.
99.
PROCEDURE
PROCEDURE DIVISION
DIVISION USING
USING ParamValue.
ParamValue.
Begin.
Begin.
ADD
ADD ParamValue
ParamValue TO
TO RunningTotal.
RunningTotal.
DISPLAY
"Total
=
",
DISPLAY "Total = ", RunningTotal.
RunningTotal.
EXIT
PROGRAM.
EXIT PROGRAM.

12
Total = 62
12
Total = 62

Contained Sub-Programs
$$ SET
SET SOURCEFORMAT"FREE"
SOURCEFORMAT"FREE"
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID.
MainProgram.
PROGRAM-ID. MainProgram.
?? ?? ?? ?? ?? ?? ?? ?? ??
01
GLOBAL
01 TableItem
TableItem IS
IS GLOBAL.
GLOBAL.
GLOBAL
PROCEDURE
PROCEDURE DIVISION.
DIVISION.
?? ?? ?? ?? ?? ?? ?? ?? ??
CALL
CALL PutToTable
PutToTable USING
USING BY
BY CONTENT
CONTENT DataItem
DataItem
?? ?? ?? ?? ?? ?? ?? ?? ??
CALL
CALL ReportFromTable.
ReportFromTable.
EXIT
EXIT PROGRAM.
PROGRAM.
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID.
PROGRAM-ID. PutToTable.
PutToTable.
?? ?? ?? ?? ?? ?? ?? ?? ??
END-PROGRAM
END-PROGRAM PutToTable.
PutToTable.
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID.
ReportFromTable.
PROGRAM-ID. ReportFromTable.
?? ?? ?? ?? ?? ?? ?? ?? ??
END-PROGRAM
END-PROGRAM ReportFromTable.
ReportFromTable.
END-PROGRAM
END-PROGRAM MainProgram.
MainProgram.

Contained Sub-Programs
$$ SET
SET SOURCEFORMAT"FREE"
SOURCEFORMAT"FREE"
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID.
MainProgram.
PROGRAM-ID. MainProgram.
?? ?? ?? ?? ?? ?? ?? ?? ??
01
GLOBAL
01 TableItem
TableItem IS
IS GLOBAL.
GLOBAL.
GLOBAL
PROCEDURE
PROCEDURE DIVISION.
DIVISION.
?? ?? ?? ?? ?? ?? ?? ?? ??
CALL
CALL PutToTable
PutToTable USING
USING BY
BY CONTENT
CONTENT DataItem
DataItem
?? ?? ?? ?? ?? ?? ?? ?? ??
CALL
CALL ReportFromTable.
ReportFromTable.
EXIT
EXIT PROGRAM.
PROGRAM.
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID.
PROGRAM-ID. PutToTable.
PutToTable.
?? ?? ?? ?? ?? ?? ?? ?? ??
END-PROGRAM
END-PROGRAM PutToTable.
PutToTable.
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID.
ReportFromTable.
PROGRAM-ID. ReportFromTable.
?? ?? ?? ?? ?? ?? ?? ?? ??
END-PROGRAM
END-PROGRAM ReportFromTable.
ReportFromTable.
END-PROGRAM
END-PROGRAM MainProgram.
MainProgram.

Contained Sub-Programs
$$ SET
SET SOURCEFORMAT"FREE"
SOURCEFORMAT"FREE"
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID.
MainProgram.
PROGRAM-ID. MainProgram.
?? ?? ?? ?? ?? ?? ?? ?? ??
01
GLOBAL
01 TableItem
TableItem IS
IS GLOBAL.
GLOBAL.
GLOBAL
PROCEDURE
PROCEDURE DIVISION.
DIVISION.
?? ?? ?? ?? ?? ?? ?? ?? ??
CALL
CALL PutToTable
PutToTable USING
USING BY
BY CONTENT
CONTENT DataItem
DataItem
?? ?? ?? ?? ?? ?? ?? ?? ??
CALL
CALL ReportFromTable.
ReportFromTable.
EXIT
EXIT PROGRAM.
PROGRAM.
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID.
PROGRAM-ID. PutToTable.
PutToTable.
?? ?? ?? ?? ?? ?? ?? ?? ??
END-PROGRAM
END-PROGRAM PutToTable.
PutToTable.
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID.
ReportFromTable.
PROGRAM-ID. ReportFromTable.
?? ?? ?? ?? ?? ?? ?? ?? ??
END-PROGRAM
END-PROGRAM ReportFromTable.
ReportFromTable.
END-PROGRAM
END-PROGRAM MainProgram.
MainProgram.

The COMMON PROGRAM Phrase


$$ SET
SET SOURCEFORMAT"FREE"
SOURCEFORMAT"FREE"
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID.
MainProgram.
PROGRAM-ID. MainProgram.
?? ?? ?? ?? ?? ?? ?? ?? ??
01
GLOBAL
01 TableItem
TableItem IS
IS 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.
ReportFromTable
PROGRAM-ID. ReportFromTable IS
IS COMMON
COMMON PROGRAM.
PROGRAM.
?? ?? ?? ?? ?? ?? ?? ?? ??
CALL
CALL PutToTable
PutToTable USING
USING ????
????
?? ?? ?? ?? ?? ?? ?? ?? ??
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
GLOBAL
01 TableItem
TableItem IS
IS 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. YES
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID.
ReportFromTable
PROGRAM-ID. ReportFromTable IS
IS COMMON
COMMON PROGRAM.
PROGRAM.
?? ?? ?? ?? ?? ?? ?? ?? ??
CALL
CALL PutToTable
PutToTable USING
USING ????
????
?? ?? ?? ?? ?? ?? ?? ?? ??
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
GLOBAL
01 TableItem
TableItem IS
IS 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
END-PROGRAM PutToTable.
PutToTable. YES
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
PROGRAM-ID.
ReportFromTable
PROGRAM-ID. ReportFromTable IS
IS COMMON
COMMON PROGRAM.
PROGRAM.
?? ?? ?? ?? ?? ?? ?? ?? ??
CALL
CALL PutToTable
PutToTable USING
USING ????
????
?? ?? ?? ?? ?? ?? ?? ?? ??
END-PROGRAM
END-PROGRAM ReportFromTable.
ReportFromTable.
END-PROGRAM
MainProgram.
END-PROGRAM MainProgram.

Creating Abstract Data Types?


$$ SET
SOURCEFORMAT"FREE"
SET
SOURCEFORMAT"FREE"
IDENTIFICATION
DIVISION.
IDENTIFICATION
DIVISION.
PROGRAM-ID.
Stack.
PROGRAM-ID. Stack.
Main
DATA
DIVISION.
DATA DIVISION. SECTION.
WORKING-STORAGE
WORKING-STORAGE
SECTION.
01
StackHolder
IS
GLOBAL.
01 02
StackHolder
IS
GLOBAL.
StackItem
OCCURS
02 StackItem OCCURS 20
20 TIMES
TIMES PIC
PIC X(10).
X(10).
PROCEDURE
DIVISION
USING
????.
PROCEDURE
DIVISION
USING
????.
Stack
Begin.
Begin.
EVALUATE
TRUE
EVALUATE
TRUE
WHEN
PushStack
CALL
"Push"
USING
???
WHEN
PushStack
CALL
"Push"
USING
???
WHEN
PopStack
CALL
"Pop"
USING
???
WHEN PopStack CALL "Pop" USING ???
END-EVALUATE.
END-EVALUATE.
EXIT
EXIT PROGRAM.
PROGRAM.
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
Push
PROGRAM-ID.
Push.
PROGRAM-ID. Push.
?? ?? ?? ?? ?? ?? ?? ?? ??
END-PROGRAM
END-PROGRAM Push.
Push.
IDENTIFICATION
DIVISION.
IDENTIFICATION
DIVISION.
PROGRAM-ID.
Pop.
PROGRAM-ID.
?? ?? ?? ?? ?Pop.
?? ?? ?? ??
?
END-PROGRAM
Pop.
END-PROGRAM
Pop.
END-PROGRAM
Stack.
END-PROGRAM Stack.

Pop

Creating Abstract Data Types?


$$ SET
SOURCEFORMAT"FREE"
SET
SOURCEFORMAT"FREE"
IDENTIFICATION
DIVISION.
IDENTIFICATION
DIVISION.
PROGRAM-ID.
Stack.
PROGRAM-ID. Stack.
Main
DATA
DIVISION.
DATA DIVISION. SECTION.
WORKING-STORAGE
WORKING-STORAGE
SECTION.
01
StackHolder
IS
GLOBAL.
01 02
StackHolder
IS
GLOBAL.
StackItem
OCCURS
02 StackItem OCCURS 20
20 TIMES
TIMES PIC
PIC X(10).
X(10).
PROCEDURE
DIVISION
USING
????.
PROCEDURE
DIVISION
USING
????.
Stack
Begin.
Begin.
EVALUATE
TRUE
EVALUATE
TRUE
WHEN
PushStack
CALL
"Push"
USING
???
WHEN
PushStack
CALL
"Push"
USING
???
WHEN
PopStack
CALL
"Pop"
USING
???
WHEN PopStack CALL "Pop" USING ???
END-EVALUATE.
END-EVALUATE.
EXIT
EXIT PROGRAM.
PROGRAM.
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
Push
PROGRAM-ID.
Push.
PROGRAM-ID. Push.
?? ?? ?? ?? ?? ?? ?? ?? ??
END-PROGRAM
END-PROGRAM Push.
Push.
IDENTIFICATION
DIVISION.
IDENTIFICATION
DIVISION.
PROGRAM-ID.
Pop.
PROGRAM-ID.
?? ?? ?? ?? ?Pop.
?? ?? ?? ??
?
END-PROGRAM
Pop.
END-PROGRAM
Pop.
END-PROGRAM
Stack.
END-PROGRAM Stack.

Pop

Creating Abstract Data Types?


$$ SET
SOURCEFORMAT"FREE"
SET
SOURCEFORMAT"FREE"
IDENTIFICATION
DIVISION.
IDENTIFICATION
DIVISION.
PROGRAM-ID.
Stack.
PROGRAM-ID. Stack.
Main
DATA
DIVISION.
DATA DIVISION. SECTION.
WORKING-STORAGE
WORKING-STORAGE
SECTION.
01
StackHolder
IS
GLOBAL.
01 02
StackHolder
IS
GLOBAL.
StackItem
OCCURS
02 StackItem OCCURS 20
20 TIMES
TIMES PIC
PIC X(10).
X(10).
PROCEDURE
DIVISION
USING
????.
PROCEDURE
DIVISION
USING
????.
Stack
Begin.
Begin.
EVALUATE
TRUE
EVALUATE
TRUE
WHEN
PushStack
CALL
"Push"
USING
???
WHEN
PushStack
CALL
"Push"
USING
???
WHEN
PopStack
CALL
"Pop"
USING
???
WHEN PopStack CALL "Pop" USING ???
END-EVALUATE.
END-EVALUATE.
EXIT
EXIT PROGRAM.
PROGRAM.
IDENTIFICATION
IDENTIFICATION DIVISION.
DIVISION.
Push
PROGRAM-ID.
Push.
PROGRAM-ID. Push.
?? ?? ?? ?? ?? ?? ?? ?? ??
END-PROGRAM
END-PROGRAM Push.
Push.
IDENTIFICATION
DIVISION.
IDENTIFICATION
DIVISION.
PROGRAM-ID.
Pop.
PROGRAM-ID.
?? ?? ?? ?? ?Pop.
?? ?? ?? ??
?
END-PROGRAM
Pop.
END-PROGRAM
Pop.
END-PROGRAM
Stack.
END-PROGRAM Stack.

Pop

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

The IS EXTERNAL phrase.


ProgramA

ProgramB

ProgramC

01 SharedRec etc

ProgramD
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

01 SharedRec etc

ProgramD
01 SharedRec etc

Mike12345

PUT

SharedRec
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

01 SharedRec etc

ProgramD
01 SharedRec etc
Mike12345

Mike12345

PUT

SharedRec
Mike12345

GET

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

CALL STATEMENT
Subroutines within a program are executed from the main program

SUB PROGRAMS that exist outside the main program can also
be executed from a program with the help of a CALL statement

CALL literal-1 [using identifier1]

Example of CALL
1

Calling Program
Identification Division.
.
.
Call SUB1
.
.
Call SUB2
.
.
.

Called programs
IDENTIFICATION DIVISION.
PROGRAM-ID. SUB1
.
.
GO BACK

Program SUB1 is executed

Control returns to calling program

Program SUB2 is executed

Control returns to calling program

3
IDENTIFICATION DIVISION.
PROGRAM-ID. SUB2
.
.
GO BACK

INSPECT

INSPECT
The INSPECT statement may be used for replacing a specific character in a
field with another character. It can also be used for counting the number
of occurrences of a given character

INSPECT identifier-1 TALLAYING

Identifier- 2 FOR

ALL
LEADING
CHARACTERS

Identifier 3
Literal 1

BEFORE
AFTER

INITIAL

Identifier 3
Literal 1

INSPECT Syntax - Format 1

INSPECT FullName
FOR LEADING

TALLYING UnstrPtr
SPACES.

INSPECT SourceLine TALLYING ECount


FOR ALL "e" AFTER INITIAL "start"
BEFORE INITIAL "end".

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.

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.

INSPECT Syntax - Format 2

PERFORM VARYING idx FROM 1 BY 1 UNTIL idx > 10


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

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

INSPECT Syntax - Format 4

INSPECT TextLine CONVERTING


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

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
DISPLAY RussianPay " roubles".

RussianPay

"R".

INSPECT Example 10

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

MOVE 12345.67 TO RussianPay.


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

RussianPay

$12,345.67

"R".

INSPECT Example 10

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

MOVE 12345.67 TO RussianPay.


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

RussianPay

R12,345.67

"R".

INSPECT Example 10

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

MOVE 12345.67 TO RussianPay.


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

"R".

RussianPay

R12,345.67

R12,345.67 roubles

EXAMINE

The EXAMINE verb


This verb is used by the IBM VS COBOL. This verb has 2 options.
The most basic form of this verb can be used to scan a field and re
certain occurrences of a specific character. The first format is :

EXAMINE data-name REPLACING

BY character2

ALL
LEADING
UNTIL FIRST
FIRST

character1

EXAMINE
The EXAMINE verb
The second format is as given below:

EAMINE data-name TALLAYING

ALL
LEADING
UNTIL FIRST
FIRST

REPLACING BY character2

character1

Sort
and
Merge

DATA DIVISION.
FILE SECTION.
FD StudentFile.
01 StudentDetails.
02 StudentId
02 StudentName.
03 Surname
03 Initials
02 DateOfBirth.
03 YOBirth
03 MOBirth
03 DOBirth
02 CourseCode
02 Grant
02 Gender

PIC 9(7).
PIC X(8).
PIC XX.
PIC
PIC
PIC
PIC
PIC
PIC

9(2).
9(2).
9(2).
X(4).
9(4).
X.

The StudentFile is a sequential file sequenced


upon ascending StudentId.

Write a program to display the number of students


taking each course. How?

Simplified Sort 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.

Sort Example.
FD
01

SalesFile.
SalesRec.
02 FILLER
PIC X(10).
SD WorkFile.
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
01 WorkRecord.
WorkRecord.
02
02 ProvinceCode
ProvinceCode
02
SalesmanCode
02 SalesmanCode
02
02 FILLER
FILLER

PIC
PIC 9.
9.
PIC
9(5).
PIC 9(5).
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
KEY
DESCENDING KEY SalesmanCode
SalesmanCode
USING
USING UnsortedSales
UnsortedSales
GIVING
GIVING SortedSales.
SortedSales.
OPEN
OPEN INPUT
INPUT SortedSales.
SortedSales.

How the SORT works.


SalesFile

SortedSalesFile

Unsorted
Records

SORT
Process

Sorted
Records

WorkFile
SORT WorkFile ON ASCENDING KEY WSalesmanNum
USING SalesFile
GIVING SortedSalesFile.

How the INPUT PROCEDURE works.


SalesFile

Unsorted
Records

Unsorted
Hat
Records

SortedSalesFile

Sorted
Records

SORT
Process

SelectHatSales
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

INPUT PROCEDURE - Example


FD
FD SalesFile.
SalesFile.
01
01 SalesRec.
SalesRec.
88
VALUE
88 EndOfSales
EndOfSales
VALUE HIGH-VALUES.
HIGH-VALUES.
02
PIC
02 FILLER
FILLER
PIC 9(5).
9(5).
02
PIC
02 FILLER
FILLER
PIC X.
X.
88
HatRecord
VALUE
88 HatRecord
VALUE "H".
"H".
02
FILLER
PIC
X(4).
02 FILLER
PIC X(4).
SD
SD WorkFile.
WorkFile.
01
01 WorkRec.
WorkRec.
02
PIC
02 WSalesmanNum
WSalesmanNum
PIC 9(5).
9(5).
02
PIC
02 FILLER
FILLER
PIC X(5).
X(5).
FD
FD SortedSalesFile.
SortedSalesFile.
01
SortedSalesRec.
01 SortedSalesRec.
02
PIC
02 SalesmanNum
SalesmanNum
PIC 9(5).
9(5).
02
ItemType
PIC
X.
02 ItemType PIC X.
02
02 QtySold
QtySold PIC
PIC 9(4).
9(4).
PROCEDURE
PROCEDURE DIVISION.
DIVISION.
Begin.
Begin.
SORT
SORT WorkFile
WorkFile ON
ON ASCENDING
ASCENDING KEY
KEY WSalesmanNum
WSalesmanNum
INPUT
INPUT PROCEDURE
PROCEDURE IS
IS SelectHatSales
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
WorkRecord.
01 WorkRecord.
88
88 EndOfWorkFile
EndOfWorkFile
02
02 ProvinceCode
ProvinceCode
88
88 ProvinceIsUlster
ProvinceIsUlster
02
02 SalesmanCode
SalesmanCode
02
02 FILLER
FILLER
FD
FD UnsortedSales.
UnsortedSales.
01
01 FILLER
FILLER
FD
FD SortedSales.
SortedSales.
01
SortedRec.
01 SortedRec.
88
88 EndOfSalesFile
EndOfSalesFile
02
ProvinceCode
02 ProvinceCode
02
02 SalesmanCode
SalesmanCode
02
02 ItemCode
ItemCode
02
02 ItemCost
ItemCost
02
02 QtySold
QtySold

VALUE
VALUE HIGH-VALUES.
HIGH-VALUES.
PIC
PIC 9.
9.
VALUE
VALUE 4.
4.
PIC
PIC 9(5).
9(5).
PIC
PIC X(19).
X(19).
PIC
PIC X(25).
X(25).
VALUE
VALUE HIGH-VALUES.
HIGH-VALUES.
PIC
9.
PIC 9.
PIC
PIC 9(5).
9(5).
PIC
PIC 9(7).
9(7).
PIC
PIC 9(3)V99.
9(3)V99.
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
PROCEDURE IS
IS SelectUlsterRecs
SelectUlsterRecs
GIVING
SortedSales.
GIVING SortedSales.
OPEN
OPEN INPUT
INPUT SortedSales.
SortedSales.
SelectUlsterRecs.
SelectUlsterRecs.
OPEN
OPEN INPUT
INPUT UnsortedSales
UnsortedSales
READ
READ UnsortedSales
UnsortedSales INTO
INTO WorkRec
WorkRec
AT
END
SET
EndOfSalesFile
AT END SET EndOfSalesFile TO
TO TRUE
TRUE
END-READ
END-READ
PERFORM
PERFORM UNTIL
UNTIL EndOfSalesFile
EndOfSalesFile
IF
ProvinceIsUlster
IF ProvinceIsUlster RELEASE
RELEASE WorkRec
WorkRec
END-IF
END-IF
READ
READ UnsortedSales
UnsortedSales INTO
INTO WorkRec
WorkRec
AT
END
SET
EndOfSalesFile
AT END SET EndOfSalesFile TO
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.

How the OUTPUT PROCEDURE works.


SalesFile

SalesSummaryFile

Unsorted
Records

SORT
Process

Sorted
Records

Salesman
Summary
Record

SummariseSales
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
01
01
SD
SD
01
01

SalesFile.
SalesFile.
SalesRec
PIC
SalesRec
PIC X(10).
X(10).
WorkFile.
WorkFile.
WorkRec.
WorkRec.
88
VALUE
88 EndOfWorkFile
EndOfWorkFile
VALUE HIGH-VALUES.
HIGH-VALUES.
02
PIC
02 WSalesmanNum
WSalesmanNum
PIC 9(5).
9(5).
02
PIC
02 FILLER
FILLER
PIC X.
X.
02
PIC
02 WQtySold
WQtySold
PIC X(4).
X(4).
FD
FD SalesSummaryFile.
SalesSummaryFile.
01
01 SummaryRec.
SummaryRec.
02
PIC
02 SalesmanNum
SalesmanNum
PIC 9(5).
9(5).
02
PIC
02 TotalQtySold
TotalQtySold
PIC 9(6).
9(6).
PROCEDURE
PROCEDURE DIVISION.
DIVISION.
Begin.
Begin.
SORT
SORT WorkFile
WorkFile ON
ON ASCENDING
ASCENDING KEY
KEY WSalesmanNum
WSalesmanNum
USING
USING SalesFile
SalesFile
OUTPUT
SummariseSales
OUTPUT PROCEDURE
PROCEDURE IS
IS SummariseSales.
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 TO
TO 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 TO
TO 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

Feeding the SORT from the keyboard.


8965125COUGHLAN

StudentFile

Unsorted
Student
Records

SORT
Process

Sorted
Student
Records

GetStudentDetails
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 TO
TO "SORTSTUD.DAT"
"SORTSTUD.DAT"
ORGANIZATION
IS
LINE
SEQUENTIAL.
ORGANIZATION IS LINE SEQUENTIAL.
SELECT
SELECT WorkFile
WorkFile ASSIGN
ASSIGN TO
TO "WORK.TMP".
"WORK.TMP".
DATA
DIVISION.
DATA DIVISION.
FILE
FILE SECTION.
SECTION.
FD
StudentFile.
FD StudentFile.
01
PIC
01 StudentDetails
StudentDetails
PIC X(32).
X(32).
SD
WorkFile.
SD WorkFile.
01
01 WorkRec.
WorkRec.
02
PIC
02 WStudentId
WStudentId
PIC 9(7).
9(7).
02
FILLER
PIC
X(25).
02 FILLER
PIC X(25).
PROCEDURE
DIVISION.
PROCEDURE DIVISION.
Begin.
Begin.
SORT
SORT WorkFile
WorkFile ON
ON 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.

ENVIRONMENT
ENVIRONMENT DIVISION.
DIVISION.
INPUT-OUTPUT
INPUT-OUTPUT SECTION.
SECTION.
FILE-CONTROL.
FILE-CONTROL.
SELECT
ASSIGN
SELECT StudentFile
StudentFile
ASSIGN TO
TO "STUDENTS.DAT"
"STUDENTS.DAT"
ORGANIZATION
IS
LINE
SEQUENTIAL.
ORGANIZATION IS LINE SEQUENTIAL.
SELECT
InsertionsFile
SELECT InsertionsFile ASSIGN
ASSIGN TO
TO "TRANSINS.DAT"
"TRANSINS.DAT"
ORGANIZATION
IS
LINE
SEQUENTIAL.
ORGANIZATION IS LINE SEQUENTIAL.
SELECT
NewStudentFile
SELECT NewStudentFile ASSIGN
ASSIGN TO
TO "STUDENTS.NEW"
"STUDENTS.NEW"
ORGANIZATION
IS
LINE
SEQUENTIAL.
ORGANIZATION IS LINE SEQUENTIAL.
SELECT
ASSIGN
SELECT WorkFile
WorkFile
ASSIGN TO
TO "WORK.TMP".
"WORK.TMP".
DATA
DATA DIVISION.
DIVISION.
FILE
SECTION.
FILE SECTION.
FD
FD StudentFile.
StudentFile.
01
StudentRec
01 StudentRec
FD
FD InsertionsFile.
InsertionsFile.
01
InsertionRec
01 InsertionRec
FD
FD NewStudentFile.
NewStudentFile.
01
NewStudentRec
01 NewStudentRec
SD
SD WorkFile.
WorkFile.
01
WorkRec.
01 WorkRec.
02
02 WStudentId
WStudentId
02
FILLER
02 FILLER

PIC
PIC X(32).
X(32).
PIC
PIC X(32).
X(32).
PIC
PIC X(32).
X(32).
PIC
PIC 9(7).
9(7).
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.

You might also like