Post on 23-Nov-2014
1
IBMMAINFRAMES.comIBMMAINFRAMES.com
With
DEXTRA UniversityDEXTRA UniversityPresents
COBOL – Complete ReferenceCOBOL – Complete Reference
2
IntroductioIntroduction to n to
COBOL COBOL
3
COBOLCOBOL COBOL is an acronym which stands for
Common Business Oriented Language. The name indicates the target area of COBOL applications. COBOL is used for developing business, typically file-
oriented, applications. It is not designed for writing systems programs. You would
not develop an operating system or a compiler using COBOL. COBOL is one of the oldest computer languages in use (it was
developed around the end of the 1950s). As a result it has some idiosyncrasies which programmers may find irritating.
4
COBOL COBOL idiosyncrasiesidiosyncrasies 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.
5
The COBOL Meta language - Syntax The COBOL Meta language - Syntax NotationNotation
Words in uppercase are reserved words.– When underlined they must be present when the operation of
which they are a part is used.– When they are not underlined the used for readability only and are
optional. If used they must be spelt correctly. Words in mixed case represent names which will be devised
by the programmer. When material is enclosed in braces { } a choice must be
made from the options within the braces. Material is enclosed in square brackets [ ] indicates that the
material is an option which may be included or omitted as required.
The ellipsis symbol ‘...’ indicates that the preceding syntax element may be repeated at the programmer’s discretion.
6
ProgramProgramProgramProgram
Divisions
Section(s)
Paragraph(s)
Sentence(s)
Statement(s)
Structure of COBOL programs.
7
The Four The Four Divisions.Divisions.
DIVISIONS are used to identify the principal components of the program text. There are four DIVISIONS in all.
IDENTIFICATION DIVISION.
ENVIRONMENT DIVISION.
DATA DIVISION.
PROCEDURE DIVISION.
Although some of the divisions may be omitted the sequence in which the DIVISIONS are specified is fixed and must follow the pattern shown above.
8
Functions of the four Functions of the four divisions.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.
9
COBOL Program Text Structure COBOL Program Text Structure
Data Descriptions
Algorithm Description
IDENTIFICATION DIVISION.IDENTIFICATION DIVISION.
DATA DIVISION.DATA DIVISION.
PROCEDURE DIVISION.PROCEDURE DIVISION.
Program Details
NNOTEOTEThe keyword DIVISION and a ‘full-stop’ is used in every case.
NNOTEOTEThe keyword DIVISION and a ‘full-stop’ is used in every case.
10
IDENTIFICATION IDENTIFICATION DIVISION.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.
11
The IDENTIFICATION DIVISION Syntax.The IDENTIFICATION DIVISION Syntax.
The IDENTIFICATION DIVISION has the following structureIDENTIFICATION 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.
12
The IDENTIFICATION DIVISION Syntax.The IDENTIFICATION DIVISION Syntax. The IDENTIFICATION DIVISION has the following
structureIDENTIFICATION 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.
$ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. SequenceProgram.AUTHOR. Michael Coughlan.
$ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. SequenceProgram.AUTHOR. Michael Coughlan.
13
The DATA DIVISION.The DATA DIVISION.
The DATA DIVISION is used to describe most of the data that a program processes.
The DATA DIVISION is divided into two main sections;– FILE SECTION.– WORKING-STORAGE SECTION.
The FILE SECTION is used to describe most of the data that is sent to, or comes from, the computer’s peripherals.
The WORKING-STORAGE SECTION is used to describe the general variables used in the program.
14
The DATA DIVISION has the following structure
DATA DIVISION SyntaxDATA DIVISION Syntax
DATA DIVISION.FILE SECTION. File Section entries.WORKING-STORAGE SECTION. WS entries.
$ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. Sequence-Program.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.
$ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. Sequence-Program.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.
15
The PROCEDURE The PROCEDURE DIVISION.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.
16
SectionSectionss
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.
17
ParagraphParagraphss
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.
18
Sentences and Sentences and Statements.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 StudentNameDISPLAY "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 TRUEEND-READ
19
A Full COBOL program.A Full COBOL program.IDENTIFICATION DIVISION.PROGRAM-ID. SequenceProgram.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.
PROCEDURE DIVISION.CalculateResult. ACCEPT Num1. ACCEPT Num2. MULTIPLY Num1 BY Num2 GIVING
Result. DISPLAY "Result is = ", Result. STOP RUN.
IDENTIFICATION DIVISION.PROGRAM-ID. SequenceProgram.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.
PROCEDURE DIVISION.CalculateResult. ACCEPT Num1. ACCEPT Num2. MULTIPLY Num1 BY Num2 GIVING
Result. DISPLAY "Result is = ", Result. STOP RUN.
20
The minimum COBOL program.The minimum COBOL program.
IDENTIFICATION DIVISION.PROGRAM-ID. SmallestProgram.
PROCEDURE DIVISION.DisplayPrompt. DISPLAY "I did it". STOP RUN.
IDENTIFICATION DIVISION.PROGRAM-ID. SmallestProgram.
PROCEDURE DIVISION.DisplayPrompt. DISPLAY "I did it". STOP RUN.
21
COBOL COBOL Basics 1 Basics 1
22
COBOL coding COBOL coding rulesrules
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.
23
COBOL coding rulesCOBOL coding rules
$ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. ProgramFragment.* This is a comment. It starts* with an asterisk in column 1
$ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. ProgramFragment.* This is a comment. It starts* with an asterisk in column 1
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.
24
Name Name Construction.Construction.
All user defined names, such as data names, paragraph names, section names and mnemonic names, must adhere to the following rules;
– They must contain at least one character and not more than 30 characters.
– They must contain at least one alphabetic character and they must not begin or end with a hyphen.
– They must be contructed from the characters A to Z, the number 0 to 9 and the hyphen.e.g. TotalPay, Gross-Pay, PrintReportHeadings, Customer10-Rec
All data-names should describe the data they contain. All paragraph and section names should describe the function of
the paragraph or section.
25
Describing DATA.Describing DATA.
ŒVariables.Literals.ŽFigurative Constants.
Unlike other programming languages, COBOL does not support user defined constants.
There are basically three kinds of data used in COBOL programs;
26
Data-Names / Data-Names / VariablesVariables
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.
27
StudentName
Using VariablesUsing Variables
MOVE "JOHN" TO StudentName.DISPLAY "My name is ", StudentName.
01 StudentName01 StudentName PIC X(6) VALUE PIC X(6) VALUE SPACESSPACES..
28
StudentName
MOVE "JOHN" TO StudentName.MOVE "JOHN" TO StudentName.DISPLAY "My name is ", StudentName.
01 StudentName PIC X(6) VALUE SPACES.
J O H N
Using Using VariablesVariables
29
StudentName
MOVE "JOHN" TO StudentName.DISPLAY "My name is ", StudentName.DISPLAY "My name is ", StudentName.
01 StudentName PIC X(6) VALUE SPACES.
My name is JOHN
Using Using VariablesVariables
J O H NJ O H N
30
COBOL Data TypesCOBOL 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”!
31
Quick Review of “Data Typing”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.
32
COBOL data description.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.
33
COBOL ‘PICTURE’ Clause COBOL ‘PICTURE’ Clause symbolssymbols
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.
34
COBOL ‘PICTURE’ COBOL ‘PICTURE’ ClausesClauses
Some examples– PICTURE 999 a three digit (+ive only) integer– PICTURE S999 a three digit (+ive/-ive) integer– PICTURE XXXX a four character text item or string– PICTURE 99V99 a +ive ‘real’ in the range 0 to 99.99– PICTURE S9V9 a +ive/-ive ‘real’ in the range ?
If you wish you can use the abbreviation PIC.
Numeric values can have a maximum of 18 (eighteen) digits (i.e. 9’s).
The limit on string values is usually system-dependent.
35
Abbreviating recurring symbolsAbbreviating 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
36
Declaring DATA in COBOLDeclaring 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.
Num1 VatRate StudentNameNum1 VatRate StudentName
000000 .18.18
DDATAATA
37
COBOL Literals.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
38
Figurative Figurative ConstantsConstants
COBOL provides its own, special constants called Figurative Constants.
SPACE or SPACESSPACE or SPACES =
ZERO or ZEROS or ZEROSZERO or ZEROS or ZEROS = 0
QUOTE or QUOTESQUOTE or QUOTES = "
HIGH-VALUE or HIGH-VALUESHIGH-VALUE or HIGH-VALUES = Max Value
LOW-VALUE or LOW-VALUESLOW-VALUE or LOW-VALUES = Min Value
ALL ALL literalliteral = Fill With Literal
SPACE or SPACESSPACE or SPACES =
ZERO or ZEROS or ZEROSZERO or ZEROS or ZEROS = 0
QUOTE or QUOTESQUOTE or QUOTES = "
HIGH-VALUE or HIGH-VALUESHIGH-VALUE or HIGH-VALUES = Max Value
LOW-VALUE or LOW-VALUESLOW-VALUE or LOW-VALUES = Min Value
ALL ALL literalliteral = Fill With Literal
39
Figurative Constants - ExamplesFigurative Constants - Examples01 GrossPay PIC 9(5)V99 VALUE 13.5.
MOVE TO GrossPay.
01 GrossPay PIC 9(5)V99 VALUE 13.5.
MOVE TO GrossPay.ZEROZEROSZEROES
01 StudentName PIC X(10) VALUE "MIKE".
MOVE ALL "-" TO StudentName.
01 StudentName PIC X(10) VALUE "MIKE".
MOVE ALL "-" TO StudentName.
StudentName
M I K E M I K E
GrossPay
0 0 0 1 3 5 0
40
Figurative Constants - ExamplesFigurative Constants - Examples
01 GrossPay PIC 9(5)V99 VALUE 13.5.
MOVE TO GrossPay.
01 GrossPay PIC 9(5)V99 VALUE 13.5.
MOVE TO GrossPay.ZEROZEROSZEROES
01 StudentName PIC X(10) VALUE "MIKE".
MOVE ALL "-" TO StudentName.
01 StudentName PIC X(10) VALUE "MIKE".
MOVE ALL "-" TO StudentName.
StudentName
- - - - - - - - - -- - - - - - - - - -
GrossPay
0 0 0 0 0 0 0
41
Editing, Checking, Compiling, Editing, Checking, Compiling, RunningRunning
42
PROCO MenusPROCO MenusPROCO 1 - Menu
F1=help F2=edit F3=check F4=animate F5=compile F6=run F7=library F8=build
F10=directory
PROCO 1 - MenuF1=help F2=edit F3=check F4=animate F5=compile F6=run F7=library F8=build
F10=directory
PROCO 2 - Alt MenuF1=help F2=screens F7=link F10=CoWriter
PROCO 3 - Ctrl MenuF1=help F3=update-menu F4=UseUpdatedMenu F5=batch-files F7=OS-command F8=config
F10=user-menu
PROCO 2 - Alt MenuF1=help F2=screens F7=link F10=CoWriter
PROCO 3 - Ctrl MenuF1=help F3=update-menu F4=UseUpdatedMenu F5=batch-files F7=OS-command F8=config
F10=user-menu
EDIT 1 -MenuF1=help F2=COBOL F3=InsertLine
F4=DeleteLine F5=RepeatLine F6=RestoreLine F7=RetypeChar F8=RestoreChar
F9=WordLeft F10=WordRight
EDIT 1 -MenuF1=help F2=COBOL F3=InsertLine
F4=DeleteLine F5=RepeatLine F6=RestoreLine F7=RetypeChar F8=RestoreChar
F9=WordLeft F10=WordRight
EDIT 2 - Alt MenuF1=help F2=library F3=load-file F4=save-
file F5=split-line F6=join-line F7=print F8=calculate F9=untype-word-left
F10=DeleteWord
EDIT 3 - Ctrl MenuF1=help F2=find F3=block F4=clear F5=margins F6=draw/forms F7=tags
F8=WordWrap F9=window F10=scroll <-/-> (move in window) Home/End (of text) PgUp/PgDn
EDIT 2 - Alt MenuF1=help F2=library F3=load-file F4=save-
file F5=split-line F6=join-line F7=print F8=calculate F9=untype-word-left
F10=DeleteWord
EDIT 3 - Ctrl MenuF1=help F2=find F3=block F4=clear F5=margins F6=draw/forms F7=tags
F8=WordWrap F9=window F10=scroll <-/-> (move in window) Home/End (of text) PgUp/PgDn
COBOL menuF1=help F2=check/animate F3=cmd-file
F7=locate-previous F8=locate-next F9=locate-current
COBOL menuF1=help F2=check/animate F3=cmd-file
F7=locate-previous F8=locate-next F9=locate-current
Checker MenuF1=help F2=check/anim F3=pause
F4=list F6=lang F7=ref F9/F10=directives
Checker MenuF1=help F2=check/anim F3=pause
F4=list F6=lang F7=ref F9/F10=directives
Animate-MenuF1=help F2=view F3=align F4=exchange F5=where F6=look-up F9/F10=word-</>
Escape Animate Step Wch Go Zoom nx-If Prfm Rst Brk Env Qury Find Locate Txt Do
Animate-MenuF1=help F2=view F3=align F4=exchange F5=where F6=look-up F9/F10=word-</>
Escape Animate Step Wch Go Zoom nx-If Prfm Rst Brk Env Qury Find Locate Txt Do
ALT key
CTRL key
ALT key
CTRL key
43
COBOL COBOL BasicsBasics
2 2
44
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 Group Items/RecordsItems/Records
StudentDetails
WORKING-STORAGE SECTION.01 StudentDetails PIC X(26).
WORKING-STORAGE SECTION.01 StudentDetails PIC X(26).
45
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
StudentDetails
StudentName StudentId CourseCode Grant Gender
Group Items/RecordsGroup Items/Records
WORKING-STORAGE SECTION.01 StudentDetails.
0202 StudentNameStudentName PIC X(10).PIC X(10).0202 StudentIdStudentId PIC 9(7).PIC 9(7).0202 CourseCodeCourseCode PIC X(4).PIC X(4).0202 GrantGrant PIC 9(4).PIC 9(4).0202 GenderGender PIC X.PIC X.
WORKING-STORAGE SECTION.01 StudentDetails.
0202 StudentNameStudentName PIC X(10).PIC X(10).0202 StudentIdStudentId PIC 9(7).PIC 9(7).0202 CourseCodeCourseCode PIC X(4).PIC X(4).0202 GrantGrant PIC 9(4).PIC 9(4).0202 GenderGender PIC X.PIC X.
46
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
StudentDetails
Surname Initials
WORKING-STORAGE SECTION.01 StudentDetails.
0202 StudentName.StudentName.03 Surname03 Surname PIC X(8).PIC X(8).03 Initials03 Initials PIC XX.PIC XX.
0202 StudentIdStudentId PIC 9(7).PIC 9(7).0202 CourseCodeCourseCode PIC X(4).PIC X(4).0202 GrantGrant PIC 9(4).PIC 9(4).0202 GenderGender PIC X.PIC X.
WORKING-STORAGE SECTION.01 StudentDetails.
0202 StudentName.StudentName.03 Surname03 Surname PIC X(8).PIC X(8).03 Initials03 Initials PIC XX.PIC XX.
0202 StudentIdStudentId PIC 9(7).PIC 9(7).0202 CourseCodeCourseCode PIC X(4).PIC X(4).0202 GrantGrant PIC 9(4).PIC 9(4).0202 GenderGender PIC X.PIC X.
StudentName StudentId CourseCode Grant Gender
Group Items/RecordsGroup Items/Records
47
LEVEL Numbers express DATA LEVEL Numbers express DATA hierarchyhierarchy
In COBOL, level numbers are used to decompose a structure into it’s constituent parts.
In this hierarchical structure the higher the level number, the lower the item is in the hierarchy. At the lowest level the data is completely atomic.
The level numbers 01 through 49 are general level numbers but there are also special level numbers such as 66, 77 and 88.
In a hierarchical data description what is important is the relationship of the level numbers to one another, not the actual level numbers used.
48
LEVEL Numbers express DATA LEVEL Numbers express DATA hierarchyhierarchy
In COBOL, level numbers are used to decompose a structure into it’s constituent parts.
In this hierarchical structure the higher the level number, the lower the item is in the hierarchy. At the lowest level the data is completely atomic.
The level numbers 01 through 49 are general level numbers but there are also special level numbers such as 66, 77 and 88.
In a hierarchical data description what is important is the relationship of the level numbers to one another, not the actual level numbers used.
01 StudentDetails.02 StudentName.
03 Surname PIC X(8).03 Initials PIC XX.
02 StudentId PIC 9(7).02 CourseCode PIC X(4).02 Grant PIC 9(4).02 Gender PIC X.
01 StudentDetails.02 StudentName.
03 Surname PIC X(8).03 Initials PIC XX.
02 StudentId PIC 9(7).02 CourseCode PIC X(4).02 Grant PIC 9(4).02 Gender PIC X.
01 StudentDetails.05 StudentName.
10 Surname PIC X(8).10 Initials PIC XX.
05 StudentId PIC 9(7).05 CourseCode PIC X(4).05 Grant PIC 9(4).05 Gender PIC X.
01 StudentDetails.05 StudentName.
10 Surname PIC X(8).10 Initials PIC XX.
05 StudentId PIC 9(7).05 CourseCode PIC X(4).05 Grant PIC 9(4).05 Gender PIC X.
=
49
Group and elementary items.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.
50
PICTUREs for Group ItemsPICTUREs 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.
51
Assignment in COBOLAssignment 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.
52
The MOVE VerbThe MOVE Verb
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.
MOVE TO ...Identifier
LiteralIdentifier
53
MOVE “RYAN” TO Surname.MOVE “FITZPATRICK” TO Surname.MOVE “RYAN” TO Surname.MOVE “FITZPATRICK” TO Surname.
01 Surname PIC X(8).
MOVE-ing MOVE-ing DataData
C O U G H L A N
54
R Y A N
MOVE “RYAN” TO Surname.MOVE “RYAN” TO Surname.MOVE “FITZPATRICK” TO Surname.MOVE “RYAN” TO Surname.MOVE “RYAN” TO Surname.MOVE “FITZPATRICK” TO Surname.
01 Surname PIC X(8).
MOVEing MOVEing DataData
55
MOVE “RYAN” TO Surname.MOVE “FITZPATRICK” TO Surname.MOVE “FITZPATRICK” TO Surname.MOVE “RYAN” TO Surname.MOVE “FITZPATRICK” TO Surname.MOVE “FITZPATRICK” TO Surname.
01 Surname PIC X(8).
MOVEing DataMOVEing Data
F I T Z P A T R I C K
56
MOVEing to a numeric item.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.
57
MOVE ZEROS TO GrossPay.
MOVE 12.4 TO GrossPay.
MOVE 123.456 TO GrossPay.
MOVE 12345.757 TO GrossPay.
01 GrossPay PIC 9(4)V99.
0 0 0 0 0 0
0 0 1 2 4 0
0 1 2 3 4 5 6
1 2 3 4 5 7 5 7
GrossPay
GrossPay
GrossPay
GrossPay
58
MOVE 1234 TO CountyPop.
MOVE 12.4 TO CountyPop.
MOVE 154 TO Price.
MOVE 3552.75 TO Price.
01 CountyPop PIC 999.01 Price PIC 999V99.
1 2 3 4
0 1 2 4
1 5 4 0 0
3 5 5 2 7 5
Price
CountyPop
CountyPop
Price
59
Legal MOVEsLegal MOVEsCertain combinations of sending and receiving data types are not permitted (even by COBOL).
60
The DISPLAY VerbThe DISPLAY Verb
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.
DISPLAY Identifier
Literal
Identifier
Literal ...
UPON WITH NO ADVANCING
Mnemonic - Name
61
The ACCEPT The ACCEPT verbverb
Format 1. ACCEPT Identifier FROM Mnemonic - name
Format 2. ACCEPT Identifier FROM
DATE
DAY
DAY - OF - WEEK
TIME
01 CurrentDate01 CurrentDate PIC 9(6).PIC 9(6).* YYMMDD
01 DayOfYear01 DayOfYear PIC 9(5).PIC 9(5).* YYDDD
01 Day0fWeek01 Day0fWeek PIC 9.PIC 9.* D (1=Monday)
01 CurrentTime 01 CurrentTime PIC 9(8).PIC 9(8).* HHMMSSss s = S/100
01 CurrentDate01 CurrentDate PIC 9(6).PIC 9(6).* YYMMDD
01 DayOfYear01 DayOfYear PIC 9(5).PIC 9(5).* YYDDD
01 Day0fWeek01 Day0fWeek PIC 9.PIC 9.* D (1=Monday)
01 CurrentTime 01 CurrentTime PIC 9(8).PIC 9(8).* HHMMSSss s = S/100
62
PROCEDURE DIVISION.Begin. DISPLAY "Enter student details using template below". DISPLAY "NNNNNNNNNNSSSSSSSCCCCGGGGS ". ACCEPT StudentDetails. ACCEPT CurrentDate FROM DATE. ACCEPT DayOfYear FROM DAY. ACCEPT CurrentTime FROM TIME. DISPLAY "Name is ", Initials SPACE Surname. DISPLAY "Date is " CurrentDay SPACE CurrentMonth SPACE CurrentYear. DISPLAY "Today is day " YearDay " of the year". DISPLAY "The time is " CurrentHour ":" CurrentMinute. STOP RUN.
PROCEDURE DIVISION.Begin. DISPLAY "Enter student details using template below". DISPLAY "NNNNNNNNNNSSSSSSSCCCCGGGGS ". ACCEPT StudentDetails. ACCEPT CurrentDate FROM DATE. ACCEPT DayOfYear FROM DAY. ACCEPT CurrentTime FROM TIME. DISPLAY "Name is ", Initials SPACE Surname. DISPLAY "Date is " CurrentDay SPACE CurrentMonth SPACE CurrentYear. DISPLAY "Today is day " YearDay " of the year". DISPLAY "The time is " CurrentHour ":" CurrentMinute. STOP RUN.
$ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. AcceptAndDisplay.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 StudentDetails. 02 StudentName. 03 Surname PIC X(8). 03 Initials PIC XX. 02 StudentId PIC 9(7). 02 CourseCode PIC X(4). 02 Grant PIC 9(4). 02 Gender PIC X.
01 CurrentDate. 02 CurrentYear PIC 99. 02 CurrentMonth PIC 99. 02 CurrentDay PIC 99.
01 DayOfYear. 02 FILLER PIC 99. 02 YearDay PIC 9(3).
01 CurrentTime. 02 CurrentHour PIC 99. 02 CurrentMinute PIC 99. 02 FILLER PIC 9(4).
$ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. AcceptAndDisplay.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 StudentDetails. 02 StudentName. 03 Surname PIC X(8). 03 Initials PIC XX. 02 StudentId PIC 9(7). 02 CourseCode PIC X(4). 02 Grant PIC 9(4). 02 Gender PIC X.
01 CurrentDate. 02 CurrentYear PIC 99. 02 CurrentMonth PIC 99. 02 CurrentDay PIC 99.
01 DayOfYear. 02 FILLER PIC 99. 02 YearDay PIC 9(3).
01 CurrentTime. 02 CurrentHour PIC 99. 02 CurrentMinute PIC 99. 02 FILLER PIC 9(4).
Enter student details using template belowNNNNNNNNNNSSSSSSSCCCCGGGGSCOUGHLANMS9476532LM511245MName is MS COUGHLANDate is 24 01 94Today is day 024 of the yearThe time is 22:23
Enter student details using template belowNNNNNNNNNNSSSSSSSCCCCGGGGSCOUGHLANMS9476532LM511245MName is MS COUGHLANDate is 24 01 94Today is day 024 of the yearThe time is 22:23
Run of Accept and Display programRun of Accept and Display program
63
ALGORITALGORITHMS HMS
64
IDENTIFICATION DIVISION.PROGRAM-ID. FragmentAFragmentA.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.
PROCEDURE DIVISION.Calc-ResultCalc-Result. ACCEPT Num1. MULTIPLY Num1 BY Num2 GIVING Result. ACCEPT Num2. DISPLAY "Result is = ", Result. STOP RUN.
Num1 Num2 ResultNum1 Num2 Result
00 00 0000
DATA
65
IDENTIFICATION DIVISION.PROGRAM-ID. FragmentA.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.
PROCEDURE DIVISION.Calc-Result. ACCEPT Num1ACCEPT Num1. MULTIPLY Num1 BY Num2 GIVING Result. ACCEPT Num2. DISPLAY "Result is = ", Result. STOP RUN.
Num1 Num2 ResultNum1 Num2 Result
99 00 0000
DATA
66
IDENTIFICATION DIVISION.PROGRAM-ID. FragmentA.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.
PROCEDURE DIVISION.Calc-Result. ACCEPT Num1. MULTIPLY Num1 BY Num2 GIVING ResultMULTIPLY Num1 BY Num2 GIVING Result. ACCEPT Num2. DISPLAY "Result is = ", Result. STOP RUN.
Num1 Num2 ResultNum1 Num2 Result
99 00 0000
DATA
67
IDENTIFICATION DIVISION.PROGRAM-ID. FragmentA.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.
PROCEDURE DIVISION.Calc-Result. ACCEPT Num1. MULTIPLY Num1 BY Num2 GIVING Result. ACCEPT Num2ACCEPT Num2. DISPLAY "Result is = ", Result. STOP RUN.
Num1 Num2 ResultNum1 Num2 Result
00 55 0000
DATA
68
IDENTIFICATION DIVISION.PROGRAM-ID. FragmentA.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.
PROCEDURE DIVISION.Calc-Result. ACCEPT Num1. MULTIPLY Num1 BY Num2 GIVING Result. ACCEPT Num2. DISPLAY "Result is = ", ResultDISPLAY "Result is = ", Result. STOP RUN.
Num1 Num2 ResultNum1 Num2 Result
99 55 0000
DATA
69
Sequence.
Selection.
Iteration.
Programs are written using three Programs are written using three main programming constructsmain programming constructs.
70
Num1 Num2 Result OperatorNum1 Num2 Result Operator
IDENTIFICATION DIVISION.PROGRAM-ID. Selection-ProgramSelection-Program.AUTHOR. Michael Coughlan.
DATA DIVISION.DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.01 Operator PIC X VALUE SPACE.
PROCEDURE DIVISION.CalculatorCalculator. ACCEPT Num1. ACCEPT Num2. ACCEPT Operator IF Operator = "+" THEN ADD Num1, Num2 GIVING Result END-IF IF Operator = "*" THEN MULTIPLY Num1 BY Num2 GIVING Result END-IF. DISPLAY "Result is = ", Result. STOP RUN.
00 00 0000
DATA
__
71
IDENTIFICATION DIVISION.PROGRAM-ID. Selection-Program.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.01 Operator PIC X VALUE SPACE.
PROCEDURE DIVISION.Calculator. ACCEPT Num1ACCEPT Num1. ACCEPT Num2. ACCEPT Operator IF Operator = "+" THEN ADD Num1, Num2 GIVING Result END-IF IF Operator = "*" THEN MULTIPLY Num1 BY Num2 GIVING Result END-IF. DISPLAY "Result is = ", Result. STOP RUN.
Num1 Num2 Result OperatorNum1 Num2 Result Operator
77 00 0000
DATA
__
72
IDENTIFICATION DIVISION.PROGRAM-ID. Selection-Program.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.01 Operator PIC X VALUE SPACE.
PROCEDURE DIVISION.Calculator. ACCEPT Num1. ACCEPT Num2ACCEPT Num2. ACCEPT Operator IF Operator = "+" THEN ADD Num1, Num2 GIVING Result END-IF IF Operator = "*" THEN MULTIPLY Num1 BY Num2 GIVING Result END-IF. DISPLAY "Result is = ", Result. STOP RUN.
Num1 Num2 Result OperatorNum1 Num2 Result Operator
77 33 0000
DATA
__
73
IDENTIFICATION DIVISION.PROGRAM-ID. Selection-Program.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.01 Operator PIC X VALUE SPACE.
PROCEDURE DIVISION.Calculator. ACCEPT Num1. ACCEPT Num2. ACCEPT OperatorACCEPT Operator IF Operator = "+" THEN ADD Num1, Num2 GIVING Result END-IF IF Operator = "*" THEN MULTIPLY Num1 BY Num2 GIVING Result END-IF. DISPLAY "Result is = ", Result. STOP RUN.
Num1 Num2 Result OperatorNum1 Num2 Result Operator
77 33 0000
DATA
++
74
IDENTIFICATION DIVISION.PROGRAM-ID. Selection-Program.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.01 Operator PIC X VALUE SPACE.
PROCEDURE DIVISION.Calculator. ACCEPT Num1. ACCEPT Num2. ACCEPT Operator IF Operator = "+" THENIF Operator = "+" THEN ADD Num1, Num2 GIVING Result END-IFEND-IF IF Operator = "*" THEN MULTIPLY Num1 BY Num2 GIVING Result END-IF. DISPLAY "Result is = ", Result. STOP RUN.
Num1 Num2 Result OperatorNum1 Num2 Result Operator
77 33 0000
DATA
++
75
IDENTIFICATION DIVISION.PROGRAM-ID. Selection-Program.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.01 Operator PIC X VALUE SPACE.
PROCEDURE DIVISION.Calculator. ACCEPT Num1. ACCEPT Num2. ACCEPT Operator IF Operator = "+" THEN ADD Num1, Num2 GIVING ResultADD Num1, Num2 GIVING Result END-IF IF Operator = "*" THEN MULTIPLY Num1 BY Num2 GIVING Result END-IF. DISPLAY "Result is = ", Result. STOP RUN.
Num1 Num2 Result OperatorNum1 Num2 Result Operator
77 33 1010
DATA
++
76
IDENTIFICATION DIVISION.PROGRAM-ID. Selection-Program.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.01 Operator PIC X VALUE SPACE.
PROCEDURE DIVISION.Calculator. ACCEPT Num1. ACCEPT Num2. ACCEPT Operator IF Operator = "+" THEN ADD Num1, Num2 GIVING Result END-IF IF Operator = "*" THENIF Operator = "*" THEN MULTIPLY Num1 BY Num2 GIVING Result END-IFEND-IF. DISPLAY "Result is = ", Result. STOP RUN.
Num1 Num2 Result OperatorNum1 Num2 Result Operator
77 33 1010
DATA
++
77
IDENTIFICATION DIVISION.PROGRAM-ID. Selection-Program.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.01 Operator PIC X VALUE SPACE.
PROCEDURE DIVISION.Calculator. ACCEPT Num1. ACCEPT Num2. ACCEPT Operator IF Operator = "+" THEN ADD Num1, Num2 GIVING Result END-IF IF Operator = "*" THEN MULTIPLY Num1 BY Num2 GIVING Result END-IF. DISPLAY "Result is = ", ResultDISPLAY "Result is = ", Result. STOP RUN.
Num1 Num2 Result OperatorNum1 Num2 Result Operator
77 33 1010
DATA
++
78
IDENTIFICATION DIVISION.PROGRAM-ID. Iteration-ProgramIteration-Program.AUTHOR. Michael Coughlan.
DATA DIVISIONDATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.01 Operator PIC X VALUE SPACE.
PROCEDURE DIVISION.Calculator. PERFORM 5 TIMES ACCEPT Num1 ACCEPT Num2 ACCEPT Operator IF Operator = "+" THEN ADD Num1, Num2 GIVING Result END-IF IF Operator = "*" THEN MULTIPLY Num1 BY Num2 GIVING Result END-IF DISPLAY "Result is = ", Result END-PERFORM. STOP RUN.
DATANum1 Num2 Result OperatorNum1 Num2 Result Operator
00 00 0000
DATA
__
Ex2: ITERATION PROGRAMEx2: ITERATION PROGRAM
79
IDENTIFICATION DIVISION.PROGRAM-ID. Iteration-Program.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.01 Operator PIC X VALUE SPACE.
PROCEDURE DIVISION.Calculator. PERFORM 5 TIMESPERFORM 5 TIMES ACCEPT Num1 ACCEPT Num2 ACCEPT Operator IF Operator = "+" THEN ADD Num1, Num2 GIVING Result END-IF IF Operator = "*" THEN MULTIPLY Num1 BY Num2 GIVING Result END-IF DISPLAY "Result is = ", Result END-PERFORMEND-PERFORM. STOP RUN.
DATANum1 Num2 Result OperatorNum1 Num2 Result Operator
00 00 0000
DATA
__
80
IDENTIFICATION DIVISION.PROGRAM-ID. Iteration-Program.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.01 Operator PIC X VALUE SPACE.
PROCEDURE DIVISION.Calculator. PERFORM 5 TIMES ACCEPT Num1ACCEPT Num1 ACCEPT Num2 ACCEPT Operator IF Operator = "+" THEN ADD Num1, Num2 GIVING Result END-IF IF Operator = "*" THEN MULTIPLY Num1 BY Num2 GIVING Result END-IF DISPLAY "Result is = ", Result END-PERFORM. STOP RUN.
DATANum1 Num2 Result OperatorNum1 Num2 Result Operator
55 00 0000
DATA
__
81
IDENTIFICATION DIVISION.PROGRAM-ID. Iteration-Program.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.01 Operator PIC X VALUE SPACE.
PROCEDURE DIVISION.Calculator. PERFORM 5 TIMES ACCEPT Num1 ACCEPT Num2ACCEPT Num2 ACCEPT Operator IF Operator = "+" THEN ADD Num1, Num2 GIVING Result END-IF IF Operator = "*" THEN MULTIPLY Num1 BY Num2 GIVING Result END-IF DISPLAY "Result is = ", Result END-PERFORM. STOP RUN.
DATANum1 Num2 Result OperatorNum1 Num2 Result Operator
55 33 0000
DATA
__
82
IDENTIFICATION DIVISION.PROGRAM-ID. Iteration-Program.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.01 Operator PIC X VALUE SPACE.
PROCEDURE DIVISION.Calculator. PERFORM 5 TIMES ACCEPT Num1 ACCEPT Num2 ACCEPT OperatorACCEPT Operator IF Operator = "+" THEN ADD Num1, Num2 GIVING Result END-IF IF Operator = "*" THEN MULTIPLY Num1 BY Num2 GIVING Result END-IF DISPLAY "Result is = ", Result END-PERFORM. STOP RUN.
DATANum1 Num2 Result OperatorNum1 Num2 Result Operator
55 33 0000
DATA
**
83
IDENTIFICATION DIVISION.PROGRAM-ID. Iteration-Program.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.01 Operator PIC X VALUE SPACE.
PROCEDURE DIVISION.Calculator. PERFORM 5 TIMES ACCEPT Num1 ACCEPT Num2 ACCEPT Operator IF Operator = "+" THENIF Operator = "+" THEN ADD Num1, Num2 GIVING Result END-IFEND-IF IF Operator = "*" THEN MULTIPLY Num1 BY Num2 GIVING Result END-IF DISPLAY "Result is = ", Result END-PERFORM. STOP RUN.
DATANum1 Num2 Result OperatorNum1 Num2 Result Operator
55 33 0000
DATA
**
84
IDENTIFICATION DIVISION.PROGRAM-ID. Iteration-Program.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.01 Operator PIC X VALUE SPACE.
PROCEDURE DIVISION.Calculator. PERFORM 5 TIMES ACCEPT Num1 ACCEPT Num2 ACCEPT Operator IF Operator = "+" THEN ADD Num1, Num2 GIVING Result END-IF IF Operator = "*" THENIF Operator = "*" THEN MULTIPLY Num1 BY Num2 GIVING Result END-IFEND-IF DISPLAY "Result is = ", Result END-PERFORM. STOP RUN.
DATANum1 Num2 Result OperatorNum1 Num2 Result Operator
55 33 0000
DATA
**
85
IDENTIFICATION DIVISION.PROGRAM-ID. Iteration-Program.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.01 Operator PIC X VALUE SPACE.
PROCEDURE DIVISION.Calculator. PERFORM 5 TIMES ACCEPT Num1 ACCEPT Num2 ACCEPT Operator IF Operator = "+" THEN ADD Num1, Num2 GIVING Result END-IF IF Operator = "*" THEN MULTIPLY Num1 BY Num2 GIVING ResultMULTIPLY Num1 BY Num2 GIVING Result END-IF DISPLAY "Result is = ", Result END-PERFORM. STOP RUN.
DATANum1 Num2 Result OperatorNum1 Num2 Result Operator
55 33 1515
DATA
**
86
IDENTIFICATION DIVISION.PROGRAM-ID. Iteration-Program.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.01 Operator PIC X VALUE SPACE.
PROCEDURE DIVISION.Calculator. PERFORM 5 TIMES ACCEPT Num1 ACCEPT Num2 ACCEPT Operator IF Operator = "+" THEN ADD Num1, Num2 GIVING Result END-IF IF Operator = "*" THEN MULTIPLY Num1 BY Num2 GIVING Result END-IF DISPLAY "Result is = ", ResultDISPLAY "Result is = ", Result END-PERFORM. STOP RUN.
DATANum1 Num2 Result OperatorNum1 Num2 Result Operator
55 33 1515
DATA
**
87
IDENTIFICATION DIVISION.PROGRAM-ID. Iteration-Program.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.01 Operator PIC X VALUE SPACE.
PROCEDURE DIVISION.Calculator. PERFORM 5 TIMES ACCEPT Num1ACCEPT Num1 ACCEPT Num2 ACCEPT Operator IF Operator = "+" THEN ADD Num1, Num2 GIVING Result END-IF IF Operator = "*" THEN MULTIPLY Num1 BY Num2 GIVING Result END-IF DISPLAY "Result is = ", Result END-PERFORM. STOP RUN.
DATANum1 Num2 Result OperatorNum1 Num2 Result Operator
99 33 1515
DATA
**
88
IDENTIFICATION DIVISION.PROGRAM-ID. Iteration-Program.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.01 Operator PIC X VALUE SPACE.
PROCEDURE DIVISION.Calculator. PERFORM 5 TIMES ACCEPT Num1 ACCEPT Num2ACCEPT Num2 ACCEPT Operator IF Operator = "+" THEN ADD Num1, Num2 GIVING Result END-IF IF Operator = "*" THEN MULTIPLY Num1 BY Num2 GIVING Result END-IF DISPLAY "Result is = ", Result END-PERFORM. STOP RUN.
DATANum1 Num2 Result OperatorNum1 Num2 Result Operator
99 33 1515
DATA
**
89
General General IntroductionIntroductionAlgorithmsAlgorithms
90
Let’s write a programLet’s write a program
A program is a collection of statements written in a language the computer understands.
A computer executes program statements one after another in sequence until it reaches the end of the program unless some statement in the program alters the order of execution.
Let’s write a program to accept two numbers from the user, multiply them together and display the result on the screen.
We’ll write the program in COBOL.
What COBOL program statements will we need to do the job?
91
Program StatementsProgram Statements
We need a statement to take in the first number and store it in a named memory location.– ACCEPT Num1.
We need a statement to take in the second number and store it in a named memory location.– ACCEPT Num2.
We need a statement to multiply the two numbers together and store the result in a named location.– MULTIPLY Num1 BY Num2 GIVING Result.
We need a statement to display the result on the screen.– DISPLAY "Result is = ", Result.
92
IDENTIFICATION DIVISION.PROGRAM-ID. FragmentAFragmentA.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.
PROCEDURE DIVISION.Calc-ResultCalc-Result. ACCEPT Num1. MULTIPLY Num1 BY Num2 GIVING Result. ACCEPT Num2. DISPLAY "Result is = ", Result. STOP RUN.
Num1 Num2 ResultNum1 Num2 Result
00 00 0000
DATA
93
IDENTIFICATION DIVISION.PROGRAM-ID. FragmentA.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.
PROCEDURE DIVISION.Calc-Result. ACCEPT Num1ACCEPT Num1. MULTIPLY Num1 BY Num2 GIVING Result. ACCEPT Num2. DISPLAY "Result is = ", Result. STOP RUN.
Num1 Num2 ResultNum1 Num2 Result
99 00 0000
DATA
94
IDENTIFICATION DIVISION.PROGRAM-ID. FragmentA.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.
PROCEDURE DIVISION.Calc-Result. ACCEPT Num1. MULTIPLY Num1 BY Num2 GIVING ResultMULTIPLY Num1 BY Num2 GIVING Result. ACCEPT Num2. DISPLAY "Result is = ", Result. STOP RUN.
Num1 Num2 ResultNum1 Num2 Result
99 00 0000
DATA
95
IDENTIFICATION DIVISION.PROGRAM-ID. FragmentA.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.
PROCEDURE DIVISION.Calc-Result. ACCEPT Num1. MULTIPLY Num1 BY Num2 GIVING Result. ACCEPT Num2ACCEPT Num2. DISPLAY "Result is = ", Result. STOP RUN.
Num1 Num2 ResultNum1 Num2 Result
00 55 0000
DATA
96
IDENTIFICATION DIVISION.PROGRAM-ID. FragmentA.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.
PROCEDURE DIVISION.Calc-Result. ACCEPT Num1. MULTIPLY Num1 BY Num2 GIVING Result. ACCEPT Num2. DISPLAY "Result is = ", ResultDISPLAY "Result is = ", Result. STOP RUN.
Num1 Num2 ResultNum1 Num2 Result
99 55 0000
DATA
Oh No!!Oh No!!We got the We got the
wrong wrong answer.answer.Let’s try Let’s try again.again.
97
IDENTIFICATION DIVISION.PROGRAM-ID. FragmentBFragmentB.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.
PROCEDURE DIVISION.Calc-ResultCalc-Result. ACCEPT Num1. ACCEPT Num2. DISPLAY "Result is = ", Result. MULTIPLY Num1 BY Num2 GIVING Result. STOP RUN.
Num1 Num2 ResultNum1 Num2 Result
00 00 0000
DATA
98
IDENTIFICATION DIVISION.PROGRAM-ID. FragmentB.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.
PROCEDURE DIVISION.Calc-Result. ACCEPT Num1.ACCEPT Num1. ACCEPT Num2. DISPLAY "Result is = ", Result. MULTIPLY Num1 BY Num2 GIVING Result. STOP RUN.
Num1 Num2 ResultNum1 Num2 Result
99 00 0000
DATA
99
IDENTIFICATION DIVISION.PROGRAM-ID. FragmentB.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.
PROCEDURE DIVISION.Calc-Result. ACCEPT Num1. ACCEPT Num2ACCEPT Num2. DISPLAY "Result is = ", Result. MULTIPLY Num1 BY Num2 GIVING Result. STOP RUN.
Num1 Num2 ResultNum1 Num2 Result
99 55 0000
DATA
100
IDENTIFICATION DIVISION.PROGRAM-ID. FragmentB.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.
PROCEDURE DIVISION.Calc-Result. ACCEPT Num1. ACCEPT Num2. DISPLAY "Result is = ", ResultDISPLAY "Result is = ", Result. MULTIPLY Num1 BY Num2 GIVING Result. STOP RUN.
Num1 Num2 ResultNum1 Num2 Result
99 55 0000
DATA
Oh No!!Oh No!!We got the We got the
wrong answer wrong answer again.again.
Let’s have one Let’s have one more try.more try.
101
IDENTIFICATION DIVISION.PROGRAM-ID. FragmentB.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.
PROCEDURE DIVISION.Calc-Result. ACCEPT Num1. ACCEPT Num2. DISPLAY "Result is = ", Result. MULTIPLY Num1 BY Num2 GIVING ResultMULTIPLY Num1 BY Num2 GIVING Result. STOP RUN.
Num1 Num2 ResultNum1 Num2 Result
99 55 4545
DATA
102
Num1 Num2 ResultNum1 Num2 Result
IDENTIFICATION DIVISION.PROGRAM-ID. Sequence-ProgramSequence-Program.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.
PROCEDURE DIVISION.Calc-ResultCalc-Result. ACCEPT Num1. ACCEPT Num2. MULTIPLY Num1 BY Num2 GIVING Result. DISPLAY "Result is = ", Result. STOP RUN.
00 00 0000
DATA
103
IDENTIFICATION DIVISION.PROGRAM-ID. Sequence-Program.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.
PROCEDURE DIVISION.Calc-Result. ACCEPT Num1ACCEPT Num1. ACCEPT Num2. MULTIPLY Num1 BY Num2 GIVING Result. DISPLAY "Result is = ", Result. STOP RUN.
9 0 00
Num1 Num2 Result
DATA
104
IDENTIFICATION DIVISION.PROGRAM-ID. Sequence-Program.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.
PROCEDURE DIVISION.Calc-Result. ACCEPT Num1. ACCEPT Num2ACCEPT Num2. MULTIPLY Num1 BY Num2 GIVING Result. DISPLAY "Result is = ", Result. STOP RUN.
9 5 00
Num1 Num2 Result
DATA
105
IDENTIFICATION DIVISION.PROGRAM-ID. Sequence-Program.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.
PROCEDURE DIVISION.Calc-Result. ACCEPT Num1. ACCEPT Num2. MULTIPLY Num1 BY Num2 GIVING ResultMULTIPLY Num1 BY Num2 GIVING Result. DISPLAY "Result is = ", Result. STOP RUN.
9 5 45
Num1 Num2 Result
DATA
106
IDENTIFICATION DIVISION.PROGRAM-ID. Sequence-Program.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.
PROCEDURE DIVISION.Calc-Result. ACCEPT Num1. ACCEPT Num2. MULTIPLY Num1 BY Num2 GIVING Result. DISPLAY "Result is = ", ResultDISPLAY "Result is = ", Result. STOP RUN.
9 5 45
Num1 Num2 Result
DATA
Right .. At last!!Right .. At last!!
It’s not enough to It’s not enough to know what know what
statements we need. statements we need. We must make sure We must make sure
the computer the computer executes them in the executes them in the
right order.right order.
107
Sequence.
Selection.
Iteration.
Programs are written using three Programs are written using three main programming constructsmain programming constructs.
108
Num1 Num2 Result OperatorNum1 Num2 Result Operator
IDENTIFICATION DIVISION.PROGRAM-ID. Selection-ProgramSelection-Program.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.01 Operator PIC X VALUE SPACE.
PROCEDURE DIVISION.CalculatorCalculator. ACCEPT Num1. ACCEPT Num2. ACCEPT Operator IF Operator = "+" THEN ADD Num1, Num2 GIVING Result END-IF IF Operator = "*" THEN MULTIPLY Num1 BY Num2 GIVING Result END-IF. DISPLAY "Result is = ", Result. STOP RUN.
00 00 0000
DATA
__
109
IDENTIFICATION DIVISION.PROGRAM-ID. Selection-Program.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.01 Operator PIC X VALUE SPACE.
PROCEDURE DIVISION.Calculator. ACCEPT Num1ACCEPT Num1. ACCEPT Num2. ACCEPT Operator IF Operator = "+" THEN ADD Num1, Num2 GIVING Result END-IF IF Operator = "*" THEN MULTIPLY Num1 BY Num2 GIVING Result END-IF. DISPLAY "Result is = ", Result. STOP RUN.
Num1 Num2 Result OperatorNum1 Num2 Result Operator
77 00 0000
DATA
__
110
IDENTIFICATION DIVISION.PROGRAM-ID. Selection-Program.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.01 Operator PIC X VALUE SPACE.
PROCEDURE DIVISION.Calculator. ACCEPT Num1. ACCEPT Num2ACCEPT Num2. ACCEPT Operator IF Operator = "+" THEN ADD Num1, Num2 GIVING Result END-IF IF Operator = "*" THEN MULTIPLY Num1 BY Num2 GIVING Result END-IF. DISPLAY "Result is = ", Result. STOP RUN.
Num1 Num2 Result OperatorNum1 Num2 Result Operator
77 33 0000
DATA
__
111
IDENTIFICATION DIVISION.PROGRAM-ID. Selection-Program.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.01 Operator PIC X VALUE SPACE.
PROCEDURE DIVISION.Calculator. ACCEPT Num1. ACCEPT Num2. ACCEPT OperatorACCEPT Operator IF Operator = "+" THEN ADD Num1, Num2 GIVING Result END-IF IF Operator = "*" THEN MULTIPLY Num1 BY Num2 GIVING Result END-IF. DISPLAY "Result is = ", Result. STOP RUN.
Num1 Num2 Result OperatorNum1 Num2 Result Operator
77 33 0000
DATA
++
112
IDENTIFICATION DIVISION.PROGRAM-ID. Selection-Program.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.01 Operator PIC X VALUE SPACE.
PROCEDURE DIVISION.Calculator. ACCEPT Num1. ACCEPT Num2. ACCEPT Operator IF Operator = "+" THENIF Operator = "+" THEN ADD Num1, Num2 GIVING Result END-IFEND-IF IF Operator = "*" THEN MULTIPLY Num1 BY Num2 GIVING Result END-IF. DISPLAY "Result is = ", Result. STOP RUN.
Num1 Num2 Result OperatorNum1 Num2 Result Operator
77 33 0000
DATA
++
113
IDENTIFICATION DIVISION.PROGRAM-ID. Selection-Program.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.01 Operator PIC X VALUE SPACE.
PROCEDURE DIVISION.Calculator. ACCEPT Num1. ACCEPT Num2. ACCEPT Operator IF Operator = "+" THEN ADD Num1, Num2 GIVING ResultADD Num1, Num2 GIVING Result END-IF IF Operator = "*" THEN MULTIPLY Num1 BY Num2 GIVING Result END-IF. DISPLAY "Result is = ", Result. STOP RUN.
Num1 Num2 Result OperatorNum1 Num2 Result Operator
77 33 1010
DATA
++
114
IDENTIFICATION DIVISION.PROGRAM-ID. Selection-Program.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.01 Operator PIC X VALUE SPACE.
PROCEDURE DIVISION.Calculator. ACCEPT Num1. ACCEPT Num2. ACCEPT Operator IF Operator = "+" THEN ADD Num1, Num2 GIVING Result END-IF IF Operator = "*" THENIF Operator = "*" THEN MULTIPLY Num1 BY Num2 GIVING Result END-IFEND-IF. DISPLAY "Result is = ", Result. STOP RUN.
Num1 Num2 Result OperatorNum1 Num2 Result Operator
77 33 1010
DATA
++
115
IDENTIFICATION DIVISION.PROGRAM-ID. Selection-Program.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.01 Operator PIC X VALUE SPACE.
PROCEDURE DIVISION.Calculator. ACCEPT Num1. ACCEPT Num2. ACCEPT Operator IF Operator = "+" THEN ADD Num1, Num2 GIVING Result END-IF IF Operator = "*" THEN MULTIPLY Num1 BY Num2 GIVING Result END-IF. DISPLAY "Result is = ", ResultDISPLAY "Result is = ", Result. STOP RUN.
Num1 Num2 Result OperatorNum1 Num2 Result Operator
77 33 1010
DATA
++
116
IDENTIFICATION DIVISION.PROGRAM-ID. Iteration-ProgramIteration-Program.AUTHOR. Michael Coughlan.
DATA DIVISIONDATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.01 Operator PIC X VALUE SPACE.
PROCEDURE DIVISION.Calculator. PERFORM 5 TIMES ACCEPT Num1 ACCEPT Num2 ACCEPT Operator IF Operator = "+" THEN ADD Num1, Num2 GIVING Result END-IF IF Operator = "*" THEN MULTIPLY Num1 BY Num2 GIVING Result END-IF DISPLAY "Result is = ", Result END-PERFORM. STOP RUN.
DATANum1 Num2 Result OperatorNum1 Num2 Result Operator
00 00 0000
DATA
__
117
IDENTIFICATION DIVISION.PROGRAM-ID. Iteration-Program.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.01 Operator PIC X VALUE SPACE.
PROCEDURE DIVISION.Calculator. PERFORM 5 TIMESPERFORM 5 TIMES ACCEPT Num1 ACCEPT Num2 ACCEPT Operator IF Operator = "+" THEN ADD Num1, Num2 GIVING Result END-IF IF Operator = "*" THEN MULTIPLY Num1 BY Num2 GIVING Result END-IF DISPLAY "Result is = ", Result END-PERFORMEND-PERFORM. STOP RUN.
DATANum1 Num2 Result OperatorNum1 Num2 Result Operator
00 00 0000
DATA
__
118
IDENTIFICATION DIVISION.PROGRAM-ID. Iteration-Program.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.01 Operator PIC X VALUE SPACE.
PROCEDURE DIVISION.Calculator. PERFORM 5 TIMES ACCEPT Num1ACCEPT Num1 ACCEPT Num2 ACCEPT Operator IF Operator = "+" THEN ADD Num1, Num2 GIVING Result END-IF IF Operator = "*" THEN MULTIPLY Num1 BY Num2 GIVING Result END-IF DISPLAY "Result is = ", Result END-PERFORM. STOP RUN.
DATANum1 Num2 Result OperatorNum1 Num2 Result Operator
55 00 0000
DATA
__
119
IDENTIFICATION DIVISION.PROGRAM-ID. Iteration-Program.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.01 Operator PIC X VALUE SPACE.
PROCEDURE DIVISION.Calculator. PERFORM 5 TIMES ACCEPT Num1 ACCEPT Num2ACCEPT Num2 ACCEPT Operator IF Operator = "+" THEN ADD Num1, Num2 GIVING Result END-IF IF Operator = "*" THEN MULTIPLY Num1 BY Num2 GIVING Result END-IF DISPLAY "Result is = ", Result END-PERFORM. STOP RUN.
DATANum1 Num2 Result OperatorNum1 Num2 Result Operator
55 33 0000
DATA
__
120
IDENTIFICATION DIVISION.PROGRAM-ID. Iteration-Program.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.01 Operator PIC X VALUE SPACE.
PROCEDURE DIVISION.Calculator. PERFORM 5 TIMES ACCEPT Num1 ACCEPT Num2 ACCEPT OperatorACCEPT Operator IF Operator = "+" THEN ADD Num1, Num2 GIVING Result END-IF IF Operator = "*" THEN MULTIPLY Num1 BY Num2 GIVING Result END-IF DISPLAY "Result is = ", Result END-PERFORM. STOP RUN.
DATANum1 Num2 Result OperatorNum1 Num2 Result Operator
55 33 0000
DATA
**
121
IDENTIFICATION DIVISION.PROGRAM-ID. Iteration-Program.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.01 Operator PIC X VALUE SPACE.
PROCEDURE DIVISION.Calculator. PERFORM 5 TIMES ACCEPT Num1 ACCEPT Num2 ACCEPT Operator IF Operator = "+" THENIF Operator = "+" THEN ADD Num1, Num2 GIVING Result END-IFEND-IF IF Operator = "*" THEN MULTIPLY Num1 BY Num2 GIVING Result END-IF DISPLAY "Result is = ", Result END-PERFORM. STOP RUN.
DATANum1 Num2 Result OperatorNum1 Num2 Result Operator
55 33 0000
DATA
**
122
IDENTIFICATION DIVISION.PROGRAM-ID. Iteration-Program.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.01 Operator PIC X VALUE SPACE.
PROCEDURE DIVISION.Calculator. PERFORM 5 TIMES ACCEPT Num1 ACCEPT Num2 ACCEPT Operator IF Operator = "+" THEN ADD Num1, Num2 GIVING Result END-IF IF Operator = "*" THENIF Operator = "*" THEN MULTIPLY Num1 BY Num2 GIVING Result END-IFEND-IF DISPLAY "Result is = ", Result END-PERFORM. STOP RUN.
DATANum1 Num2 Result OperatorNum1 Num2 Result Operator
55 33 0000
DATA
**
123
IDENTIFICATION DIVISION.PROGRAM-ID. Iteration-Program.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.01 Operator PIC X VALUE SPACE.
PROCEDURE DIVISION.Calculator. PERFORM 5 TIMES ACCEPT Num1 ACCEPT Num2 ACCEPT Operator IF Operator = "+" THEN ADD Num1, Num2 GIVING Result END-IF IF Operator = "*" THEN MULTIPLY Num1 BY Num2 GIVING ResultMULTIPLY Num1 BY Num2 GIVING Result END-IF DISPLAY "Result is = ", Result END-PERFORM. STOP RUN.
DATANum1 Num2 Result OperatorNum1 Num2 Result Operator
55 33 1515
DATA
**
124
IDENTIFICATION DIVISION.PROGRAM-ID. Iteration-Program.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.01 Operator PIC X VALUE SPACE.
PROCEDURE DIVISION.Calculator. PERFORM 5 TIMES ACCEPT Num1 ACCEPT Num2 ACCEPT Operator IF Operator = "+" THEN ADD Num1, Num2 GIVING Result END-IF IF Operator = "*" THEN MULTIPLY Num1 BY Num2 GIVING Result END-IF DISPLAY "Result is = ", ResultDISPLAY "Result is = ", Result END-PERFORM. STOP RUN.
DATANum1 Num2 Result OperatorNum1 Num2 Result Operator
55 33 1515
DATA
**
125
IDENTIFICATION DIVISION.PROGRAM-ID. Iteration-Program.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.01 Operator PIC X VALUE SPACE.
PROCEDURE DIVISION.Calculator. PERFORM 5 TIMES ACCEPT Num1ACCEPT Num1 ACCEPT Num2 ACCEPT Operator IF Operator = "+" THEN ADD Num1, Num2 GIVING Result END-IF IF Operator = "*" THEN MULTIPLY Num1 BY Num2 GIVING Result END-IF DISPLAY "Result is = ", Result END-PERFORM. STOP RUN.
DATANum1 Num2 Result OperatorNum1 Num2 Result Operator
99 33 1515
DATA
**
126
IDENTIFICATION DIVISION.PROGRAM-ID. Iteration-Program.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.01 Operator PIC X VALUE SPACE.
PROCEDURE DIVISION.Calculator. PERFORM 5 TIMES ACCEPT Num1 ACCEPT Num2ACCEPT Num2 ACCEPT Operator IF Operator = "+" THEN ADD Num1, Num2 GIVING Result END-IF IF Operator = "*" THEN MULTIPLY Num1 BY Num2 GIVING Result END-IF DISPLAY "Result is = ", Result END-PERFORM. STOP RUN.
DATANum1 Num2 Result OperatorNum1 Num2 Result Operator
99 33 1515
DATA
**
127
Arithmetic Arithmetic and and
Edited Edited PicturesPictures
128
Arithmetic Verb Arithmetic Verb TemplateTemplate
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.
VERB Identifier
Literal
TO
FROM
BY
INTO
Identifier
Identifier GIVING Identifier ROUNDED
ON SIZE ERROR StatementBlock END - VERB
129
The ROUNDED optionThe 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 The ROUNDED option takes effect when, after decimal point alignment, the result calculated must be truncated on point alignment, the result calculated must be truncated on the right hand side. the right hand side.
The option adds 1 to the receiving item when the leftmost The option adds 1 to the receiving item when the leftmost truncated digit has an absolute value of 5 or greater.truncated digit has an absolute value of 5 or greater.
130
A size error condition exists when, after decimal point A size error condition exists when, after decimal point alignment, the result is truncated on either the alignment, the result is truncated on either the leftleft or the or the rightright hand side.hand side.
If an arithmetic statement has a rounded phrase then a size If an arithmetic statement has a rounded phrase then a size error only occurs if there is truncation on the error only occurs if there is truncation on the leftleft hand side hand side (most significant digits).(most significant digits).
Receiving Field Actual Result SIZE ERROR
PIC 9(3)V9. 245.96
PIC 9(3)V9. 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
The ON SIZE ERROR optionThe ON SIZE ERROR option
Yes
Yes
No
Yes
Yes
No
Yes
131
ADD ExamplesADD Examples
ADD Cash TO Total.BeforeBefore 3 1000AfterAfter
ADD Cash, 20 TO Total, Wage.Before Before 3 1000 100AfterAfter
ADD Cash, Total GIVING Result.BeforeBefore 3 1000 0015AfterAfter
ADD Males TO Females GIVING TotalStudents.Before Before 1500 0625 1234AfterAfter
ADD Cash TO Total.BeforeBefore 3 1000AfterAfter
ADD Cash, 20 TO Total, Wage.Before Before 3 1000 100AfterAfter
ADD Cash, Total GIVING Result.BeforeBefore 3 1000 0015AfterAfter
ADD Males TO Females GIVING TotalStudents.Before Before 1500 0625 1234AfterAfter
3 1003
3 1023 123
3 1000 1003
1500 0625 2125
132
SUBTRACT ExamplesSUBTRACT Examples
SUBTRACT Tax FROM GrossPay, Total.Before Before 120 4000 9120 AfterAfter
SUBTRACT Tax, 80 FROM Total.Before Before 100 480AfterAfter
SUBTRACT Tax FROM GrossPay GIVING NetPay.BeforeBefore 750 1000 0012AfterAfter
SUBTRACT Tax FROM GrossPay, Total.Before Before 120 4000 9120 AfterAfter
SUBTRACT Tax, 80 FROM Total.Before Before 100 480AfterAfter
SUBTRACT Tax FROM GrossPay GIVING NetPay.BeforeBefore 750 1000 0012AfterAfter
120 3880 9000
100 300
750 1000 0250
133
MULTIPLY and DIVIDE MULTIPLY and DIVIDE ExamplesExamples
MULTIPLY Subs BY Members GIVING TotalSubs ON SIZE ERROR DISPLAY "TotalSubs too small" END-MULTIPLY. Subs Members TotalSubsSubs Members TotalSubs
BeforeBefore 15.50 100 0123.45AfterAfter
MULTIPLY 10 BY Magnitude, Size.
BeforeBefore 355 125AfterAfter
DIVIDE Total BY Members GIVING Average ROUNDED.BeforeBefore 9234.55 100 1234.56AfterAfter
MULTIPLY Subs BY Members GIVING TotalSubs ON SIZE ERROR DISPLAY "TotalSubs too small" END-MULTIPLY. Subs Members TotalSubsSubs Members TotalSubs
BeforeBefore 15.50 100 0123.45AfterAfter
MULTIPLY 10 BY Magnitude, Size.
BeforeBefore 355 125AfterAfter
DIVIDE Total BY Members GIVING Average ROUNDED.BeforeBefore 9234.55 100 1234.56AfterAfter
15.50 100 1550.00
3550 1250
9234.55 100 92.35
134
The Divide ExceptionThe Divide Exception
DIVIDE INTO GIVING Identifier [ ROUNDED ] REMAINDER Identifier
ON SIZE ERROR
NOT ON SIZE ERROR StatementBlock END - DIVIDE
DIVIDE BY GIVING Identifier [ ROUNDED ] REMAINDER Identifier
ON SIZE ERROR
NOT ON SIZE ERROR StatementBlock END - DIVIDE
Identifier
Literal
Identifier
Literal
Identifier
Literal
Identifier
Literal
DIVIDE 201 BY 10 GIVING Quotient REMAINDER Remain.Before Before 209 424AfterAfter
DIVIDE 201 BY 10 GIVING Quotient REMAINDER Remain.Before Before 209 424AfterAfter
020 001
135
Compute IrishPrice = SterlingPrice / Rate * 100.Before Before 1000.50 156.25 87 AfterAfter
Compute IrishPrice = SterlingPrice / Rate * 100.Before Before 1000.50 156.25 87 AfterAfter 179.59 156.25 87
The COMPUTEThe COMPUTE COMPUTE Identifier [ ROUNDED ] . . . = ArithmeticExpression
ON SIZE ERROR
NOT ON SIZE ERROR StatementBlock END - COMPUTE
Precedence Rules.Precedence Rules.1.1. **** = POWER NN
2.2. ** = MULTIPLY x// = DIVIDE ÷
3.3. ++ = ADD +-- = SUBTRACT -
Precedence Rules.Precedence Rules.1.1. **** = POWER NN
2.2. ** = MULTIPLY x// = DIVIDE ÷
3.3. ++ = ADD +-- = SUBTRACT -
136
Edited Pictures.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).
137
Editing TypesEditing 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-categoriesInsertion editing
Simple InsertionSpecial InsertionFixed InsertionFloating Insertion
Suppression and ReplacementZero suppression and replacement with spacesZero suppression and replacement with asterisks
138
Editing SymbolsEditing Symbols
, B 0 / Simple Insertion
. Special Insertion
+ - CR DB $ Fixed Insertion
+ - S Floating Insertion
Z * Suppression and Replacement
, B 0 / Simple Insertion
. Special Insertion
+ - CR DB $ Fixed Insertion
+ - S Floating Insertion
Z * Suppression and Replacement
Edit Symbol Editing TypeEdit Symbol Editing Type
139
Simple Insertion.Simple Insertion.
Sending Sending Receiving Receiving
Picture Data Picture ResultPicture Data Picture Result
PIC 999999 123456 PIC 999,999
PIC 9(6) 000078 PIC 9(3),9(3)
PIC 9(6) 000078 PIC ZZZ,ZZZ
PIC 9(6) 000178 PIC ***,***
PIC 9(6) 002178 PIC ***,***
PIC 9(6) 120183 PIC 99B99B99
PIC 9(6) 120183 PIC 99/99/99
PIC 9(6) 001245 PIC 990099
Sending Sending Receiving Receiving
Picture Data Picture ResultPicture Data Picture Result
PIC 999999 123456 PIC 999,999
PIC 9(6) 000078 PIC 9(3),9(3)
PIC 9(6) 000078 PIC ZZZ,ZZZ
PIC 9(6) 000178 PIC ***,***
PIC 9(6) 002178 PIC ***,***
PIC 9(6) 120183 PIC 99B99B99
PIC 9(6) 120183 PIC 99/99/99
PIC 9(6) 001245 PIC 990099
123,456000,07878****178**2,178
12018312/01/83 120045
140
Special Special Insertion.Insertion.
Sending Sending Receiving Receiving
Picture Data Picture ResultPicture Data Picture Result
PIC 999V99 12345 PIC 999.99
PIC 999V99 02345 PIC 999.9
PIC 999V99 51234 PIC 99.99
PIC 999 456 PIC 999.99
Sending Sending Receiving Receiving
Picture Data Picture ResultPicture Data Picture Result
PIC 999V99 12345 PIC 999.99
PIC 999V99 02345 PIC 999.9
PIC 999V99 51234 PIC 99.99
PIC 999 456 PIC 999.99
123.45
023.4
12.34
456.00
141
Fixed Insertion - Plus and Minus.Fixed Insertion - Plus and Minus.
Sending Sending Receiving Receiving
Picture Data Picture ResultPicture Data Picture Result
PIC S999 -123 PIC -999
PIC S999 -123 PIC 999-
PIC S999 +123 PIC -999
PIC S9(5) +12345 PIC +9(5)
PIC S9(3) -123 PIC +9(3)
PIC S9(3) -123 PIC 999+
Sending Sending Receiving Receiving
Picture Data Picture ResultPicture Data Picture Result
PIC S999 -123 PIC -999
PIC S999 -123 PIC 999-
PIC S999 +123 PIC -999
PIC S9(5) +12345 PIC +9(5)
PIC S9(3) -123 PIC +9(3)
PIC S9(3) -123 PIC 999+
-123123-123
+12345-123123-
142
Fixed Insertion - Credit, Debit, $Fixed Insertion - Credit, Debit, $
Sending Sending Receiving Receiving
Picture Data Picture ResultPicture Data Picture Result
PIC S9(4) +1234 PIC 9(4)CR
PIC S9(4) -1234 PIC 9(4)CR
PIC S9(4) +1234 PIC 9(4)DB
PIC S9(4) -1234 PIC 9(4)DB
PIC 9(4) 1234 PIC $99999
PIC 9(4) 0000 PIC $ZZZZZ
Sending Sending Receiving Receiving
Picture Data Picture ResultPicture Data Picture Result
PIC S9(4) +1234 PIC 9(4)CR
PIC S9(4) -1234 PIC 9(4)CR
PIC S9(4) +1234 PIC 9(4)DB
PIC S9(4) -1234 PIC 9(4)DB
PIC 9(4) 1234 PIC $99999
PIC 9(4) 0000 PIC $ZZZZZ
12341234CR12231234DB
$01234$
143
Floating Floating Insertion.Insertion.
Sending Sending Receiving Receiving
Picture Data Picture ResultPicture Data Picture Result
PIC 9(4) 0000 PIC $$,$$9.99
PIC 9(4) 0080 PIC $$,$$9.00
PIC 9(4) 0128 PIC $$,$$9.99
PIC 9(5) 57397 PIC $$,$$9
PIC S9(4) - 0005 PIC ++++9
PIC S9(4) +0080 PIC ++++9
PIC S9(4) - 0080 PIC - - - - 9
PIC S9(5) +71234 PIC - - - - 9
Sending Sending Receiving Receiving
Picture Data Picture ResultPicture Data Picture Result
PIC 9(4) 0000 PIC $$,$$9.99
PIC 9(4) 0080 PIC $$,$$9.00
PIC 9(4) 0128 PIC $$,$$9.99
PIC 9(5) 57397 PIC $$,$$9
PIC S9(4) - 0005 PIC ++++9
PIC S9(4) +0080 PIC ++++9
PIC S9(4) - 0080 PIC - - - - 9
PIC S9(5) +71234 PIC - - - - 9
$0.00 $80.00 $128.00$7,397
-5 +80 -80 ž1234
144
Suppression and Suppression and ReplacementReplacement
Sending Sending Receiving Receiving
Picture Data Picture ResultPicture Data Picture Result
PIC 9(5) 12345 PIC ZZ,999
PIC 9(5) 01234 PIC ZZ,999
PIC 9(5) 00123 PIC ZZ,999
PIC 9(5) 00012 PIC ZZ,999
PIC 9(5) 05678 PIC **,**9
PIC 9(5) 00567 PIC **,**9
PIC 9(5) 00000 PIC **,***
Sending Sending Receiving Receiving
Picture Data Picture ResultPicture Data Picture Result
PIC 9(5) 12345 PIC ZZ,999
PIC 9(5) 01234 PIC ZZ,999
PIC 9(5) 00123 PIC ZZ,999
PIC 9(5) 00012 PIC ZZ,999
PIC 9(5) 05678 PIC **,**9
PIC 9(5) 00567 PIC **,**9
PIC 9(5) 00000 PIC **,***
12,3451,234123012*5,678***567******
145
The The USAUSAGE GE
clausclause e
146
USAGE IS DISPLAYUSAGE IS DISPLAY
The USAGE clause specifies the format of numeric data items in the computer storage.
When no USAGE clause is explicitly declared, USAGE IS DISPLAY is assumed.
When numeric items have a USAGE of DISPLAY they are held as ASCII characters !!
SYSTEMSYSTEM CHARCHAR HEXHEX DEC DEC 88 44 22 11 88 44 22 11
ASCIIASCII "A" "A" 41 41 65 65 00 11 00 00 00 00 00 11
EBCDICEBCDIC "A" "A" C1 C1 193 193 11 11 00 00 00 00 00 11
147
Arithmetic when USAGE IS Arithmetic when USAGE IS DISPLAYDISPLAY
88 44 22 11 88 44 22 11 HEX CHARHEX CHAR
Num1 PIC 9 VALUE 4.Num1 PIC 9 VALUE 4. 00 00 11 11 00 11 00 00 41 41 "4""4"
Num2 PIC 9 VALUE 1.Num2 PIC 9 VALUE 1. 00 00 11 11 00 00 00 11 31 31 "1""1"
Num3 PIC 9.Num3 PIC 9. 00 00 00 00 00 00 00 00 0 0 nulnul
ADD Num1,Num2 GIVING Num3.ADD Num1,Num2 GIVING Num3.
148
Arithmetic when USAGE IS Arithmetic when USAGE IS DISPLAYDISPLAY
88 44 22 11 88 44 22 11 HEX CHARHEX CHAR
Num1 PIC 9 VALUE 4.Num1 PIC 9 VALUE 4. 00 00 11 11 00 11 00 00 41 41 "4""4"
Num2 PIC 9 VALUE 1.Num2 PIC 9 VALUE 1. 00 00 11 11 00 00 00 11 31 31 "1""1"
Num3 PIC 9.Num3 PIC 9. 00 11 11 00 00 11 00 11 65 65 "e""e"
ADD Num1,Num2 GIVING Num3.ADD Num1,Num2 GIVING Num3.
149
Why use the USAGE Why use the USAGE clause?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.
150
USAGE SyntaxUSAGE Syntax
01 Num1 PIC 9(5)V99 USAGE IS COMP.
01 Num2 PIC 99 USAGE IS PACKED-DECIMAL.
01 IdxItem USAGE IS INDEX.
01 GroupItems COMP. 02 Item1 PIC 999. 02 Item2 PIC 9(4)V99. 02 New1 PIC S9(5) COMP SYNC.
151
USAGE IS COMPUSAGE IS COMP
Number of DigitsNumber of Digits Storage Required.Storage Required.
11 TOTO 44 1 WORD (2 Bytes)1 WORD (2 Bytes)
55 TOTO 99 1 LONGWORD (4 Bytes)1 LONGWORD (4 Bytes)
1010 TOTO 1818 1 QUADWORD (8 Bytes)1 QUADWORD (8 Bytes)
01 TotalCount PIC 9(7) USAGE IS COMP.01 TotalCount PIC 9(7) USAGE IS COMP.
Takes 4 bytes (1 LONGWORD) of storage.Takes 4 bytes (1 LONGWORD) of storage.
COMP items are held in memory as pure binary two's complement numbers.
152
COMP - Storage COMP - Storage RequirementsRequirements
2 Bytes can represent any 4 digit number.2 Bytes can represent any 4 digit number.
32768 16384 8192 4096 2048 1024 512 256 128 64 32 16 8 4 2 1
Max. number = Max. number = ++ or or - - 32767 32767 PIC 9999 PIC 9999
4 Bytes can represent any 9 digit number4 Bytes can represent any 9 digit number
Max. number = Max. number = ++ or or - - 2, 147,483,647 2, 147,483,647 PIC 999 999 999 PIC 999 999 999
153
USAGE IS PACKED-USAGE IS PACKED-DECIMALDECIMAL
Data items declared as PACKED-DECIMAL are held in binary-coded-decimal (BCD) form.
Instead of representing the value as one single binary number, each digit is held in binary form in a nibble (half a byte).
PIC S9 PIC S9(2) PIC S9(3) VALUE +5 VALUE -32 VALUE +262
5 +5 + 0 3 2 -0 3 2 - 2 6 2 +2 6 2 +
154
01 ThreeBytes01 ThreeBytes PIC XXX VALUE "DOG".PIC XXX VALUE "DOG".01 TwoBytes01 TwoBytes PIC 9(4) COMP.PIC 9(4) COMP.
D O G D O G NumberNumber
The SYNCHRONIZED The SYNCHRONIZED ClauseClause
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.
Word1 Word2 Word3
155
01 ThreeBytes01 ThreeBytes PIC XXX VALUE "DOG".PIC XXX VALUE "DOG".01 TwoBytes01 TwoBytes PIC 9(4) COMP PIC 9(4) COMP SYNCSYNC..
D O G D O G NumberNumber
The SYNCHRONIZED The SYNCHRONIZED ClauseClause
COMP SYNC (1 TO 4 Digits) = 2 Byte boundaryCOMP SYNC (5 TO 9 Digits) = 4 Byte boundaryCOMP SYNC (10 TO 18 Digits) = 8 Byte boundary INDEX = 4 Byte boundary
Word1 Word2 Word3
156
01 FiveBytes01 FiveBytes PIC XXX VALUE "FROGS".PIC XXX VALUE "FROGS".01 FourBytes01 FourBytes PIC S9(5) COMP.PIC S9(5) COMP.
F R O G S F R O G S NumberNumberNumberNumber
The SYNCHRONIZED The SYNCHRONIZED ClauseClause
COMP SYNC (1 TO 4 Digits) = 2 Byte boundaryCOMP SYNC (5 TO 9 Digits) = 4 Byte boundaryCOMP SYNC (10 TO 18 Digits) = 8 Byte boundary INDEX = 4 Byte boundary
Word1 Word2 Word3 Word4 Word5 Word6
157
01 FiveBytes01 FiveBytes PIC XXX VALUE "FROGS".PIC XXX VALUE "FROGS".01 FourBytes01 FourBytes PIC S9(5) COMP PIC S9(5) COMP SYNCSYNC..
F R O G S F R O G S NumberNumberNumberNumber
The SYNCHRONIZED The SYNCHRONIZED ClauseClause
COMP SYNC (1 TO 4 Digits) = 2 Byte boundaryCOMP SYNC (5 TO 9 Digits) = 4 Byte boundaryCOMP SYNC (10 TO 18 Digits) = 8 Byte boundary INDEX = 4 Byte boundary
Word1 Word2 Word3 Word4 Word5 Word6
Aligns along a 4 byte boundary
Aligns along a 4 byte boundary
158
ConditioConditions. ns.
159
IF IF Syntax.Syntax.
IF Condition THEN StatementBlock
NEXT SENTENCE
ELSE StatementBlock
NEXT SENTENCE END - IF
Simple Conditions– Relation Conditions– Class Conditions– Sign Conditions
Complex ConditionsCondition Names
Simple Conditions– Relation Conditions– Class Conditions– Sign Conditions
Complex ConditionsCondition Names
CCONDITION ONDITION TTYPESYPES
160
Relation ConditionsRelation Conditions
Identifier
Literal
ArithmeticExpression
Identifier
Literal
ArithmeticExpression
IS
NOT GREATER THAN
NOT >
NOT LESS THAN
NOT <
NOT EQUAL TO
NOT =
GREATER THAN OR EQUAL TO
>=
LESS THAN OR EQUAL TO
<=
161
Class Class Conditions.Conditions.
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.
Identifier IS [NOT]
NUMERIC
ALPHABETIC
ALPHABETIC - LOWER
ALPHABETIC - UPPER
UserDefinedClassName
162
Sign Sign ConditionsConditions
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.
ArithExp IS [NOT]
POSITIVE
NEGATIVE
ZERO
163
Complex conditions.Complex conditions.
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.
Condition AND
OR Condition
164
Just like arithmetic expressions, complex conditions Just like arithmetic expressions, complex conditions are evaluated using precedence rules and the order of are evaluated using precedence rules and the order of evaluation may be changed by bracketing.evaluation may be changed by bracketing.
ExamplesExamplesIF Row > 0 IF Row > 0 ANDAND Row < 26 THEN Row < 26 THEN
DISPLAY “On Screen”DISPLAY “On Screen”END-IFEND-IF
IF VarA > VarC IF VarA > VarC OROR VarC = VarD VarC = VarD OROR VarA VarA NOTNOT = VarF = VarF DISPLAY “Done”DISPLAY “Done”
END-IFEND-IF
( ) ( )
( ) ( ) ( )
Complex conditions have precedence rules Complex conditions have precedence rules too.too.
Precedence Rules.Precedence Rules.1.1. NOTNOT = **
2.2. ANDAND = * or /
3.3. OROR = + or -
Precedence Rules.Precedence Rules.1.1. NOTNOT = **
2.2. ANDAND = * or /
3.3. OROR = + or -
165
Implied Implied Subjects.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 THENIF Grade = “A” OR Grade = “B+” OR GRADE = “B” THENIF 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 THENIF Grade=“A” OR “B+” OR “B” THENIF VarA > VarB AND VarC AND VarD
DISPLAY “VarA is the Greatest”END-IF
Implied SubjectsImplied SubjectsTotalAmt Grade = VarA >
Implied SubjectsImplied SubjectsTotalAmt Grade = VarA >
166
Nested IFsNested IFs
IF ( VarA < 10 ) AND ( VarB NOT > VarC ) THENIF VarG = 14 THEN
DISPLAY “First”ELSE
DISPLAY “Second”END-IF
ELSEDISPLAY “Third”
END-IF
IF ( VarA < 10 ) AND ( VarB NOT > VarC ) THENIF VarG = 14 THEN
DISPLAY “First”ELSE
DISPLAY “Second”END-IF
ELSEDISPLAY “Third”
END-IF
VarAVarA VarBVarB VarCVarC VarGVarG DISPLAYDISPLAY
3 4 15 14 3 4 15 15 3 4 3 14 13 4 15 14
VarAVarA VarBVarB VarCVarC VarGVarG DISPLAYDISPLAY
3 4 15 14 3 4 15 15 3 4 3 14 13 4 15 14
167
Condition Names.Condition Names.
Wherever a condition can occur, such as in an IF statement or an EVALUATE or a PERFORM..UNTIL, a CONDITION NAME (Level 88) may be used.
A Condition Name is essentially a BOOLEAN variable which is either TRUE or FALSE.
Example.IF StudentRecord = HIGH-VALUES THEN Action
The statement above may be replaced by the one below. The condition name EndOfStudentFile may be used instead of the condition StudentRecord = HIGH-VALUES.
IF EndOfStudentFile THEN Action
168
Defining Condition Defining Condition Names.Names.
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.
88 ConditionName VALUE
VALUES
Literal
LowValue THROUGH
THRU HighValue
169
01 CityCode PIC 9 VALUE 5.88 Dublin VALUE 1.88 Limerick VALUE 2.88 Cork VALUE 3.88 Galway VALUE 4.88 Sligo VALUE 5.88 Waterford VALUE 6.88 UniversityCity VALUE 1 THRU 4.
01 CityCode PIC 9 VALUE 5.88 Dublin VALUE 1.88 Limerick VALUE 2.88 Cork VALUE 3.88 Galway VALUE 4.88 Sligo VALUE 5.88 Waterford VALUE 6.88 UniversityCity VALUE 1 THRU 4.
IF Limerick DISPLAY "Hey, we're home."END-IFIF UniversityCity PERFORM CalcRentSurchargeEND-IF
IF Limerick DISPLAY "Hey, we're home."END-IFIF UniversityCity PERFORM CalcRentSurchargeEND-IF
Dublin FALSE Limerick FALSECork FALSEGalway FALSESligo TRUEWaterford FALSEUniversityCity FALSE
City CodeCity Code
55
170
01 CityCode PIC 9 VALUE 5.88 Dublin VALUE 1.88 Limerick VALUE 2.88 Cork VALUE 3.88 Galway VALUE 4.88 Sligo VALUE 5.88 Waterford VALUE 6.88 UniversityCity VALUE 1 THRU 4.
01 CityCode PIC 9 VALUE 5.88 Dublin VALUE 1.88 Limerick VALUE 2.88 Cork VALUE 3.88 Galway VALUE 4.88 Sligo VALUE 5.88 Waterford VALUE 6.88 UniversityCity VALUE 1 THRU 4.
IF Limerick DISPLAY "Hey, we're home."END-IFIF UniversityCity PERFORM CalcRentSurchargeEND-IF
IF Limerick DISPLAY "Hey, we're home."END-IFIF UniversityCity PERFORM CalcRentSurchargeEND-IF
Dublin FALSE Limerick TRUECork FALSEGalway FALSESligo FALSEWaterford FALSEUniversityCity TRUE
City CodeCity Code
22
171
01 CityCode PIC 9 VALUE 5.88 Dublin VALUE 1.88 Limerick VALUE 2.88 Cork VALUE 3.88 Galway VALUE 4.88 Sligo VALUE 5.88 Waterford VALUE 6.88 UniversityCity VALUE 1 THRU 4.
01 CityCode PIC 9 VALUE 5.88 Dublin VALUE 1.88 Limerick VALUE 2.88 Cork VALUE 3.88 Galway VALUE 4.88 Sligo VALUE 5.88 Waterford VALUE 6.88 UniversityCity VALUE 1 THRU 4.
IF Limerick DISPLAY "Hey, we're home."END-IFIF UniversityCity PERFORM CalcRentSurchargeEND-IF
IF Limerick DISPLAY "Hey, we're home."END-IFIF UniversityCity PERFORM CalcRentSurchargeEND-IF
Dublin FALSE Limerick FALSECork FALSEGalway FALSESligo FALSEWaterford TRUEUniversityCity FALSE
City CodeCity Code
66
172
01 InputChar PIC X.88 Vowel VALUE "A","E","I","O","U".88 Consonant VALUE "B" THRU "D", "F","G","H"
"J" THRU "N", "P" THRU "T""V" THRU "Z".
88 Digit VALUE "0" THRU "9".88 LowerCase VALUE "a" THRU "z".88 ValidChar VALUE "A" THRU "Z","0" THRU "9".
01 InputChar PIC X.88 Vowel VALUE "A","E","I","O","U".88 Consonant VALUE "B" THRU "D", "F","G","H"
"J" THRU "N", "P" THRU "T""V" THRU "Z".
88 Digit VALUE "0" THRU "9".88 LowerCase VALUE "a" THRU "z".88 ValidChar VALUE "A" THRU "Z","0" THRU "9".
IF ValidChar DISPLAY "Input OK."END-IFIF LowerCase
DISPLAY "Not Upper Case"END-IFIF Vowel Display "Vowel entered."END-IF
IF ValidChar DISPLAY "Input OK."END-IFIF LowerCase
DISPLAY "Not Upper Case"END-IFIF Vowel Display "Vowel entered."END-IF
Vowel TRUEConsonant FALSEDigit FALSELowerCase FALSEValidChar TRUE
Input CharInput Char
EE
173
01 InputChar PIC X.88 Vowel VALUE "A","E","I","O","U".88 Consonant VALUE "B" THRU "D", "F","G","H"
"J" THRU "N", "P" THRU "T""V" THRU "Z".
88 Digit VALUE "0" THRU "9".88 LowerCase VALUE "a" THRU "z".88 ValidChar VALUE "A" THRU "Z","0" THRU "9".
01 InputChar PIC X.88 Vowel VALUE "A","E","I","O","U".88 Consonant VALUE "B" THRU "D", "F","G","H"
"J" THRU "N", "P" THRU "T""V" THRU "Z".
88 Digit VALUE "0" THRU "9".88 LowerCase VALUE "a" THRU "z".88 ValidChar VALUE "A" THRU "Z","0" THRU "9".
IF ValidChar DISPLAY "Input OK."END-IFIF LowerCase
DISPLAY "Not Upper Case"END-IFIF Vowel Display "Vowel entered."END-IF
IF ValidChar DISPLAY "Input OK."END-IFIF LowerCase
DISPLAY "Not Upper Case"END-IFIF Vowel Display "Vowel entered."END-IF
Vowel FALSEConsonant FALSEDigit TRUELowerCase FALSEValidChar TRUE
Input CharInput Char
44
174
01 InputChar PIC X.88 Vowel VALUE "A","E","I","O","U".88 Consonant VALUE "B" THRU "D", "F","G","H"
"J" THRU "N", "P" THRU "T""V" THRU "Z".
88 Digit VALUE "0" THRU "9".88 LowerCase VALUE "a" THRU "z".88 ValidChar VALUE "A" THRU "Z","0" THRU "9".
01 InputChar PIC X.88 Vowel VALUE "A","E","I","O","U".88 Consonant VALUE "B" THRU "D", "F","G","H"
"J" THRU "N", "P" THRU "T""V" THRU "Z".
88 Digit VALUE "0" THRU "9".88 LowerCase VALUE "a" THRU "z".88 ValidChar VALUE "A" THRU "Z","0" THRU "9".
IF ValidChar DISPLAY "Input OK."END-IFIF LowerCase
DISPLAY "Not Upper Case"END-IFIF Vowel Display "Vowel entered."END-IF
IF ValidChar DISPLAY "Input OK."END-IFIF LowerCase
DISPLAY "Not Upper Case"END-IFIF Vowel Display "Vowel entered."END-IF
Vowel FALSEConsonant FALSEDigit FALSELowerCase TRUEValidChar FALSE
Input CharInput Char
gg
175
01 EndOfFileFlag PIC 9 VALUE 0.88 EndOfFile VALUE 1.
01 EndOfFileFlag PIC 9 VALUE 0.88 EndOfFile VALUE 1.
READ InFileAT END MOVE 1 TO EndOfFileFlag
END-READPERFORM UNTIL EndOfFile
StatementsREAD InFile
AT END MOVE 1 TO EndOfFileFlagEND-READ
END-PERFORM
READ InFileAT END MOVE 1 TO EndOfFileFlag
END-READPERFORM UNTIL EndOfFile
StatementsREAD InFile
AT END MOVE 1 TO EndOfFileFlagEND-READ
END-PERFORM
EndOfFile
EndOfFileFlagEndOfFileFlag
00
176
01 EndOfFileFlag PIC 9 VALUE 0.88 EndOfFile VALUE 1.
01 EndOfFileFlag PIC 9 VALUE 0.88 EndOfFile VALUE 1.
READ InFileAT END MOVE 1 TO EndOfFileFlag
END-READPERFORM UNTIL EndOfFile
StatementsREAD InFile
AT END MOVE 1 TO EndOfFileFlagAT END MOVE 1 TO EndOfFileFlagEND-READ
END-PERFORM
READ InFileAT END MOVE 1 TO EndOfFileFlag
END-READPERFORM UNTIL EndOfFile
StatementsREAD InFile
AT END MOVE 1 TO EndOfFileFlagAT END MOVE 1 TO EndOfFileFlagEND-READ
END-PERFORM
EndOfFileFlagEndOfFileFlag
11
EndOfFile
177
Using the SET Using the SET verb.verb.
01 FILLER PIC 9 VALUE 0.88 EndOfFile VALUE 1.88 NotEndOfFile VALUE 0.
01 FILLER PIC 9 VALUE 0.88 EndOfFile VALUE 1.88 NotEndOfFile VALUE 0.
READ InFileAT END SET EndOfFile TO TRUE
END-READPERFORM UNTIL EndOfFile
StatementsREAD InFile
AT END SET EndOfFile TO TRUEEND-READ
END-PERFORMSet NotEndOfFile TO TRUE.
READ InFileAT END SET EndOfFile TO TRUE
END-READPERFORM UNTIL EndOfFile
StatementsREAD InFile
AT END SET EndOfFile TO TRUEEND-READ
END-PERFORMSet NotEndOfFile TO TRUE.
EndOfFile 1NotEndOfFile 0
FILLERFILLER
00
178
Using the SET Using the SET verb.verb.
01 FILLER PIC 9 VALUE 0.88 EndOfFile VALUE 1.88 NotEndOfFile VALUE 0.
01 FILLER PIC 9 VALUE 0.88 EndOfFile VALUE 1.88 NotEndOfFile VALUE 0.
READ InFileAT END SET EndOfFile TO TRUE
END-READPERFORM UNTIL EndOfFile
StatementsREAD InFile
AT END SET EndOfFile TO TRUEAT END SET EndOfFile TO TRUEEND-READ
END-PERFORMSet NotEndOfFile TO TRUE.
READ InFileAT END SET EndOfFile TO TRUE
END-READPERFORM UNTIL EndOfFile
StatementsREAD InFile
AT END SET EndOfFile TO TRUEAT END SET EndOfFile TO TRUEEND-READ
END-PERFORMSet NotEndOfFile TO TRUE.
EndOfFile 1NotEndOfFile 0
FILLERFILLER
11
179
Using the SET Using the SET verb.verb.
01 FILLER PIC 9 VALUE 0.88 EndOfFile VALUE 1.88 NotEndOfFile VALUE 0.
01 FILLER PIC 9 VALUE 0.88 EndOfFile VALUE 1.88 NotEndOfFile VALUE 0.
READ InFileAT END SET EndOfFile TO TRUE
END-READPERFORM UNTIL EndOfFile
StatementsREAD InFile
AT END SET EndOfFile TO TRUEEND-READ
END-PERFORMSet NotEndOfFile TO TRUE.
READ InFileAT END SET EndOfFile TO TRUE
END-READPERFORM UNTIL EndOfFile
StatementsREAD InFile
AT END SET EndOfFile TO TRUEEND-READ
END-PERFORMSet NotEndOfFile TO TRUE.
EndOfFile 1NotEndOfFile 0
FILLERFILLER
00
180
PROCEDURE DIVISION.Begin. OPEN INPUT StudentFile READ StudentFile AT END SET EndOfFile TO TRUE END-READ PERFORM UNTIL EndOfFile DISPLAY StudentId SPACE StudentName SPACE CourseCode READ StudentFile AT END SET EndOfFile TO TRUE END-READ END-PERFORM CLOSE StudentFile STOP RUN.
PROCEDURE DIVISION.Begin. OPEN INPUT StudentFile READ StudentFile AT END SET EndOfFile TO TRUE END-READ PERFORM UNTIL EndOfFile DISPLAY StudentId SPACE StudentName SPACE CourseCode READ StudentFile AT END SET EndOfFile TO TRUE END-READ END-PERFORM CLOSE StudentFile STOP RUN.
FD StudentFile.01 StudentDetails. 88 EndOfFile VALUE HIGH-VALUES. 02 StudentId PIC 9(7). 02 StudentName. 03 Surname PIC X(8). 03 Initials PIC XX. 02 DateOfBirth. 03 YOBirth PIC 9(2). 03 MOBirth PIC 9(2). 03 DOBirth PIC 9(2). 02 CourseCode PIC X(4). 02 Grant PIC 9(4). 02 Gender PIC X.
FD StudentFile.01 StudentDetails. 88 EndOfFile VALUE HIGH-VALUES. 02 StudentId PIC 9(7). 02 StudentName. 03 Surname PIC X(8). 03 Initials PIC XX. 02 DateOfBirth. 03 YOBirth PIC 9(2). 03 MOBirth PIC 9(2). 03 DOBirth PIC 9(2). 02 CourseCode PIC X(4). 02 Grant PIC 9(4). 02 Gender PIC X.
181
The The EvaluateEvaluate
EVALUATE
Identifier
Literal
CondExpression
ArithExpression
TRUE
FALSE
WHEN
ANY
Condition
TRUE
FALSE
NOT
Identifier
Literal
ArithExpression
THRU
THROUGH
Identifier
Literal
ArithExpression
StatementBlock
WHEN OTHER StatementBlock
END - EVALUATE
182
W I L L I A M S W I L L I A M S
EVALUATE TRUE PositionWHEN L-Arrow 2 THRU 10 PERFORM MoveLeftWHEN R-Arrow 1 THRU 9 PERFORM MoveRightWHEN L-Arrow 1 MOVE 10 TO PositionWHEN R-Arrow 10 MOVE 1 TO PositionWHEN DeleteKey 1 PERFORM CantDeleteWHEN Character ANY PERFORM InsertCharWHEN OTHER PERFORM DisplayErrorMessage
END-EVALUATE
1 2 3 4 5 6 7 8 9 10
183
Decision Table Decision Table Implementation.Implementation.
EVALUATE Gender TRUE TRUEWHEN "M" Age<20 ANY MOVE 5 TO BonusWHEN "F" Age<20 ANY MOVE 10 TO BonusWHEN "M" Age>19 AND <41 Service<10 MOVE 12 TO BonusWHEN "F" Age>19 AND <41 Service<10 MOVE 13 TO BonusWHEN "M" Age>40 Service<10 MOVE 20 TO BonusWHEN "F" Age>40 Service<10 MOVE 15 TO Bonus
: : : : : : : : : :
WHEN "F" ANY Service>20 MOVE 25 TO BonusEND-EVALUATE
GenderGender M F M F M F M F Age Age <20 <20 20-40 20-40 40> 40> 20-40 20-40 etcServiceService Any Any <10 <10 <10 <10 10-20 10-20 etc% Bonus% Bonus 5 10 12 13 20 15 14 23
184
DesignDesigninging
PrograProgramsms
185
COBOLCOBOL
COBOL is an acronym standing for Common Business Oriented Language.
COBOL programs are (mostly) written for the vertical market.
COBOL programs tend to be long lived.
Because of this longevity ease of program maintenance is an important consideration.
Why is program maintenance important?
186
Cost of a system over its entire Cost of a system over its entire life.life.
Maintenance Costs are only as low as this because many systems become so unmaintainable early in their lives that they have to be SCRAPPED !! :- B. Boehm
Maintenance67%
Testing15%Coding
7%
Analysisand
Design 9%
Zelkowitz ACM 1978
p202
187
Program Program Maintenance.Maintenance.
Program maintenance is an umbrella term that covers;
Œ Changing the program to fix bugs that appear in the system.
Changing the program to reflect changes in the environment.
ŽChanging the program to reflect changes in the users perception of the requirements.
Changing the program to include extensions to the user requirements (i.e. new requirements).
What do these all have in common?
CHANGING THE PROGRAM.
188
How should write your How should write your programs?programs?
You should write your programs with the expectation that they will have to be changed.
This means that you should;
write programs that are easy to read.
write programs that are easy to understand.
write programs that are easy to change.
You should write your programs as you would like them written if you had to maintain them.
189
Efficiency vs Efficiency vs Clarity.Clarity.
Many programmers are overly concerned about making their programs as efficient as possible (in terms of the speed of execution or the amount of memory used).
But the proper concern of a programmer, and particularly a COBOL programmer, is not this kind of efficiency, it is clarity.
As a rule 70% of the work of the program will be done in 10% of the code.
It is therefore a pointless exercise to try to optimize the whole program, especially if this has to be done at the expense of clarity.
Write your program as clearly as possible and then, if its too slow, identify the 10% of the code where the work is being done and optimize it.
190
When shouldn’t we design our When shouldn’t we design our programs?programs?
We shouldn’t design our programs, when we want to create programs that do not work.
We shouldn’t design when we want to produce programs that do not solve the problem specified.
When we want to create programs that;get the wrong inputs,or perform the wrong transformations on themor produce the wrong outputs
then we shouldn’t bother to design our programs.
But if we want to create programs that work, we cannot avoid design.
The only question is; will it be a good design or a bad design
191
Producing a Good Producing a Good Design.Design.
The first step to producing a good design is to design consciously.
Subconscious design means that design is done while constructing the program. This never leads to good results.
Conscious design starts by separating the design task from the task of program construction.
Design, consists of devising a solution to the problem specified.
Construction, consists of taking the design and encoding the solution using a particular programming language.
192
Why separate design from Why separate design from construction?construction?
Separating program design from program construction makes both tasks easier.
Designing before construction, allows us to plan our solution to the problem - instead of stumbling from one incorrect solution to another.
Good program structure results from planing and design. It is unlikely to result from ad hoc tinkering.
Designing helps us to get an overview of the problem and to think about the solution without getting bogged down by the details of construction.
It helps us to iron out problems with the specification and to discover any bugs in our solution before we commit it to code (see next slide).
Design allows us to develop portable solutions
193
Relative cost of fixing a bug.Relative cost of fixing a bug.
In ProductionIn Productionx82x82
In In ConstructionConstruction
x20x20
194
Design Notations.Design Notations.
A number of notations have been suggested to assist the programmer with the task of program design.
Some notations are textual and others graphical.
Some notations can actually assist in the design process.
While others merely articulate the design.
195
Flowcharts as design tools.Flowcharts as design tools.
196
Structured Flowcharts as design Structured Flowcharts as design tools.tools.
197
Structured English.Structured English.
For each transaction record do the followingIF the record is a receipt then
add 1 to the ReceiptsCountadd the Amount to the Balance
otherwiseadd 1 to the PaymentsCountsubtract the Amount from the
BalanceEndIFadd 1 to the RecordCountWrite the Balance to the CustomerFile
When the file has been processed Output the ReceiptsCount
the PaymentsCountand the RecordCount
For each transaction record do the followingIF the record is a receipt then
add 1 to the ReceiptsCountadd the Amount to the Balance
otherwiseadd 1 to the PaymentsCountsubtract the Amount from the
BalanceEndIFadd 1 to the RecordCountWrite the Balance to the CustomerFile
When the file has been processed Output the ReceiptsCount
the PaymentsCountand the RecordCount
198
The Jackson Method.The Jackson Method.
199
Warnier-Orr Warnier-Orr Diagrams.Diagrams.
UpdateCustomerBalance
OpenFiles
ProcessRecords
RecordType ?
ProcessReceipt
ProcessPayment
WriteNewBalance
PrintTotals
CloseFiles
200
IntroductionIntroductionto to
Diagrammatic Diagrammatic Stepwise Stepwise
RefinementRefinement
201
DIAGRAMMATIC STEPWISE REFINEMENT (DSR).DIAGRAMMATIC STEPWISE REFINEMENT (DSR).
an approach to program design based onan approach to program design based on
The Program Structure Diagrams used in the Jackson Method (JSP)
Wirth's Stepwise Refinement approach to program design.
202
Steps in the DSR Steps in the DSR approachapproach
1. Define the problem completely.
2. Work out what needs to be done to solve the problem.
3. Using Stepwise Refinement, design a Program Structure Diagram (PSD) to represent your solution to the problem.
4. Write out the Executable Operations needed to produce the output from the input.
5. Assign the Executable Operations to the appropriate places in the PSD.
6. Insert the Iteration and Selection conditions.
7. Test your solution using test data.
8. Translate the populated PSD into code.
203
Stepwise RefinementStepwise Refinement
Is an approach to program design which involves breaking a task into sub-tasks.
Each sub-task is in turn broken into further sub-tasks.
This process continues until the sub-tasks are so simple that their implementation is straight forward.
204
Sequence
Selection
Iteration
Program Structure Program Structure DiagramsDiagrams
Program Structure Diagrams (PSDs) are used to Program Structure Diagrams (PSDs) are used to represent the hierarchy of tasks and sub-tasks represent the hierarchy of tasks and sub-tasks created by Stepwise Refinement. created by Stepwise Refinement.
They are drawn using the three classic constructs They are drawn using the three classic constructs of Structured Programming.of Structured Programming.
205
PRINTPRINTREPORTREPORT
Sequence PSDSequence PSD
PRINTPRINTREPORTREPORT
HEADINGSHEADINGS
PRINTPRINTREPORTREPORT
BODYBODY
PRINTPRINTREPORTREPORTFOOTINGFOOTING
206
ADD TOADD TOFEMALESFEMALES
ADD TOADD TOMALESMALES
Selection PSDSelection PSD
COUNTCOUNTSTUDENTSTUDENT
oo
207
Selection with Null partSelection with Null part
COUNTCOUNTSTUDENTSTUDENT
ADD TOADD TOLM51 COUNTLM51 COUNT
ADD TOADD TOLM60 COUNTLM60 COUNT
oo
208
Iteration PSDIteration PSD
PROCESSPROCESSACCOUNTACCOUNT
PROCESSPROCESSACCOUNTSACCOUNTS
**
209
PROCESSPROCESSACCOUNTACCOUNT
Iteration PSD - Explicit Repeat Iteration PSD - Explicit Repeat LoopLoop
PROCESSPROCESSREMAININGREMAININGACCOUNTSACCOUNTS
**
PROCESSPROCESSACCOUNTSACCOUNTS
PROCESSPROCESSFIRST FIRST
ACCOUNTACCOUNT
210
PROCESSPROCESSCOUNTYCOUNTYRECORDRECORD
Iteration PSDIteration PSD
PRINTPRINTCOUNTRYCOUNTRY
BODYBODY
PRINTPRINTCOUNTYCOUNTYTOTALSTOTALS
INITIALIZEINITIALIZECOUNTYCOUNTYTOTALSTOTALS
**
Print-Country-Body is an iteration of three components. This is equivalent to ;
an iteration of one component which is in turn a sequence of three.
211
PROCESSPROCESSCOUNTYCOUNTYRECORDRECORD
Iteration PSDIteration PSD
PRINTPRINTCOUNTRYCOUNTRY
BODYBODY
PRINTPRINTCOUNTYCOUNTYTOTALSTOTALS
INITIALIZEINITIALIZECOUNTYCOUNTYTOTALSTOTALS
**
PRINTPRINTCOUNTYCOUNTYREPORTREPORT
212
Payroll Proof Totals Program Payroll Proof Totals Program SpecificationSpecification
Write a program to produce proof totals for a weekly payroll. The payroll file consists of records with the following format:-
COL 1 Record-Type PIC 9.1 = Regular2 = Overtime3 = Bonus
COLS 2-6 Employee-Number PIC 9(5).COLS 7-11 Earnings PIC 9(3)V99.
(in pounds and pence)
The print layout should be as follows:
PAYROLL PROOF TOTALS
Regular Earnings : 25$2,111.23
Overtime Earnings : 2$21.50
Bonus Earnings : 6$123.45
PAYROLL PROOF TOTALS
Regular Earnings : 25$2,111.23
Overtime Earnings : 2$21.50
Bonus Earnings : 6$123.45
213
Applying DSR to the Payroll Proof Totals ProgramApplying DSR to the Payroll Proof Totals Program
1. Define the problem completely2. Work out what needs to be done to solve the
problem.3. Using Stepwise Refinement design a Program
Structure Diagram (PSD) to represent your solution to the problem.
214
PrintPrintProof TotalsProof Totals
ReportReport
215
PrintPrintProof TotalsProof Totals
ReportReport
PrintPrintProofProofTotalsTotals
ProcessProcessPayrollPayroll
RecordsRecords
216
PrintPrintProof TotalsProof Totals
ReportReport
PrintPrintProofProofTotalsTotals
**
ProcessProcessPayrollPayroll
RecordsRecords
Process AProcess APayrollPayrollRecordRecord
217
PrintPrintProof TotalsProof Totals
ReportReport
oo
PrintPrintProofProofTotalsTotals
**
ProcessProcessPayrollPayroll
RecordsRecords
Process AProcess APayrollPayrollRecordRecord
Add To Add To OvertimeOvertime
Add To Add To RegularRegular
Add ToAdd ToBonusBonus
218
PrintPrintProof TotalsProof Totals
ReportReport
oo
PrintPrintProofProofTotalsTotals
**
ProcessProcessPayrollPayroll
RecordsRecords
Process AProcess APayrollPayrollRecordRecord
Add To Add To OvertimeOvertime
Add To Add To RegularRegular
Add ToAdd ToBonusBonus
PrintPrintReportReport
HeadingsHeadings
PrintPrintRegular Regular TotalsTotals
PrintPrintOvertimeOvertime
TotalsTotals
PrintPrintBonusBonusTotalsTotals
219
1. OPEN OUTPUT Print-File.2. CLOSE Print-File.3. WRITE Print-Line FROM Heading-Line AFTER ADVANCING PAGE.4. WRITE Print-Line FROM Regular-Line AFTER ADVANCING 1 LINE.5. WRITE Print-Line FROM Overtime-Line AFTER ADVANCING 1 LINE.6. WRITE Print-Line FROM Bonus-Line AFTER ADVANCING 1 LINE.7. MOVE Regular-Total TO Print-Reg-Total.8. MOVE Overtime-Total TO Print-Overtime-Total.9. MOVE Bonus-Total TO Print-Bonus-Total.10. MOVE Regular-Count TO Print-Reg-Count.11. MOVE Overtime-Count TO Print-Over-Count.12. MOVE Bonus-Count TO Print-Bonus-Count.13. ADD Earnings TO Regular-Total.14. ADD Earnings TO Overtime-Total.15. ADD Earnings TO Bonus-Total.16. ADD 1 TO Regular-Count.17. ADD 1 TO Overtime-Count.18. ADD 1 TO Bonus-Count.19. READ Payroll-File
AT END SET End-of-File TO TRUEEND-READ.
20. OPEN INPUT Payroll-File.21. CLOSE Payroll-File.
1. OPEN OUTPUT Print-File.2. CLOSE Print-File.3. WRITE Print-Line FROM Heading-Line AFTER ADVANCING PAGE.4. WRITE Print-Line FROM Regular-Line AFTER ADVANCING 1 LINE.5. WRITE Print-Line FROM Overtime-Line AFTER ADVANCING 1 LINE.6. WRITE Print-Line FROM Bonus-Line AFTER ADVANCING 1 LINE.7. MOVE Regular-Total TO Print-Reg-Total.8. MOVE Overtime-Total TO Print-Overtime-Total.9. MOVE Bonus-Total TO Print-Bonus-Total.10. MOVE Regular-Count TO Print-Reg-Count.11. MOVE Overtime-Count TO Print-Over-Count.12. MOVE Bonus-Count TO Print-Bonus-Count.13. ADD Earnings TO Regular-Total.14. ADD Earnings TO Overtime-Total.15. ADD Earnings TO Bonus-Total.16. ADD 1 TO Regular-Count.17. ADD 1 TO Overtime-Count.18. ADD 1 TO Bonus-Count.19. READ Payroll-File
AT END SET End-of-File TO TRUEEND-READ.
20. OPEN INPUT Payroll-File.21. CLOSE Payroll-File.
4.4. Write out the Executable Operations needed to Write out the Executable Operations needed to produce the produce the outputoutput from the from the input input..
220
5.5. Assign the Executable Operations to the Assign the Executable Operations to the appropriate places in the PSD.appropriate places in the PSD.
AlgorithmFor all Executable Operations.
– Get an Executable Operation.– Ask "To what component/components must I attach this
operation to get the program to work?".– If there are already operations attached to a target component
then a further question must be asked ; "Where, in relation to the existing operations, does this operation go?".
221
PrintPrintProof TotalsProof Totals
ReportReport
oo
PrintPrintProofProofTotalsTotals
**
ProcessProcessPayrollPayroll
RecordsRecords
Process AProcess APayrollPayrollRecordRecord
Add To Add To OvertimeOvertime
Add To Add To RegularRegular
Add ToAdd ToBonusBonus
PrintPrintReportReport
HeadingsHeadings
PrintPrintRegular Regular TotalsTotals
PrintPrintOvertimeOvertime
TotalsTotals
PrintPrintBonusBonusTotalsTotals
1. OPEN OUTPUT Print-File.2. CLOSE Print-File.
222
PrintPrintProof TotalsProof Totals
ReportReport
oo
PrintPrintProofProofTotalsTotals
**
ProcessProcessPayrollPayroll
RecordsRecords
Process AProcess APayrollPayrollRecordRecord
Add To Add To OvertimeOvertime
Add To Add To RegularRegular
Add ToAdd ToBonusBonus
PrintPrintReportReport
HeadingsHeadings
PrintPrintRegular Regular TotalsTotals
PrintPrintOvertimeOvertime
TotalsTotals
PrintPrintBonusBonusTotalsTotals
11 22
1. OPEN OUTPUT Print-File.2. CLOSE Print-File.3. WRITE Print-Line FROM Heading-Line ... 4. WRITE Print-Line FROM Regular-Line ... 5. WRITE Print-Line FROM Overtime-Line ... 6. WRITE Print-Line FROM Bonus-Line ...
223
PrintPrintProof TotalsProof Totals
ReportReport
oo
PrintPrintProofProofTotalsTotals
**
ProcessProcessPayrollPayroll
RecordsRecords
Process AProcess APayrollPayrollRecordRecord
Add To Add To OvertimeOvertime
Add To Add To RegularRegular
Add ToAdd ToBonusBonus
PrintPrintReportReport
HeadingsHeadings
PrintPrintRegular Regular TotalsTotals
PrintPrintOvertimeOvertime
TotalsTotals
PrintPrintBonusBonusTotalsTotals
1 2
3. WRITE Print-Line FROM Heading-Line ... 4. WRITE Print-Line FROM Regular-Line ... 5. WRITE Print-Line FROM Overtime-Line ... 6. WRITE Print-Line FROM Bonus-Line ...7. MOVE Regular-Total TO Print-Reg-Total.8. MOVE Overtime-Total TO Print-Overtime-Total.9. MOVE Bonus-Total TO Print-Bonus-Total.
33 44 6655
224
PrintPrintProof TotalsProof Totals
ReportReport
oo
PrintPrintProofProofTotalsTotals
**
ProcessProcessPayrollPayroll
RecordsRecords
Process AProcess APayrollPayrollRecordRecord
Add To Add To OvertimeOvertime
Add To Add To RegularRegular
Add ToAdd ToBonusBonus
PrintPrintReportReport
HeadingsHeadings
PrintPrintRegular Regular TotalsTotals
PrintPrintOvertimeOvertime
TotalsTotals
PrintPrintBonusBonusTotalsTotals
1 2
7. MOVE Regular-Total TO Print-Reg-Total.8. MOVE Overtime-Total TO Print-Overtime-Total.9. MOVE Bonus-Total TO Print-Bonus-Total.10. MOVE Regular-Count TO Print-Reg-Count.11. MOVE Overtime-Count TO Print-Over-Count.12. MOVE Bonus-Count TO Print-Bonus-Count.
3 77,4 99,688,5
225
PrintPrintProof TotalsProof Totals
ReportReport
oo
PrintPrintProofProofTotalsTotals
**
ProcessProcessPayrollPayroll
RecordsRecords
Process AProcess APayrollPayrollRecordRecord
Add To Add To OvertimeOvertime
Add To Add To RegularRegular
Add ToAdd ToBonusBonus
PrintPrintReportReport
HeadingsHeadings
PrintPrintRegular Regular TotalsTotals
PrintPrintOvertimeOvertime
TotalsTotals
PrintPrintBonusBonusTotalsTotals
1 2
10. MOVE Regular-Count TO Print-Reg-Count.11. MOVE Overtime-Count TO Print-Over-Count.12. MOVE Bonus-Count TO Print-Bonus-Count.13. ADD Earnings TO Regular-Total.14. ADD Earnings TO Overtime-Total.15. ADD Earnings TO Bonus-Total.16. ADD 1 TO Regular-Count.17. ADD 1 TO Overtime-Count.18. ADD 1 TO Bonus-Count.
7,1010,4 1212,9,61111,8,53
226
PrintPrintProof TotalsProof Totals
ReportReport
oo
PrintPrintProofProofTotalsTotals
**
ProcessProcessPayrollPayroll
RecordsRecords
Process AProcess APayrollPayrollRecordRecord
Add To Add To OvertimeOvertime
Add To Add To RegularRegular
Add ToAdd ToBonusBonus
PrintPrintReportReport
HeadingsHeadings
PrintPrintRegular Regular TotalsTotals
PrintPrintOvertimeOvertime
TotalsTotals
PrintPrintBonusBonusTotalsTotals
1 2
13. ADD Earnings TO Regular-Total.14. ADD Earnings TO Overtime-Total.15. ADD Earnings TO Bonus-Total.16. ADD 1 TO Regular-Count.17. ADD 1 TO Overtime-Count.18. ADD 1 TO Bonus-Count.19. READ Payroll-File
AT END SET End-of-File TO TRUEEND-READ.
14,1714,17 15,1815,18
7,10,4 12,9,611,8,53
227
PrintPrintProof TotalsProof Totals
ReportReport
oo
PrintPrintProofProofTotalsTotals
**
ProcessProcessPayrollPayroll
RecordsRecords
Process AProcess APayrollPayrollRecordRecord
Add To Add To OvertimeOvertime
Add To Add To RegularRegular
Add ToAdd ToBonusBonus
PrintPrintReportReport
HeadingsHeadings
PrintPrintRegular Regular TotalsTotals
PrintPrintOvertimeOvertime
TotalsTotals
PrintPrintBonusBonusTotalsTotals
1,1919 2
19. READ Payroll-FileAT END SET End-of-File TO TRUE
END-READ.
13,16 14,17 15,18
7,10,4 12,9,611,8,53
228
PrintPrintProof TotalsProof Totals
ReportReport
oo
PrintPrintProofProofTotalsTotals
**
ProcessProcessPayrollPayroll
RecordsRecords
Process AProcess APayrollPayrollRecordRecord
Add To Add To OvertimeOvertime
Add To Add To RegularRegular
Add ToAdd ToBonusBonus
PrintPrintReportReport
HeadingsHeadings
PrintPrintRegular Regular TotalsTotals
PrintPrintOvertimeOvertime
TotalsTotals
PrintPrintBonusBonusTotalsTotals
1,19 2
19. READ Payroll-FileAT END SET End-of-File TO TRUE
END-READ.20. OPEN INPUT Payroll-File.21. CLOSE Payroll-File.
13,16 14,17 15,18
1919
7,10,4 12,9,611,8,53
229
PrintPrintProof TotalsProof Totals
ReportReport
oo
PrintPrintProofProofTotalsTotals
**
ProcessProcessPayrollPayroll
RecordsRecords
Process AProcess APayrollPayrollRecordRecord
Add To Add To OvertimeOvertime
Add To Add To RegularRegular
Add ToAdd ToBonusBonus
PrintPrintReportReport
HeadingsHeadings
PrintPrintRegular Regular TotalsTotals
PrintPrintOvertimeOvertime
TotalsTotals
PrintPrintBonusBonusTotalsTotals
20. OPEN INPUT Payroll-File.21. CLOSE Payroll-File.
1,2020,19 2,2121
19
13,16 14,17 15,18
3 7,10,4 12,9,611,8,5
230
6.6. Insert the Iteration and Selection Insert the Iteration and Selection conditions.conditions.
Go to each iteration component and ask;"What iteration statement must I use here to get the program to work correctly?". Write the Iteration statement, give it a number and insert its number into the diagram.
Go to each selection component and ask;" What selection statement must I use here to get the program to work correctly?". Write the Selection statement, give it a number and insert its number into the diagram.
231
PrintPrintProof TotalsProof Totals
ReportReport
oo
PrintPrintProofProofTotalsTotals
ProcessProcessPayrollPayroll
RecordsRecords
Process AProcess APayrollPayrollRecordRecord
Add To Add To OvertimeOvertime
Add To Add To RegularRegular
Add ToAdd ToBonusBonus
PrintPrintReportReport
HeadingsHeadings
PrintPrintRegular Regular TotalsTotals
PrintPrintOvertimeOvertime
TotalsTotals
PrintPrintBonusBonusTotalsTotals
1,20,19 2,21
1. 1. PERFORM Process-Payroll-Records UNTIL End-of-File.
13,16 14,17 15,18
19
11
7,10,4 12,9,611,8,53
**
232
PrintPrintProof TotalsProof Totals
ReportReport
PrintPrintProofProofTotalsTotals
**
ProcessProcessPayrollPayroll
RecordsRecords
Process AProcess APayrollPayrollRecordRecord
Add To Add To OvertimeOvertime
Add To Add To RegularRegular
Add ToAdd ToBonusBonus
PrintPrintReportReport
HeadingsHeadings
PrintPrintRegular Regular TotalsTotals
PrintPrintOvertimeOvertime
TotalsTotals
PrintPrintBonusBonusTotalsTotals
1,20,19 2,21
1. 1. PERFORM Process-Payroll-Records UNTIL End-of-File.
2.2. IF Regular-Rec PERFORM Add-to-RegularELSE
IF Overtime-Rec PERFORM Add-to-Overtime
ELSE PERFORM Add-to-BonusEND-IF
END-IF.
13,16 14,17 15,18
19
11
227,10,4 12,9,611,8,53
oo
Using IF...ELSEUsing IF...ELSE
233
PrintPrintProof TotalsProof Totals
ReportReport
PrintPrintProofProofTotalsTotals
**
ProcessProcessPayrollPayroll
RecordsRecords
Process AProcess APayrollPayrollRecordRecord
Add To Add To OvertimeOvertime
Add To Add To RegularRegular
Add ToAdd ToBonusBonus
PrintPrintReportReport
HeadingsHeadings
PrintPrintRegular Regular TotalsTotals
PrintPrintOvertimeOvertime
TotalsTotals
PrintPrintBonusBonusTotalsTotals
1,20,19 2,21
1. 1. PERFORM Process-Payroll-Records UNTIL End-of-File.
2.2. EVALUATE TRUEWHEN Regular-Rec PERFORM Add-to-
RegularWHEN Overtime-Rec PERFORM Add-to-
OvertimeWHEN Bonus-Rec PERFORM Add-to-
BonusEND-EVALUATE.
13,16 14,17 15,18
19
11
227,10,4 12,9,611,8,53
oo
Using the EvaluateUsing the Evaluate
23411 12341234 050.25050.2511 12341234 050.25050.25
PrintPrintProof TotalsProof Totals
ReportReport
PrintPrintProofProofTotalsTotals
**
ProcessProcessPayrollPayroll
RecordsRecords
Process AProcess APayrollPayrollRecordRecord
Add To Add To OvertimeOvertime
Add To Add To RegularRegular
Add ToAdd ToBonusBonus
PrintPrintReportReport
HeadingsHeadings
PrintPrintRegular Regular TotalsTotals
PrintPrintOvertimeOvertime
TotalsTotals
PrintPrintBonusBonusTotalsTotals
1,20,19 2,21
13,16 14,17 15,18
19
11
227,10,4 12,9,611,8,53
oo
7.7. Test the program using test Test the program using test data.data.
TypeType Emp-No Emp-No EarningsEarnings11 12341234 050.25050.2522 12341234 025.50025.5011 23452345 120.25120.2533 12341234 010.50010.50
Employee-RecEmployee-RecTypeType Emp-No Emp-No EarningsEarnings
000.00000.00 000000
000.00000.00 000000
000.00000.00 000000
23511 12341234 050.25050.2511 12341234 050.25050.25
PrintPrintProof TotalsProof Totals
ReportReport
PrintPrintProofProofTotalsTotals
**
ProcessProcessPayrollPayroll
RecordsRecords
Process AProcess APayrollPayrollRecordRecord
Add To Add To OvertimeOvertime
Add To Add To RegularRegular
Add ToAdd ToBonusBonus
PrintPrintReportReport
HeadingsHeadings
PrintPrintRegular Regular TotalsTotals
PrintPrintOvertimeOvertime
TotalsTotals
PrintPrintBonusBonusTotalsTotals
1,20,19 2,21
13,16 14,17 15,18
19
11
227,10,4 12,9,611,8,53
oo
7.7. Test the program using test Test the program using test data.data.
TypeType Emp-No Emp-No EarningsEarnings11 12341234 050.25050.2522 12341234 025.50025.5011 23452345 120.25120.2533 12341234 010.50010.50
Employee-RecEmployee-RecTypeType Emp-No Emp-No EarningsEarnings
050.25050.25050.25050.25 001001001001
000.00000.00 000000
000.00000.00 000000
23622 12341234 025.50025.5022 12341234 025.50025.50
PrintPrintProof TotalsProof Totals
ReportReport
PrintPrintProofProofTotalsTotals
**
ProcessProcessPayrollPayroll
RecordsRecords
Process AProcess APayrollPayrollRecordRecord
Add To Add To OvertimeOvertime
Add To Add To RegularRegular
Add ToAdd ToBonusBonus
PrintPrintReportReport
HeadingsHeadings
PrintPrintRegular Regular TotalsTotals
PrintPrintOvertimeOvertime
TotalsTotals
PrintPrintBonusBonusTotalsTotals
1,20,19 2,21
13,16 14,17 15,18
19
11
227,10,4 12,9,611,8,53
oo
7.7. Test the program using test Test the program using test data.data.
TypeType Emp-No Emp-No EarningsEarnings11 12341234 050.25050.2522 12341234 025.50025.5011 23452345 120.25120.2533 12341234 010.50010.50
Employee-RecEmployee-RecTypeType Emp-No Emp-No EarningsEarnings
050.25050.25 001001
000.00000.00 000000
000.00000.00 000000
23722 12341234 025.50025.5022 12341234 025.50025.50
PrintPrintProof TotalsProof Totals
ReportReport
PrintPrintProofProofTotalsTotals
**
ProcessProcessPayrollPayroll
RecordsRecords
Process AProcess APayrollPayrollRecordRecord
Add To Add To OvertimeOvertime
Add To Add To RegularRegular
Add ToAdd ToBonusBonus
PrintPrintReportReport
HeadingsHeadings
PrintPrintRegular Regular TotalsTotals
PrintPrintOvertimeOvertime
TotalsTotals
PrintPrintBonusBonusTotalsTotals
1,20,19 2,21
13,16 14,17 15,18
19
11
227,10,4 12,9,611,8,53
oo
7.7. Test the program using test Test the program using test data.data.
TypeType Emp-No Emp-No EarningsEarnings11 12341234 050.25050.2522 12341234 025.50025.5011 23452345 120.25120.2533 12341234 010.50010.50
Employee-RecEmployee-RecTypeType Emp-No Emp-No EarningsEarnings
050.25050.25 001001
025.50025.50025.50025.50 001001001001
000.00000.00 000000
23811 23452345 120.25120.2511 23452345 120.25120.25
PrintPrintProof TotalsProof Totals
ReportReport
PrintPrintProofProofTotalsTotals
**
ProcessProcessPayrollPayroll
RecordsRecords
Process AProcess APayrollPayrollRecordRecord
Add To Add To OvertimeOvertime
Add To Add To RegularRegular
Add ToAdd ToBonusBonus
PrintPrintReportReport
HeadingsHeadings
PrintPrintRegular Regular TotalsTotals
PrintPrintOvertimeOvertime
TotalsTotals
PrintPrintBonusBonusTotalsTotals
1,20,19 2,21
13,16 14,17 15,18
19
11
227,10,4 12,9,611,8,53
oo
7.7. Test the program using test Test the program using test data.data.
TypeType Emp-No Emp-No EarningsEarnings11 12341234 050.25050.2522 12341234 025.50025.5011 23452345 120.25120.2533 12341234 010.50010.50
Employee-RecEmployee-RecTypeType Emp-No Emp-No EarningsEarnings
050.25050.25 001001
025.50025.50 001001
000.00000.00 000000
23911 23452345 120.25120.2511 23452345 120.25120.25
PrintPrintProof TotalsProof Totals
ReportReport
PrintPrintProofProofTotalsTotals
**
ProcessProcessPayrollPayroll
RecordsRecords
Process AProcess APayrollPayrollRecordRecord
Add To Add To OvertimeOvertime
Add To Add To RegularRegular
Add ToAdd ToBonusBonus
PrintPrintReportReport
HeadingsHeadings
PrintPrintRegular Regular TotalsTotals
PrintPrintOvertimeOvertime
TotalsTotals
PrintPrintBonusBonusTotalsTotals
1,20,19 2,21
13,16 14,17 15,18
19
11
227,10,4 12,9,611,8,53
oo
7.7. Test the program using test Test the program using test data.data.
TypeType Emp-No Emp-No EarningsEarnings11 12341234 050.25050.2522 12341234 025.50025.5011 23452345 120.25120.2533 12341234 010.50010.50
Employee-RecEmployee-RecTypeType Emp-No Emp-No EarningsEarnings
170.50170.50170.50170.50 002002002002
025.50025.50 001001
000.00000.00 000000
24033 12341234 010.50010.5033 12341234 010.50010.50
PrintPrintProof TotalsProof Totals
ReportReport
PrintPrintProofProofTotalsTotals
**
ProcessProcessPayrollPayroll
RecordsRecords
Process AProcess APayrollPayrollRecordRecord
Add To Add To OvertimeOvertime
Add To Add To RegularRegular
Add ToAdd ToBonusBonus
PrintPrintReportReport
HeadingsHeadings
PrintPrintRegular Regular TotalsTotals
PrintPrintOvertimeOvertime
TotalsTotals
PrintPrintBonusBonusTotalsTotals
1,20,19 2,21
13,16 14,17 15,18
19
11
227,10,4 12,9,611,8,53
oo
7.7. Test the program using test Test the program using test data.data.
TypeType Emp-No Emp-No EarningsEarnings11 12341234 050.25050.2522 12341234 025.50025.5011 23452345 120.25120.2533 12341234 010.50010.50
Employee-RecEmployee-RecTypeType Emp-No Emp-No EarningsEarnings
170.50170.50 002002
025.50025.50 001001
000.00000.00 000000
24133 12341234 010.50010.5033 12341234 010.50010.50
PrintPrintProof TotalsProof Totals
ReportReport
PrintPrintProofProofTotalsTotals
**
ProcessProcessPayrollPayroll
RecordsRecords
Process AProcess APayrollPayrollRecordRecord
Add To Add To OvertimeOvertime
Add To Add To RegularRegular
Add ToAdd ToBonusBonus
PrintPrintReportReport
HeadingsHeadings
PrintPrintRegular Regular TotalsTotals
PrintPrintOvertimeOvertime
TotalsTotals
PrintPrintBonusBonusTotalsTotals
1,20,19 2,21
13,16 14,17 15,18
19
11
227,10,4 12,9,611,8,53
oo
7.7. Test the program using test Test the program using test data.data.
TypeType Emp-No Emp-No EarningsEarnings11 12341234 050.25050.2522 12341234 025.50025.5011 23452345 120.25120.2533 12341234 010.50010.50
Employee-RecEmployee-RecTypeType Emp-No Emp-No EarningsEarnings
170.50170.50 002002
025.50025.50 001001
010.50010.50010.50010.50 001001001001
242
PrintPrintProof TotalsProof Totals
ReportReport
PrintPrintProofProofTotalsTotals
**
ProcessProcessPayrollPayroll
RecordsRecords
Process AProcess APayrollPayrollRecordRecord
Add To Add To OvertimeOvertime
Add To Add To RegularRegular
Add ToAdd ToBonusBonus
PrintPrintReportReport
HeadingsHeadings
PrintPrintRegular Regular TotalsTotals
PrintPrintOvertimeOvertime
TotalsTotals
PrintPrintBonusBonusTotalsTotals
1,20,19 2,21
13,16 14,17 15,18
19
11
227,10,4 12,9,611,8,53
oo
7.7. Test the program using test Test the program using test data.data.
TypeType Emp-No Emp-No EarningsEarnings11 12341234 050.25050.2522 12341234 025.50025.5011 23452345 120.25120.2533 12341234 010.50010.50
Employee-RecEmployee-RecTypeType Emp-No Emp-No EarningsEarnings
170.50170.50 002002
025.50025.50 001001
010.50010.50 001001HIGH-VALUESHIGH-VALUESHIGH-VALUESHIGH-VALUES
243
PrintPrintProof TotalsProof Totals
ReportReport
PrintPrintProofProofTotalsTotals
**
ProcessProcessPayrollPayroll
RecordsRecords
Process AProcess APayrollPayrollRecordRecord
Add To Add To OvertimeOvertime
Add To Add To RegularRegular
Add ToAdd ToBonusBonus
PrintPrintReportReport
HeadingsHeadings
PrintPrintRegular Regular TotalsTotals
PrintPrintOvertimeOvertime
TotalsTotals
PrintPrintBonusBonusTotalsTotals
1,20,19 2,21
13,16 14,17 15,18
19
11
227,10,4 12,9,611,8,53
oo
7.7. Test the program using test Test the program using test data.data.
TypeType Emp-No Emp-No EarningsEarnings11 12341234 050.25050.2522 12341234 025.50025.5011 23452345 120.25120.2533 12341234 010.50010.50
Employee-RecEmployee-RecTypeType Emp-No Emp-No EarningsEarnings
170.50170.50 002002
025.50025.50 001001
010.50010.50 001001HIGH-VALUESHIGH-VALUESHIGH-VALUESHIGH-VALUES
244
PrintPrintProof TotalsProof Totals
ReportReport
PrintPrintProofProofTotalsTotals
**
ProcessProcessPayrollPayroll
RecordsRecords
Process AProcess APayrollPayrollRecordRecord
Add To Add To OvertimeOvertime
Add To Add To RegularRegular
Add ToAdd ToBonusBonus
PrintPrintReportReport
HeadingsHeadings
PrintPrintRegular Regular TotalsTotals
PrintPrintOvertimeOvertime
TotalsTotals
PrintPrintBonusBonusTotalsTotals
1,20,19 2,21
13,16 14,17 15,18
19
11
227,10,4 12,9,611,8,53
oo
7.7. Test the program using test Test the program using test data.data.
TypeType Emp-No Emp-No EarningsEarnings11 12341234 050.25050.2522 12341234 025.50025.5011 23452345 120.25120.2533 12341234 010.50010.50
Employee-RecEmployee-RecTypeType Emp-No Emp-No EarningsEarnings
170.50170.50 002002
025.50025.50 001001
010.50010.50 001001HIGH-VALUESHIGH-VALUESHIGH-VALUESHIGH-VALUES
245
8.8. Translate the populated PSD into COBOL codeTranslate the populated PSD into COBOL code
Start at the top of the diagram. At each parent component write the sequence of
executable operations, child components and iteration and selection conditions as statements in a paragraph.
Replace child components with PERFORMs of the component name.
At the top component, use the name as the name of the first paragraph and preceed it with the PROCEDURE DIVISION header. End the sequence with the STOP RUN statement.
246
PrintPrintProof TotalsProof Totals
ReportReport
PrintPrintProofProofTotalsTotals
**
ProcessProcessPayrollPayroll
RecordsRecords
Process AProcess APayrollPayrollRecordRecord
Add To Add To OvertimeOvertime
Add To Add To RegularRegular
Add ToAdd ToBonusBonus
PrintPrintReportReport
HeadingsHeadings
PrintPrintRegular Regular TotalsTotals
PrintPrintOvertimeOvertime
TotalsTotals
PrintPrintBonusBonusTotalsTotals
1,20,19 2,21
13,16 14,17 15,18
19
11
227,10,4 12,9,611,8,53
oo
247
PrintPrintProof TotalsProof Totals
ReportReport
PrintPrintProofProofTotalsTotals
**
ProcessProcessPayrollPayroll
RecordsRecords
Process AProcess APayrollPayrollRecordRecord
Add To Add To OvertimeOvertime
Add To Add To RegularRegular
Add ToAdd ToBonusBonus
PrintPrintReportReport
HeadingsHeadings
PrintPrintRegular Regular TotalsTotals
PrintPrintOvertimeOvertime
TotalsTotals
PrintPrintBonusBonusTotalsTotals
1,20,19 2,21
PROCEDURE DIVISION.PROCEDURE DIVISION.Print-Proof-Totals-Report.Print-Proof-Totals-Report.
OPEN INPUT Payroll-File.OPEN INPUT Payroll-File.OPEN Output Print-File.OPEN Output Print-File.Read Payroll-File ....Read Payroll-File ....PERFORM Process-Payroll-Records PERFORM Process-Payroll-Records
UNTIL End-Of-File.UNTIL End-Of-File.PERFORM Print-Proof-Totals.PERFORM Print-Proof-Totals.CLOSE Print-File.CLOSE Print-File.CLOSE Payroll-File.CLOSE Payroll-File.STOP RUN.STOP RUN.
13,16 14,17 15,18
19
11
227,10,4 12,9,611,8,53
oo
248
PrintPrintProof TotalsProof Totals
ReportReport
PrintPrintProofProofTotalsTotals
**
ProcessProcessPayrollPayroll
RecordsRecords
Process AProcess APayrollPayrollRecordRecord
Add To Add To OvertimeOvertime
Add To Add To RegularRegular
Add ToAdd ToBonusBonus
PrintPrintReportReport
HeadingsHeadings
PrintPrintRegular Regular TotalsTotals
PrintPrintOvertimeOvertime
TotalsTotals
PrintPrintBonusBonusTotalsTotals
1,20,19 2,21
13,16 14,17 15,18
19
11
227,10,4 12,9,611,8,53
oo
Process-Payroll-Records. EVALUATE TRUE
WHEN Regular-Rec PERFORM Add-to-RegularWHEN Overtime-Rec PERFORM Add-to-OvertimeWHEN Bonus-Rec PERFORM Add-to-Bonus
END-EVALUATE. READ Payroll-File READ Payroll-File
AT END SET End-Of-File TO TRUE AT END SET End-Of-File TO TRUEEND-READ.END-READ.
249
Tables Tables and and
PERFORM..VARYINGPERFORM..VARYING
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?
TaxTotal
Variable = Named location in memory
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 STOP RUN.
PAYENum CountyNum TaxPaid
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 STOP RUN.SumCountyTaxes. IF CountyNum = 1 ADD TaxPaid TO County1TaxTotal END-IF : : : 24 Statements : : :: : : 24 Statements : : : IF CountyNum = 26 ADD TaxPaid TO County26TaxTotal END-IF READ TaxFile AT END SET EndOfTaxFile TO TRUE END-READ
County1TaxTotal
County2TaxTotal
County3TaxTotal
County4TaxTotal
County5TaxTotal
Tables/Tables/ArraysArrays
10
1 2 3 4 5 61 2 3 4 5 6
MOVE MOVE 1010 TO CountyTax( TO CountyTax(55))
ADD TaxPaid TO CountyTax(CountyNum)ADD TaxPaid TO CountyTax(CountyNum)
ADD TaxPaid TO CountyTax(CountyNum + 2)ADD TaxPaid TO CountyTax(CountyNum + 2)
A table is a contiguous sequence of memory locations called elements elements, , which all have the same namesame name, and are uniquely identified by that name and by their positionposition in the sequence.
A table is a contiguous sequence of memory locations called elements elements, , which all have the same namesame name, and are uniquely identified by that name and by their positionposition in the sequence.
CountyTax
Tables/Tables/ArraysArrays
55
1 2 3 4 5 61 2 3 4 5 6
MOVE 10 TO CountyTax(5)MOVE 10 TO CountyTax(5)
ADD ADD TaxPaidTaxPaid TO CountyTax( TO CountyTax(CountyNumCountyNum))
ADD TaxPaid TO CountyTax(CountyNum + 2)ADD TaxPaid TO CountyTax(CountyNum + 2)
A table is a contiguous sequence of memory locations called elements elements, , which all have the same namesame name, and are uniquely identified by that name and by their positionposition in the sequence.
A table is a contiguous sequence of memory locations called elements elements, , which all have the same namesame name, and are uniquely identified by that name and by their positionposition in the sequence.
1010
55 2
CountyTax
5555
Tables/Tables/ArraysArrays
1 2 3 4 5 61 2 3 4 5 6
MOVE 10 TO CountyTax(5)MOVE 10 TO CountyTax(5)
ADD TaxPaid TO CountyTax(CountyNum)ADD TaxPaid TO CountyTax(CountyNum)
ADD ADD TaxPaidTaxPaid TO CountyTax( TO CountyTax(CountyNum + 2CountyNum + 2))
A table is a contiguous sequence of memory locations called elements elements, , which all have the same namesame name, and are uniquely identified by that name and by their positionposition in the sequence.
A table is a contiguous sequence of memory locations called elements elements, , which all have the same namesame name, and are uniquely identified by that name and by their positionposition in the sequence.
1010
55 2
55
CountyTax
55555555
Tables/Tables/ArraysArrays
1 2 3 4 5 61 2 3 4 5 6
MOVE 10 TO CountyTax(MOVE 10 TO CountyTax(55))
ADD TaxPaid TO CountyTax(ADD TaxPaid TO CountyTax(CountyNumCountyNum))
ADD TaxPaid TO CountyTax(ADD TaxPaid TO CountyTax(CountyNum + 2CountyNum + 2))
A table is a contiguous sequence of memory locations called elements elements, , which all have the same namesame name, and are uniquely identified by that name and by their positionposition in the sequence.
A table is a contiguous sequence of memory locations called elements elements, , which all have the same namesame name, and are uniquely identified by that name and by their positionposition in the sequence.
1010The position index is called a subscript.
Subscript
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 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 STOP RUN.
Subscript
1 2 3 4 5 61 2 3 4 5 6
CountyTax
TaxRecord.PAYENum CountyName TaxPaid
1 2 3 4 5 61 2 3 4 5 6
CountyTax
IF CountyName = "CARLOW" ADD TaxPaid TO CountyTax(1) END-IF IF CountyName = "CAVAN" ADD TaxPaid TO CountyTax(2) END-IF : : : : : : : : : : : : : : : : : : : : 24 TIMES24 TIMES
A-89432 CLARE 7894.55
1 2 3 4 5 61 2 3 4 5 6
CountyTax
A-89432 CLARE 7894.55
TaxRecord.PAYENum CountyName TaxPaid Idx
1 2 3 4 5 61 2 3 4 5 6
CORKCORKCAVANCAVAN DONEGALDONEGALCARLOWCARLOW CLARECLARE DUBLINDUBLIN
County
PERFORM VARYING Idx FROM 1 BY 1 UNTIL County(Idx) = CountyName END-PERFORM ADD TaxPaid TO CountyTax(Idx)
11
500.50 125.75 1000.00 745.55 345.23 123.45500.50 125.75 1000.00 745.55 345.23 123.45
1 2 3 4 5 61 2 3 4 5 6
CountyTax
A-89432 CLARE 7894.55
TaxRecord.PAYENum CountyName TaxPaid Idx
1 2 3 4 5 61 2 3 4 5 6
CORKCORKCAVANCAVAN DONEGALDONEGALCARLOWCARLOW CLARECLARE DUBLINDUBLIN
County
PERFORM VARYING Idx FROM 1 BY 1 UNTIL County(Idx) = CountyName END-PERFORM ADD TaxPaid TO CountyTax(Idx)
22
500.50 125.75 1000.00 745.55 345.23 123.45500.50 125.75 1000.00 745.55 345.23 123.45
1 2 3 4 5 61 2 3 4 5 6
CountyTax
A-89432 CLARE 7894.55
TaxRecord.PAYENum CountyName TaxPaid Idx
1 2 3 4 5 61 2 3 4 5 6
CORKCORKCAVANCAVAN DONEGALDONEGALCARLOWCARLOW CLARECLARE DUBLINDUBLIN
County
PERFORM VARYING Idx FROM 1 BY 1 UNTIL County(Idx) = CountyName END-PERFORM ADD TaxPaid TO CountyTax(Idx)
33
500.50 125.75 1000.00 745.55 345.23 123.45500.50 125.75 1000.00 745.55 345.23 123.45
1 2 3 4 5 61 2 3 4 5 6
CountyTax
A-89432 CLARE 7894.55
TaxRecord.PAYENum CountyName TaxPaid Idx
1 2 3 4 5 61 2 3 4 5 6
CORKCORKCAVANCAVAN DONEGALDONEGALCARLOWCARLOW CLARECLARE DUBLINDUBLIN
County
PERFORM VARYING Idx FROM 1 BY 1 UNTIL County(Idx) = CountyName END-PERFORM ADD TaxPaid TO CountyTax(Idx)
33
500.50 125.75 500.50 125.75 8894.558894.55 745.55 345.23 123.45 745.55 345.23 123.45
262
1 2 3 4 5 61 2 3 4 5 6
TaxTotalsCountyTax
Declaring Declaring Tables.Tables.
000000 000000 000000 000000 000000 000000
01 TaxTotals.01 TaxTotals. 02 CountyTax PIC 9(10)V99 02 CountyTax PIC 9(10)V99 OCCURS 26 TIMES. OCCURS 26 TIMES.
oror 02 CountyTax OCCURS 26 TIMES 02 CountyTax OCCURS 26 TIMES
PIC 9(10)V99. PIC 9(10)V99.
e.g. e.g. MOVE ZEROS TO TaxTotals.MOVE ZEROS TO TaxTotals.
MOVE 20 TO CountyTax(5).MOVE 20 TO CountyTax(5).
Group Items as Group Items as Elements.Elements.
1 2 3 1 2 3 4 4 5 6 5 6
TaxTotals
CountyTax PayerCount
CountyTaxDetails
01 TaxTotals.01 TaxTotals. 02 CountyTaxDetails OCCURS 26 TIMES. 02 CountyTaxDetails OCCURS 26 TIMES. 03 CountyTax PIC 9(10)V99. 03 CountyTax PIC 9(10)V99. 03 PayerCount PIC 9(7). 03 PayerCount PIC 9(7).
e.g. MOVE 25 TO PayerCount(2).e.g. MOVE 25 TO PayerCount(2). MOVE 67 TO CountyTax(5). MOVE 67 TO CountyTax(5). MOVE ZEROS TO CountyTaxDetails(3). MOVE ZEROS TO CountyTaxDetails(3).
25 67
000000 000000
264
PERFORM..VARYING PERFORM..VARYING SyntaxSyntax
PERFORM 1stProc THRU
THROUGH EndProc WITH TEST
BEFORE
AFTER
VARYING Identifer1
IndexName1 FROM
BY Identifier3
Literal UNTIL Condition1
AFTER Identifier4
IndexName3 FROM
BY Identifier6
Literal UNTIL Condition2
Identifier
IndexName
Literal
Identifier
IndexName
Literal
2
2
5
4
StatementBlock END - PERFORM
PERFORM VARYING Idx1 FROM 1 BY 1 UNTIL Idx1 EQUAL TO 3 DISPLAY Idx1END-PERFORM.
Idx1 = 3
Loop Body
True
Move 1 to Idx1Move 1 to Idx1
Next Statement
Inc Idx1
False
Idx1
11
PERFORM VARYING Idx1 FROM 1 BY 1 UNTIL Idx1 EQUAL TO 3 DISPLAY Idx1END-PERFORM.
Loop Body
True
Move 1 to Idx1
Next Statement
Inc Idx1
False
Idx1
11
Idx1 = 3
11
PERFORM VARYING Idx1 FROM 1 BY 1 UNTIL Idx1 EQUAL TO 3 DISPLAY Idx1END-PERFORM.
Loop BodyLoop Body
True
Move 1 to Idx1
Next Statement
Inc Idx1
False
Idx1
11
Idx1 = 3
11
PERFORM VARYING Idx1 FROM 1 BY 1 UNTIL Idx1 EQUAL TO 3 DISPLAY Idx1END-PERFORM.
Loop Body
True
Move 1 to Idx1
Next Statement
Inc Idx1Inc Idx1
False
Idx1
22
Idx1 = 3
11
PERFORM VARYING Idx1 FROM 1 BY 1 UNTIL Idx1 EQUAL TO 3 DISPLAY Idx1END-PERFORM.
Loop Body
True
Move 1 to Idx1
Next Statement
Inc Idx1
False
Idx1
22
Idx1 = 3
1122
PERFORM VARYING Idx1 FROM 1 BY 1 UNTIL Idx1 EQUAL TO 3 DISPLAY Idx1END-PERFORM.
Loop BodyLoop Body
True
Move 1 to Idx1
Next Statement
Inc Idx1
False
Idx1
22
Idx1 = 3
1122
PERFORM VARYING Idx1 FROM 1 BY 1 UNTIL Idx1 EQUAL TO 3 DISPLAY Idx1END-PERFORM.
Loop Body
True
Move 1 to Idx1
Next Statement
Inc Idx1Inc Idx1
False
Idx1
33
Idx1 = 3
1122
PERFORM VARYING Idx1 FROM 1 BY 1 UNTIL Idx1 EQUAL TO 3 DISPLAY Idx1END-PERFORM.
Loop Body
True
Move 1 to Idx1
Next Statement
Inc Idx1
False
Idx1
33
Next Statement
Exit value = 3
Idx1 = 3
T Idx1 Idx2T Idx1 Idx2
PERFORM IterationCount VARYING Idx1 FROM 1 BY 2 UNTIL Idx1 EQUAL TO 5 AFTER Idx2 FROM 6 BY -1 UNTIL Idx2 LESS THAN 4
IterationCountIterationCount
Y
Next Statement
Dec Idx2
N
1 1 6
2 1 5
3 1 4
4 3 6
5 3 5
6 3 4
x = 5 = 6
Move 1 to Idx1Move 6 to Idx2
Y
NMove 6 to Idx2
Inc Idx1
Idx1 = 5
Idx2 < 4
274
Advanced Advanced Tables.Tables.
01 JeansTable.01 JeansTable.
One Dimension One Dimension Table.Table.
One Dimension One Dimension Table.Table.
11 2 2 33 4 4
01 JeansTable.01 JeansTable. 02 Province OCCURS 4 TIMES.02 Province OCCURS 4 TIMES. 03 SalesValue PIC 9(8)V99. 03 SalesValue PIC 9(8)V99. 03 NumSold PIC 9(7). 03 NumSold PIC 9(7).
One Dimension One Dimension Table.Table.
11 2 2 33 4 4
01 JeansTable.01 JeansTable. 02 Province OCCURS 4 TIMES.02 Province OCCURS 4 TIMES. 03 SalesValue PIC 9(8)V99. 03 SalesValue PIC 9(8)V99. 03 NumSold PIC 9(7). 03 NumSold PIC 9(7).
ProvinceProvinceSalesValue NumSoldSalesValue NumSold
12346.99 309
Two Dimension Two Dimension Table.Table.
11 2 2 33 4 4
01 JeansTable.01 JeansTable. 02 Province OCCURS 4 TIMES.02 Province OCCURS 4 TIMES.
Two Dimension Two Dimension Table.Table.
11 2 2 33 4 4
01 JeansTable.01 JeansTable. 02 Province OCCURS 4 TIMES.02 Province OCCURS 4 TIMES. 03 Gender OCCURS 2 TIMES.03 Gender OCCURS 2 TIMES. 04 SalesValue PIC 9(8)V99. 04 SalesValue PIC 9(8)V99. 04 NumSold PIC 9(7). 04 NumSold PIC 9(7).
1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2
Three Dimension Three Dimension Table.Table.
11 2 2 33 4 4
01 JeansTable.01 JeansTable. 02 Province OCCURS 4 TIMES.02 Province OCCURS 4 TIMES.
Three Dimension Three Dimension Table.Table.
11 2 2 33 4 4
01 JeansTable.01 JeansTable. 02 Province OCCURS 4 TIMES.02 Province OCCURS 4 TIMES. 03 Gender OCCURS 2 TIMES.03 Gender OCCURS 2 TIMES.
1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2
Three Dimension Three Dimension Table.Table.
11 2 2 33 4 4
01 JeansTable.01 JeansTable. 02 Province OCCURS 4 TIMES.02 Province OCCURS 4 TIMES. 03 Gender OCCURS 2 TIMES.03 Gender OCCURS 2 TIMES. 04 Colour OCCURS 3 TIMES.04 Colour OCCURS 3 TIMES.
1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3
Three Dimension Three Dimension Table.Table.
11 2 2 33 4 4
01 JeansTable.01 JeansTable. 02 Province OCCURS 4 TIMES.02 Province OCCURS 4 TIMES. 03 Gender OCCURS 2 TIMES.03 Gender OCCURS 2 TIMES. 04 Colour OCCURS 3 TIMES.04 Colour OCCURS 3 TIMES. 05 SalesValue PIC 9(8)V99. 05 SalesValue PIC 9(8)V99. 05 NumSold PIC 9(7). 05 NumSold PIC 9(7).
1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3
ColourColourSalesValue NumSoldSalesValue NumSold
12346.99 309
Record Record Elements.Elements.
01 JeansTable.01 JeansTable. 02 Province OCCURS 4 TIMES.02 Province OCCURS 4 TIMES. 03 ProviceTotal PIC 9(8).03 ProviceTotal PIC 9(8). 03 Gender OCCURS 2 TIMES. 03 Gender OCCURS 2 TIMES. 04 Colour OCCURS 3 TIMES.04 Colour OCCURS 3 TIMES. 05 SalesValue PIC 9(8)V99. 05 SalesValue PIC 9(8)V99. 05 NumSold PIC 9(7). 05 NumSold PIC 9(7).
1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3
1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2
11 2 2 33 4 4
The Redefines The Redefines Clause.Clause.
01 Rates.01 Rates. 02 10Rate02 10Rate PIC 99V999.PIC 99V999. 02 100Rate 02 100Rate REDEFINESREDEFINES 10Rate10Rate PIC 999V99.PIC 999V99. 02 1000Rate 02 1000Rate REDEFINESREDEFINES 10Rate10Rate PIC 9999V9.PIC 9999V9.
1 2 3 4 5 1 2 3 4 5
RatesRates
..
The Redefines Clause.The Redefines Clause.
01 Rates.01 Rates. 02 10Rate02 10Rate PIC 99V999.PIC 99V999. 02 100Rate02 100Rate REDEFINESREDEFINES 10Rate10Rate PIC 999V99.PIC 999V99. 02 1000Rate 02 1000Rate REDEFINESREDEFINES 10Rate10Rate PIC 9999V9.PIC 9999V9.
1 2 3 4 5 1 2 3 4 5
RatesRates
..
The Redefines The Redefines Clause.Clause.
01 Rates.01 Rates. 02 10Rate 02 10Rate PIC 99V999.PIC 99V999. 02 100Rate 02 100Rate REDEFINESREDEFINES 10Rate10Rate PIC 999V99.PIC 999V99. 02 1000Rate02 1000Rate REDEFINESREDEFINES 10Rate10Rate PIC 9999V9.PIC 9999V9.
1 2 3 4 5 1 2 3 4 5
RatesRates
..
The Redefines Clause.The Redefines Clause.
01 HoldDate.01 HoldDate. 02 EuroDate. 02 EuroDate. 03 EuroDay PIC 99. 03 EuroDay PIC 99. 03 EuroMonth PIC 99. 03 EuroMonth PIC 99. 03 EuroYear PIC 9(4). 03 EuroYear PIC 9(4). 02 USDate REDEFINES EuroDate. 02 USDate REDEFINES EuroDate. 03 USMonth PIC 99. 03 USMonth PIC 99. 03 USDay PIC 99. 03 USDay PIC 99. 03 USYear PIC 9(4). 03 USYear PIC 9(4).
11 06 1983 11 06 1983
EuroDateEuroDateEuroDay EuroMonth EuroYearEuroDay EuroMonth EuroYear
USDay USMonth USYear USDay USMonth USYear USDateUSDate
HoldDateHoldDate
Creating Pre-filled Creating Pre-filled TablesTables
01 LetterTable.01 LetterTable. 02 TableValues. 02 TableValues.
Creating Pre-filled Creating Pre-filled TablesTables
A B C D E F G H I J K L A B C D E F G H I J K L
01 LetterTable.01 LetterTable. 02 TableValues. 02 TableValues. 03 FILLER PIC X(13) 03 FILLER PIC X(13) VALUE " VALUE "ABCDEFGHIJKLMABCDEFGHIJKLM".". 03 FILLER PIC X(13) 03 FILLER PIC X(13) VALUE " VALUE "NOPQRSTUVWXYZNOPQRSTUVWXYZ".".
Creating Pre-filled Creating Pre-filled TablesTables
A B C D E F G H I J K L A B C D E F G H I J K L
01 LetterTable.01 LetterTable. 02 TableValues. 02 TableValues. 03 FILLER PIC X(13) 03 FILLER PIC X(13) VALUE " VALUE "ABCDEFGHIJKLMABCDEFGHIJKLM".". 03 FILLER PIC X(13) 03 FILLER PIC X(13) VALUE " VALUE "NOPQRSTUVWXYZNOPQRSTUVWXYZ".".
02 FILLER REDEFINES TableValues.02 FILLER REDEFINES TableValues. 03 Letter PIC X OCCURS 26 TIMES. 03 Letter PIC X OCCURS 26 TIMES.
Two Dimension Table of Two Dimension Table of Values.Values.
01 BonusTable.01 BonusTable. 02 BonusValues. 02 BonusValues. 03 FILLER PIC X(24) 03 FILLER PIC X(24) VALUE " VALUE "507590758595354365406085507590758595354365406085".".
50 75 90 75 85 95 35 43 65 40 60 8550 75 90 75 85 95 35 43 65 40 60 85
Two Dimension Table of Two Dimension Table of Values.Values.
11 2 2 33 4 4
01 BonusTable.01 BonusTable. 02 BonusValues. 02 BonusValues. 03 FILLER PIC X(24) 03 FILLER PIC X(24) VALUE " VALUE "507590758595354365406085507590758595354365406085".". 02 FILLER REDEFINES BonusValues. 02 FILLER REDEFINES BonusValues. 03 Province OCCURS 4 TIMES. 03 Province OCCURS 4 TIMES.
50 75 90 75 85 95 35 43 65 40 60 8550 75 90 75 85 95 35 43 65 40 60 85
Two Dimension Table of Two Dimension Table of Values.Values.
11 2 2 33 4 4
01 BonusTable.01 BonusTable. 02 BonusValues. 02 BonusValues. 03 FILLER PIC X(24) 03 FILLER PIC X(24) VALUE " VALUE "507590758595354365406085507590758595354365406085".". 02 FILLER REDEFINES BonusValues. 02 FILLER REDEFINES BonusValues. 03 Province OCCURS 4 TIMES. 03 Province OCCURS 4 TIMES. 04 Bonus OCCURS 3 TIMES PIC 99.04 Bonus OCCURS 3 TIMES PIC 99.
1 2 3 1 2 3 1 2 3 1 2 31 2 3 1 2 3 1 2 3 1 2 3
50 75 90 75 85 95 35 43 65 40 60 8550 75 90 75 85 95 35 43 65 40 60 85
295
COBOL 85 Table COBOL 85 Table Changes.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.
The The PERFORMPERFORM
297
The PERFORM The PERFORM VerbVerb
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.
298
Paragraphs :- RevisitedParagraphs :- Revisited
A Paragraph is a block of code to which we have given a name.
A Paragraph Name is a programmer defined name formed using the standard rules for programmer defined names (A-Z, 0-9, -).
A Paragraph Name is ALWAYS terminated with a ‘full-stop’.
Any number of statements and sentences may be included in a paragraph, and the last one (at least) must be terminated with a ‘full-stop’.
The scope of a paragraph is delimited by the occurrence of another paragraph name or the end of the program text.
299
ProcessRecord. DISPLAY StudentRecord READ StudentFile
AT END MOVE HIGH-VALUES TO StudentRecord END-READ.
ProduceOutput. DISPLAY “Here is a message”.
Paragraph ExampleParagraph Example
NOTENOTE
The scope of ‘ProcessRecord’ is delimited by the occurrence the paragraph name ‘ProduceOutput’.
NOTENOTE
The scope of ‘ProcessRecord’ is delimited by the occurrence the paragraph name ‘ProduceOutput’.
300
Format 1 Syntax.Format 1 Syntax.
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.
PERFORM 1stProc THRU
THROUGH EndProc
PROCEDURE DIVISION.TopLevel.TopLevel. DISPLAY "In TopLevel. Starting to run program"DISPLAY "In TopLevel. Starting to run program" PERFORM OneLevelDown DISPLAY "Back in TopLevel.". STOP RUN.
TwoLevelsDown. DISPLAY ">>>>>>>> Now in TwoLevelsDown."
OneLevelDown. DISPLAY ">>>> Now in OneLevelDown" PERFORM TwoLevelsDown DISPLAY ">>>> Back in OneLevelDown".
PROCEDURE DIVISION.TopLevel.TopLevel. DISPLAY "In TopLevel. Starting to run program"DISPLAY "In TopLevel. Starting to run program" PERFORM OneLevelDown DISPLAY "Back in TopLevel.". STOP RUN.
TwoLevelsDown. DISPLAY ">>>>>>>> Now in TwoLevelsDown."
OneLevelDown. DISPLAY ">>>> Now in OneLevelDown" PERFORM TwoLevelsDown DISPLAY ">>>> Back in OneLevelDown".
Run of PerformFormat1
In TopLevel. Starting to run program>>>> Now in OneLevelDown>>>>>>>> Now in TwoLevelsDown.>>>> Back in OneLevelDownBack in TopLevel.
In TopLevel. Starting to run program>>>> Now in OneLevelDown>>>>>>>> Now in TwoLevelsDown.>>>> Back in OneLevelDownBack in TopLevel.
Format 1 Format 1 Example.Example.
PROCEDURE DIVISION.TopLevel.TopLevel. DISPLAY "In TopLevel. Starting to run program" PERFORM OneLevelDownPERFORM OneLevelDown DISPLAY "Back in TopLevel.". STOP RUN.
TwoLevelsDown. DISPLAY ">>>>>>>> Now in TwoLevelsDown."
OneLevelDown. DISPLAY ">>>> Now in OneLevelDown" PERFORM TwoLevelsDown DISPLAY ">>>> Back in OneLevelDown".
PROCEDURE DIVISION.TopLevel.TopLevel. DISPLAY "In TopLevel. Starting to run program" PERFORM OneLevelDownPERFORM OneLevelDown DISPLAY "Back in TopLevel.". STOP RUN.
TwoLevelsDown. DISPLAY ">>>>>>>> Now in TwoLevelsDown."
OneLevelDown. DISPLAY ">>>> Now in OneLevelDown" PERFORM TwoLevelsDown DISPLAY ">>>> Back in OneLevelDown".
Run of PerformFormat1
In TopLevel. Starting to run program>>>> Now in OneLevelDown>>>>>>>> Now in TwoLevelsDown.>>>> Back in OneLevelDownBack in TopLevel.
In TopLevel. Starting to run program>>>> Now in OneLevelDown>>>>>>>> Now in TwoLevelsDown.>>>> Back in OneLevelDownBack in TopLevel.
Format 1 Format 1 Example.Example.
PROCEDURE DIVISION.TopLevel. DISPLAY "In TopLevel. Starting to run program" PERFORM OneLevelDown DISPLAY "Back in TopLevel.". STOP RUN.
TwoLevelsDown. DISPLAY ">>>>>>>> Now in TwoLevelsDown."
OneLevelDown.OneLevelDown. DISPLAY ">>>> Now in OneLevelDown"DISPLAY ">>>> Now in OneLevelDown" PERFORM TwoLevelsDown DISPLAY ">>>> Back in OneLevelDown".
PROCEDURE DIVISION.TopLevel. DISPLAY "In TopLevel. Starting to run program" PERFORM OneLevelDown DISPLAY "Back in TopLevel.". STOP RUN.
TwoLevelsDown. DISPLAY ">>>>>>>> Now in TwoLevelsDown."
OneLevelDown.OneLevelDown. DISPLAY ">>>> Now in OneLevelDown"DISPLAY ">>>> Now in OneLevelDown" PERFORM TwoLevelsDown DISPLAY ">>>> Back in OneLevelDown".
Run of PerformFormat1
In TopLevel. Starting to run program>>>> Now in OneLevelDown>>>>>>>> Now in TwoLevelsDown.>>>> Back in OneLevelDownBack in TopLevel.
In TopLevel. Starting to run program>>>> Now in OneLevelDown>>>>>>>> Now in TwoLevelsDown.>>>> Back in OneLevelDownBack in TopLevel.
Format 1 Format 1 Example.Example.
PROCEDURE DIVISION.TopLevel. DISPLAY "In TopLevel. Starting to run program" PERFORM OneLevelDown DISPLAY "Back in TopLevel.". STOP RUN.
TwoLevelsDown. DISPLAY ">>>>>>>> Now in TwoLevelsDown."
OneLevelDown.OneLevelDown. DISPLAY ">>>> Now in OneLevelDown" PERFORM TwoLevelsDownPERFORM TwoLevelsDown DISPLAY ">>>> Back in OneLevelDown".
PROCEDURE DIVISION.TopLevel. DISPLAY "In TopLevel. Starting to run program" PERFORM OneLevelDown DISPLAY "Back in TopLevel.". STOP RUN.
TwoLevelsDown. DISPLAY ">>>>>>>> Now in TwoLevelsDown."
OneLevelDown.OneLevelDown. DISPLAY ">>>> Now in OneLevelDown" PERFORM TwoLevelsDownPERFORM TwoLevelsDown DISPLAY ">>>> Back in OneLevelDown".
Run of PerformFormat1
In TopLevel. Starting to run program>>>> Now in OneLevelDown>>>>>>>> Now in TwoLevelsDown.>>>> Back in OneLevelDownBack in TopLevel.
In TopLevel. Starting to run program>>>> Now in OneLevelDown>>>>>>>> Now in TwoLevelsDown.>>>> Back in OneLevelDownBack in TopLevel.
Format 1 Format 1 Example.Example.
PROCEDURE DIVISION.TopLevel. DISPLAY "In TopLevel. Starting to run program" PERFORM OneLevelDown DISPLAY "Back in TopLevel.". STOP RUN.
TwoLevelsDown.TwoLevelsDown. DISPLAY ">>>>>>>> Now in TwoLevelsDown."DISPLAY ">>>>>>>> Now in TwoLevelsDown."
OneLevelDown. DISPLAY ">>>> Now in OneLevelDown" PERFORM TwoLevelsDown DISPLAY ">>>> Back in OneLevelDown".
PROCEDURE DIVISION.TopLevel. DISPLAY "In TopLevel. Starting to run program" PERFORM OneLevelDown DISPLAY "Back in TopLevel.". STOP RUN.
TwoLevelsDown.TwoLevelsDown. DISPLAY ">>>>>>>> Now in TwoLevelsDown."DISPLAY ">>>>>>>> Now in TwoLevelsDown."
OneLevelDown. DISPLAY ">>>> Now in OneLevelDown" PERFORM TwoLevelsDown DISPLAY ">>>> Back in OneLevelDown".
Run of PerformFormat1
In TopLevel. Starting to run program>>>> Now in OneLevelDown>>>>>>>> Now in TwoLevelsDown.>>>> Back in OneLevelDownBack in TopLevel.
In TopLevel. Starting to run program>>>> Now in OneLevelDown>>>>>>>> Now in TwoLevelsDown.>>>> Back in OneLevelDownBack in TopLevel.
Format 1 Format 1 Example.Example.
PROCEDURE DIVISION.TopLevel. DISPLAY "In TopLevel. Starting to run program" PERFORM OneLevelDown DISPLAY "Back in TopLevel.". STOP RUN.
TwoLevelsDown. DISPLAY ">>>>>>>> Now in TwoLevelsDown."
OneLevelDown.OneLevelDown. DISPLAY ">>>> Now in OneLevelDown" PERFORM TwoLevelsDown DISPLAY ">>>> Back in OneLevelDown".DISPLAY ">>>> Back in OneLevelDown".
PROCEDURE DIVISION.TopLevel. DISPLAY "In TopLevel. Starting to run program" PERFORM OneLevelDown DISPLAY "Back in TopLevel.". STOP RUN.
TwoLevelsDown. DISPLAY ">>>>>>>> Now in TwoLevelsDown."
OneLevelDown.OneLevelDown. DISPLAY ">>>> Now in OneLevelDown" PERFORM TwoLevelsDown DISPLAY ">>>> Back in OneLevelDown".DISPLAY ">>>> Back in OneLevelDown".
Run of PerformFormat1
In TopLevel. Starting to run program>>>> Now in OneLevelDown>>>>>>>> Now in TwoLevelsDown.>>>> Back in OneLevelDownBack in TopLevel.
In TopLevel. Starting to run program>>>> Now in OneLevelDown>>>>>>>> Now in TwoLevelsDown.>>>> Back in OneLevelDownBack in TopLevel.
Format 1 Format 1 Example.Example.
PROCEDURE DIVISION.TopLevel.TopLevel. DISPLAY "In TopLevel. Starting to run program" PERFORM OneLevelDown DISPLAY "Back in TopLevel.".DISPLAY "Back in TopLevel.". STOP RUN.
TwoLevelsDown. DISPLAY ">>>>>>>> Now in TwoLevelsDown."
OneLevelDown. DISPLAY ">>>> Now in OneLevelDown" PERFORM TwoLevelsDown DISPLAY ">>>> Back in OneLevelDown".
PROCEDURE DIVISION.TopLevel.TopLevel. DISPLAY "In TopLevel. Starting to run program" PERFORM OneLevelDown DISPLAY "Back in TopLevel.".DISPLAY "Back in TopLevel.". STOP RUN.
TwoLevelsDown. DISPLAY ">>>>>>>> Now in TwoLevelsDown."
OneLevelDown. DISPLAY ">>>> Now in OneLevelDown" PERFORM TwoLevelsDown DISPLAY ">>>> Back in OneLevelDown".
Run of PerformFormat1
In TopLevel. Starting to run program>>>> Now in OneLevelDown>>>>>>>> Now in TwoLevelsDown.>>>> Back in OneLevelDownBack in TopLevel.
In TopLevel. Starting to run program>>>> Now in OneLevelDown>>>>>>>> Now in TwoLevelsDown.>>>> Back in OneLevelDownBack in TopLevel.
Format 1 Format 1 Example.Example.
PROCEDURE DIVISION.Begin. PERFORM SumSales STOP RUN.
SumSales. Statements Statements
IF NoErrorFound Statements Statements
IF NoErrorFound Statements Statements Statements
END-IF END-IF.
PROCEDURE DIVISION.Begin. PERFORM SumSales STOP RUN.
SumSales. Statements Statements
IF NoErrorFound Statements Statements
IF NoErrorFound Statements Statements Statements
END-IF END-IF.
Why use the PERFORM Why use the PERFORM Thru?Thru?
Go To and PERFORM Go To and PERFORM THRUTHRU
PROCEDURE DIVISIONBegin. PERFORM SumSales THRU SumSalesExit STOP RUN.
SumSales. Statements Statements IF ErrorFound GO TO SumSalesExit END-IF Statements Statements Statements IF ErrorFound GO TO SumSalesExit END-IF Statements
SumSalesExit. EXIT.
PROCEDURE DIVISIONBegin. PERFORM SumSales THRU SumSalesExit STOP RUN.
SumSales. Statements Statements IF ErrorFound GO TO SumSalesExit END-IF Statements Statements Statements IF ErrorFound GO TO SumSalesExit END-IF Statements
SumSalesExit. EXIT.
Format 2 - SyntaxFormat 2 - Syntax
PERFORM 1stProc THRU
THROUGH EndProc
RepeatCount TIMES
StatementBlock END - PERFORM
PROCEDURE DIVISION.Begin.
DisplayName.
PROCEDURE DIVISION.Begin.
DisplayName.
StatementsPERFORM DisplayName 4 TIMESStatementsSTOP RUN.
DISPLAY “Tom Ryan”.
$ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. PerformExample2.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 NumofTimes PIC 9 VALUE 5.
PROCEDURE DIVISION.Begin. DISPLAY "Starting to run program" PERFORM 3 TIMES DISPLAY ">>>>This is an in line Perform" END-PERFORM DISPLAY "Finished in line Perform" PERFORM OutOfLineEG NumOfTimes TIMES DISPLAY "Back in Begin. About to Stop". STOP RUN.
OutOfLineEG. DISPLAY ">>>> This is an out of line Perform".
$ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. PerformExample2.AUTHOR. Michael Coughlan.
DATA DIVISION.WORKING-STORAGE SECTION.01 NumofTimes PIC 9 VALUE 5.
PROCEDURE DIVISION.Begin. DISPLAY "Starting to run program" PERFORM 3 TIMES DISPLAY ">>>>This is an in line Perform" END-PERFORM DISPLAY "Finished in line Perform" PERFORM OutOfLineEG NumOfTimes TIMES DISPLAY "Back in Begin. About to Stop". STOP RUN.
OutOfLineEG. DISPLAY ">>>> This is an out of line Perform".
Format 2 Format 2 ExampleExample
Starting to run program>>>>This is an in line Perform>>>>This is an in line Perform>>>>This is an in line PerformFinished 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 PerformBack in Begin. About to Stop
Starting to run program>>>>This is an in line Perform>>>>This is an in line Perform>>>>This is an in line PerformFinished 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 PerformBack in Begin. About to Stop
Run of PerformExample2
312
Format 3 SyntaxFormat 3 Syntax
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 1stProc THRU
THROUGH EndProc WITH TEST
BEFORE
AFTER
UNTIL Condition
StatementBlock END - PERFORM
313
test
Loop Body
False
True
PERFORM WITHTEST AFTER =REPEAT ... UNTIL
PERFORM WITHTEST AFTER =REPEAT ... UNTIL
Next Statement
test
Loop Body
False
True
PERFORM WITHTEST BEFORE =WHILE ... DO
PERFORM WITHTEST BEFORE =WHILE ... DO
Next Statement
314
Sequential File Sequential File ProcessingProcessing
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”.
315
The READ The READ AheadAhead
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 itemWHILE NOT EndOfStream Process data item Attempt to READ next data itemENDWHILE
Use this to process any stream of data.
316
Reading a Sequential Reading a Sequential FileFile
Algorithm TemplateREAD StudentRecordsREAD StudentRecords
AT END MOVE HIGH-VALUES TO StudentRecordAT END MOVE HIGH-VALUES TO StudentRecordEND-READEND-READPERFORM UNTIL StudentRecord = HIGH-VALUESPERFORM UNTIL StudentRecord = HIGH-VALUES
DISPLAY StudentRecordDISPLAY StudentRecordREAD StudentRecordsREAD StudentRecords
AT END MOVE HIGH-VALUES TO AT END MOVE HIGH-VALUES TO StudentRecordStudentRecord END-READEND-READEND-PERFORMEND-PERFORM
This is an example of an algorithm which is capable of processing any sequential file; ordered or unordered!
PROCEDURE DIVISION.Begin. OPEN INPUT StudentFile
READ StudentFile AT END MOVE HIGH-VALUES TO StudentDetails END-READ PERFORM UNTIL StudentDetails = HIGH-VALUES DISPLAY StudentId SPACE StudentName SPACE CourseCode READ StudentFile AT END MOVE HIGH-VALUES TO StudentDetails END-READ END-PERFORM
CLOSE StudentFile STOP RUN.
PROCEDURE DIVISION.Begin. OPEN INPUT StudentFile
READ StudentFile AT END MOVE HIGH-VALUES TO StudentDetails END-READ PERFORM UNTIL StudentDetails = HIGH-VALUES DISPLAY StudentId SPACE StudentName SPACE CourseCode READ StudentFile AT END MOVE HIGH-VALUES TO StudentDetails END-READ END-PERFORM
CLOSE StudentFile STOP RUN.
9456789 COUGHLANMS LM51
9367892 RYAN TG LM60
9368934 WILSON HR LM61
9456789 COUGHLANMS LM51
9367892 RYAN TG LM60
9368934 WILSON HR LM61
RUN OF SeqRead
Searching Tables.Searching Tables.
Creating Pre-filled Creating Pre-filled TablesTables
A B C D E F G H I J K L A B C D E F G H I J K L
01 LetterTable. 02 TableValues. 03 FILLER PIC X(13) VALUE "ABCDEFGHIJKLMABCDEFGHIJKLM". 03 FILLER PIC X(13) VALUE "NOPQRSTUVWXYZNOPQRSTUVWXYZ".
01 LetterTable. 02 TableValues. 03 FILLER PIC X(13) VALUE "ABCDEFGHIJKLMABCDEFGHIJKLM". 03 FILLER PIC X(13) VALUE "NOPQRSTUVWXYZNOPQRSTUVWXYZ".
Creating Pre-filled Creating Pre-filled TablesTables
A B C D E F G H I J K L A B C D E F G H I J K L
01 LetterTable. 02 TableValues. 03 FILLER PIC X(13) VALUE "ABCDEFGHIJKLMABCDEFGHIJKLM". 03 FILLER PIC X(13) VALUE "NOPQRSTUVWXYZNOPQRSTUVWXYZ".
02 FILLER REDEFINES TableValues.02 FILLER REDEFINES TableValues. 03 Letter PIC X OCCURS 26 TIMES. 03 Letter PIC X OCCURS 26 TIMES.
01 LetterTable. 02 TableValues. 03 FILLER PIC X(13) VALUE "ABCDEFGHIJKLMABCDEFGHIJKLM". 03 FILLER PIC X(13) VALUE "NOPQRSTUVWXYZNOPQRSTUVWXYZ".
02 FILLER REDEFINES TableValues.02 FILLER REDEFINES TableValues. 03 Letter PIC X OCCURS 26 TIMES. 03 Letter PIC X OCCURS 26 TIMES.
Searching a Searching a TableTable
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.
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.
PERFORM VARYING Idx FROM 1 BY 1 UNTIL LetterIn EQUAL TO Letter(Idx)END-PERFORM.DISPLAY LetterIn, "is in position ", Idx.
PERFORM VARYING Idx FROM 1 BY 1 UNTIL LetterIn EQUAL TO Letter(Idx)END-PERFORM.DISPLAY LetterIn, "is in position ", Idx.
A B C D E F G H I J K L A B C D E F G H I J K L 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3 4 5 6 7 8 9 10 11 12
322
Search Search SyntaxSyntax
323
SET SET SyntaxSyntax
Searching a Searching a TableTable
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 INDEXED BY LetterIdx.
SET LetterIdx TO 1.SEARCH Letter AT END DISPLAY "Letter not found!" WHEN Letter(LetterIdx) = LetterIn DISPLAY LetterIn, "is in position ", IdxEND-SEARCH.
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 INDEXED BY LetterIdx.
SET LetterIdx TO 1.SEARCH Letter AT END DISPLAY "Letter not found!" WHEN Letter(LetterIdx) = LetterIn DISPLAY LetterIn, "is in position ", IdxEND-SEARCH.
A B C D E F G H I J K L A B C D E F G H I J K L 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3 4 5 6 7 8 9 10 11 12
Searching a Two Dimension Searching a Two Dimension Table.Table.
1 2 3 4 1 2 3 4
1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 1 2 3 41 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-SEARCHEND-PERFORM.
Search All Search All Syntax.Syntax.
Using the Search Using the Search AllAll
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 ASCENDING KEY IS Letter INDEXED BY LetterIdx.
SEARCH ALL Letter WHEN Letter(LetterIdx) = LetterIn DISPLAY LetterIn, "is in position ", IdxEND-SEARCH.
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 ASCENDING KEY IS Letter INDEXED BY LetterIdx.
SEARCH ALL Letter WHEN Letter(LetterIdx) = LetterIn DISPLAY LetterIn, "is in position ", IdxEND-SEARCH.
A B C D E F G H I J K L A B C D E F G H I J K L 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3 4 5 6 7 8 9 10 11 12
How the Search All How the Search All works.works.
A B C D E F G H I J K L A B C D E F G H I J K L MM N O P Q R S T U V W X Y Z N O P Q R S T U V W X Y Z
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
ALGORITHM.ALGORITHM.Middle = (Lower + Upper) / 2CASE 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
11
LowerLower
2626
UpperUpper
1313 MM
MiddleMiddle
==
Letter(Middle)Letter(Middle)
How the Search All How the Search All works.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 ZN O P Q R S T U V W X Y Z
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
ALGORITHM.ALGORITHM.Middle = (Lower + Upper) / 2CASE 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
1414
LowerLower
2626
UpperUpper
1313 MM
MiddleMiddle
==
Letter(Middle)Letter(Middle)
How the Search All How the Search All works.works.
A B C D E F G H I J K L M N O P Q R S N O P Q R S TT U V W X Y ZU V W X Y Z
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
ALGORITHM.ALGORITHM.Middle = (Lower + Upper) / 2CASE 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
1414
LowerLower
2626
UpperUpper
2020 TT
MiddleMiddle
==
Letter(Middle)Letter(Middle)
How the Search All How the Search All works.works.
A B C D E F G H I J K L M N O P Q R S N O P Q R S T U V W X Y Z
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
ALGORITHM.ALGORITHM.Middle = (Lower + Upper) / 2CASE 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
1414
LowerLower
1919
UpperUpper
2020 TT
MiddleMiddle
==
Letter(Middle)Letter(Middle)
How the Search All works.How the Search All works.
A B C D E F G H I J K L M N O N O PP Q R S Q R S T U V W X Y Z
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
ALGORITHM.ALGORITHM.Middle = (Lower + Upper) / 2CASE 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
1414
LowerLower
1919
UpperUpper
1616 PP
MiddleMiddle
==
Letter(Middle)Letter(Middle)
How the Search All How the Search All works.works.
A B C D E F G H I J K L M N O P Q R S Q R S T U V W X Y Z
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
ALGORITHM.ALGORITHM.Middle = (Lower + Upper) / 2CASE 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
1717
LowerLower
1919
UpperUpper
1616 PP
MiddleMiddle
==
Letter(Middle)Letter(Middle)
How the Search All How the Search All works.works.
A B C D E F G H I J K L M N O P Q Q RR S S T U V W X Y Z
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
ALGORITHM.ALGORITHM.Middle = (Lower + Upper) / 2CASE 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
1717
LowerLower
1919
UpperUpper
1818 RR
MiddleMiddle
==
Letter(Middle)Letter(Middle)
How the Search All How the Search All works.works.
A B C D E F G H I J K L M N O P Q Q R S R S T U V W X Y Z
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
ALGORITHM.ALGORITHM.Middle = (Lower + Upper) / 2CASE 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
1717
LowerLower
1717
UpperUpper
1818 RR
MiddleMiddle
==
Letter(Middle)Letter(Middle)
How the Search All How the Search All works.works.
A B C D E F G H I J K L M N O P QQ R S T U V W X Y Z
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
ALGORITHM.ALGORITHM.Middle = (Lower + Upper) / 2CASE 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
1717
LowerLower
1717
UpperUpper
1818 QQ
MiddleMiddle
==
Letter(Middle)Letter(Middle)
How the Search All How the Search All works.works.
A B C D E F G H I J K L M N O P QQ R S T U V W X Y Z
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
ALGORITHM.ALGORITHM.Middle = (Lower + Upper) / 2CASE 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
1717
LowerLower
1717
UpperUpper
1818 QQ
MiddleMiddle
==
Letter(Middle)Letter(Middle)
Search All Search All Example.Example.
01 StateTable. 02 StateValues. 03 FILLER PIC X(20) VALUE ?????????????? Post Codes and NamesPost Codes and Names 03 FILLER PIC X(20) VALUE ?????????????? 02 FILLER REDEFINES StateValues. 03 States OCCURS 50 TIMES ASCENDING KEY IS StateName INDEXED BY StateIdx. 04 PostCode PIC X(6). 04 StateName PIC X(14).
SEARCH ALL States AT END DISPLAY "State not found" WHEN StateName(StateIdx) = InputName MOVE PostCode(StateIdx) TO PrintPostCodeEND-SEARCH.
01 StateTable. 02 StateValues. 03 FILLER PIC X(20) VALUE ?????????????? Post Codes and NamesPost Codes and Names 03 FILLER PIC X(20) VALUE ?????????????? 02 FILLER REDEFINES StateValues. 03 States OCCURS 50 TIMES ASCENDING KEY IS StateName INDEXED BY StateIdx. 04 PostCode PIC X(6). 04 StateName PIC X(14).
SEARCH ALL States AT END DISPLAY "State not found" WHEN StateName(StateIdx) = InputName MOVE PostCode(StateIdx) TO PrintPostCodeEND-SEARCH.
INSPEINSPECT CT
340
INSPECT Syntax - Format INSPECT Syntax - Format 11
INSPECT FullName TALLYING UnstrPtr FOR LEADING SPACES.
INSPECT SourceLine TALLYING ECount FOR ALL "e" AFTER INITIAL "start"
BEFORE INITIAL "end".
INSPECT Example 1INSPECT Example 1
READ TextFile AT END SET EndOfFile TO TRUEEND-READPERFORM 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-READEND-PERFORMPERFORM VARYING idx FROM 1 BY 1 UNTIL idx > 26 DISPLAY "Letter " Letter(idx) " occurs " LetterCount(idx) " times" END-PERFORM
342
How the INSPECT works.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.
343
Modifying Modifying PhrasesPhrases
LEADINGThe LEADING phrase causes counting/replacement of all Compare$il characters from the first valid one encountered to the first invalid one.
FIRSTThe FIRST phrase causes only the first valid character to be replaced.
BEFOREThe BEFORE phrase designates as valid those characters to the left of the delimiter associated with it.
AFTERThe AFTER phrase designates as valid those characters to the right of the delimiter associated with it.
344
INSPECT Syntax - Format INSPECT Syntax - Format 22
PERFORM VARYING idx FROM 1 BY 1 UNTIL idx > 10
INSPECT TextLine REPLACING SwearWord(idx) BY "*#@!"
END-PERFORM
INSPECT StringData REPLACING ALL "FF" BY "GG" AFTER INITIAL "AA" BEFORE INITIAL "QQ".
FF FF FF FF AA FF FF FF FF FF QQ FF FF FF ZZ
StringDataStringData
INSPECT Example 2INSPECT Example 2
INSPECT Example INSPECT Example 22
INSPECT StringData REPLACING ALL "FF" BY "GG" AFTER INITIAL "AA" BEFORE INITIAL "QQ".
FF FF FF FF AA GG GG GG GG GG QQ FF FF FF ZZ
StringDataStringData
INSPECT Example 3INSPECT Example 3
INSPECT StringData REPLACING LEADING "FF" BY "GG" AFTER INITIAL "AA" BEFORE INITIAL "ZZ".
FF FF FF FF AA FF FF FF FF FF QQ FF FF FF ZZ
StringDataStringData
INSPECT Example 3INSPECT Example 3
INSPECT StringData REPLACING LEADING "FF" BY "GG" AFTER INITIAL "AA" BEFORE INITIAL "ZZ".
FF FF FF FF AA GG GG GG GG GG QQ FF FF FF ZZ
StringDataStringData
INSPECT Example 4INSPECT Example 4
INSPECT StringData REPLACING ALL "FF" BY "GG" AFTER INITIAL "AA" BEFORE INITIAL "ZZ".
FF FF FF FF AA FF FF FF FF FF QQ FF FF FF ZZ
StringDataStringData
INSPECT Example INSPECT Example 44
INSPECT StringData REPLACING ALL "FF" BY "GG" AFTER INITIAL "AA" BEFORE INITIAL "ZZ".
FF FF FF FF AA GG GG GG GG GG QQ GG GG GG ZZ
StringDataStringData
INSPECT Example 5INSPECT Example 5
INSPECT StringData REPLACING FIRST "FF" BY "GG" AFTER INITIAL "AA" BEFORE INITIAL "QQ".
FF FF FF FF AA FF FF FF FF FF QQ FF FF FF ZZ
StringDataStringData
INSPECT Example INSPECT Example 55
INSPECT StringData REPLACING FIRST "FF" BY "GG" AFTER INITIAL "AA" BEFORE INITIAL "QQ".
FF FF FF FF AA GG FF FF FF FF QQ FF FF FF ZZ
StringDataStringData
INSPECT Example INSPECT Example 66
FF FF FF FF AA FF FF FF FF FF QQ FF FF FF ZZ
StringDataStringData
INSPECT StringData REPLACING ALL "FFFFFFFF" BY "FROGFROG" AFTER INITIAL "AA" BEFORE INITIAL "QQ".
INSPECT Example INSPECT Example 66
FF FF FF FF AA FF RR OO GG FF QQ FF FF FF ZZ
StringDataStringData
INSPECT StringData REPLACING ALL "FFFFFFFF" BY "FROGFROG" AFTER INITIAL "AA" BEFORE INITIAL "QQ".
355
INSPECT Syntax - Format 3INSPECT Syntax - Format 3
356
INSPECT Syntax - Format 4INSPECT Syntax - Format 4
INSPECT TextLine CONVERTING "0123456789" TO "5298317046" AFTER INITIAL "codeon" BEFORE INITIAL "codeoff".
INSPECT Example 7INSPECT Example 7
INSPECT StringData CONVERTING "FXTDFXTD" TO "zyabzyab".
PP XX PP FF PP DD PP TT PP PP FF XX TT DD PP
StringDataStringData
INSPECT Example 7INSPECT Example 7
INSPECT StringData CONVERTING "FXTDFXTD" TO "zyabzyab".
PP yy PP zz PP bb PP aa PP PP zz yy aa bb PP
StringDataStringData
INSPECT Example 7INSPECT Example 7
INSPECT StringData REPLACING "FXTDFXTD" BY "zyabzyab".
PP XX PP FF PP DD PP TT PP PP FF XX TT DD PP
StringDataStringData
INSPECT Example 7INSPECT Example 7
INSPECT StringData REPLACING "FXTDFXTD" BY "zyabzyab".
PP XX PP FF PP DD PP TT PP PP zz yy aa bb PP
StringDataStringData
INSPECT Example 8INSPECT Example 8
PP xx PP ff PP dd PP TT PP PP ff xx TT dd PP
StringDataStringData
INSPECT StringData REPLACING ALL "xx" BY "yy" "dd" BY "zz" "ff" BY "ss".
INSPECT Example 8INSPECT Example 8
INSPECT StringData REPLACING ALL "XX" BY "yy" "DD" BY "zz" "FF" BY "ss".
PP yy PP ss PP zz PP TT PP PP ss yy TT zz PP
StringDataStringData
INSPECT Example INSPECT Example 99
INSPECT CustAddress CONVERTING "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz" TO "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ".
01 AlphaChars. 02 AlphaLower PIC X(26) VALUE "abcdefghijklmnopqrstuvwxyz". 02 AlphaUpper PIC X(26) VALUE "ABCDEFGHIJKLMNOPQRSTUVWXYZ".
INSPECT CustAddress CONVERTING AlphaLowerAlphaLower TO AlphaUpperAlphaUpper.INSPECT CustAddress CONVERTING AlphaUpperAlphaUpper TO AlphaLowerAlphaLower.
INSPECT Example INSPECT Example 1010
01 RussianPay PIC $$$,$$$,$$9.99.
MOVE 12345.67 TO RussianPay.INSPECT RussianPay REPLACING ALL "$"$" BY "RR".DISPLAY RussianPay " roubles".
RussianPayRussianPay
INSPECT Example 10INSPECT Example 10
01 RussianPay PIC $$$,$$$,$$9.99.
MOVE 12345.67 TO RussianPay.MOVE 12345.67 TO RussianPay.INSPECT RussianPay REPLACING ALL "$"$" BY "RR".DISPLAY RussianPay " roubles".
$12,345.67$12,345.67RussianPayRussianPay
INSPECT Example 10INSPECT Example 10
01 RussianPay PIC $$$,$$$,$$9.99.
MOVE 12345.67 TO RussianPay.INSPECT RussianPay REPLACING ALL "$$"" BY "RR".DISPLAY RussianPay " roubles".
RR12,345.6712,345.67RussianPayRussianPay
INSPECT Example 10INSPECT Example 10
01 RussianPay PIC $$$,$$$,$$9.99.
MOVE 12345.67 TO RussianPay.INSPECT RussianPay REPLACING ALL "$"$" BY "RR".DISPLAY RussianPay " roubles".
RR12,345.6712,345.67RussianPayRussianPay
R12,345.67 roublesR12,345.67 roubles
STRISTRING NG
STRING Syntax.STRING Syntax.
STRING Ident1, Ident2, "10" DELIMITED BY SIZE
INTO DestStringEND-STRING.
STRING Ident1 DELIMITED BY SIZE Ident2 DELIMITED BY SPACES Ident3 DELIMITED BY "Frogs" INTO Ident4 WITH POINTER StrPtrEND-STRING.
How the STRING How the STRING WorksWorks
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 STRING Example 11
01 DayStr PIC XX. 55
01 MonthStr PIC X(9). J U N EJ U N E
01 YearStr PIC X(4). 1 9 9 41 9 9 401 DateStr PIC X(15) VALUE ALL "-".
- - - - - - - - - - - - - - -- - - - - - - - - - - - - - -
STRING DayStr DELIMITED BY SPACES ", " DELIMITED BY SIZE MonthStr DELIMITED BY SPACES ", " DELIMITED BY SIZE YearStr DELIMITED BY SIZE INTO DateStrEND-STRING.
STRING Example STRING Example 11
01 DayStr PIC XX. 55
01 MonthStr PIC X(9). J U N EJ U N E
01 YearStr PIC X(4). 1 9 9 41 9 9 401 DateStr PIC X(15) VALUE ALL "-".
55 - - - - - - - - - - - - - - - - - - - - - - - - - - - -
STRING DayStr DELIMITED BY SPACESDayStr DELIMITED BY SPACES ", " DELIMITED BY SIZE MonthStr DELIMITED BY SPACES ", " DELIMITED BY SIZE YearStr DELIMITED BY SIZE INTO DateStrEND-STRING.
STRING Example 1STRING Example 1
01 DayStr PIC XX. 55
01 MonthStr PIC X(9). J U N EJ U N E
01 YearStr PIC X(4). 1 9 9 41 9 9 401 DateStr PIC X(15) VALUE ALL "-".
55 , , - - - - - - - - - - - - - - - - - - - - - - - - - -
STRING DayStr DELIMITED BY SPACES ", " DELIMITED BY SIZE", " DELIMITED BY SIZE MonthStr DELIMITED BY SPACES ", " DELIMITED BY SIZE YearStr DELIMITED BY SIZE INTO DateStrEND-STRING.
STRING Example 1STRING Example 1
01 DayStr PIC XX. 55
01 MonthStr PIC X(9). J U N EJ U N E
01 YearStr PIC X(4). 1 9 9 41 9 9 401 DateStr PIC X(15) VALUE ALL "-".
5 , J U N E 5 , J U N E - - - - - - - - -- - - - - - - - -
STRING DayStr DELIMITED BY SPACES ", " DELIMITED BY SIZE MonthStr DELIMITED BY SPACESMonthStr DELIMITED BY SPACES ", " DELIMITED BY SIZE YearStr DELIMITED BY SIZE INTO DateStrEND-STRING.
STRING Example STRING Example 11
01 DayStr PIC XX. 55
01 MonthStr PIC X(9). J U N EJ U N E
01 YearStr PIC X(4). 1 9 9 41 9 9 401 DateStr PIC X(15) VALUE ALL "-".
5 , J U N E , 5 , J U N E , - - - - - - - -- - - - - - - -
STRING DayStr DELIMITED BY SPACES ", " DELIMITED BY SIZE MonthStr DELIMITED BY SPACES ", " DELIMITED BY SIZE", " DELIMITED BY SIZE YearStr DELIMITED BY SIZE INTO DateStrEND-STRING.
STRING Example 1STRING Example 1
01 DayStr PIC XX. 55
01 MonthStr PIC X(9). J U N EJ U N E
01 YearStr PIC X(4). 1 9 9 41 9 9 401 DateStr PIC X(15) VALUE ALL "-".
5 , J U N E , 1 9 9 4 5 , J U N E , 1 9 9 4 - - - -- - - -
STRING DayStr DELIMITED BY SPACES ", " DELIMITED BY SIZE MonthStr DELIMITED BY SPACES ", " DELIMITED BY SIZE YearStr DELIMITED BY SIZEYearStr DELIMITED BY SIZE INTO DateStrEND-STRING.
STRING Example STRING Example 22
01 StrPtr PIC 99.
01 DayStr PIC XX. 5 5
01 MonthStr PIC X(9). J U N EJ U N E
01 YearStr PIC X(4). 1 9 9 41 9 9 401 DateStr PIC X(15) VALUE ALL "-".
- - - - - - - - - - - - - - -- - - - - - - - - - - - - - -
MOVE 1 TO StrPtrSTRING DayStr DELIMITED BY SPACES "," DELIMITED BY SIZE INTO DateStr WITH POINTER StrPtrEND-STRING.STRING MonthStr DELIMITED BY SPACES "," DELIMITED BY SIZE INTO DateStr WITH POINTER StrPtrEND-STRING.STRING YearStr DELIMITED BY SIZE INTO DateStr WITH POINTER StrPtrEND-STRING.
STRING Example 2STRING Example 2
01 StrPtr PIC 99.
01 DayStr PIC XX. 5 5
01 MonthStr PIC X(9). J U N EJ U N E
01 YearStr PIC X(4). 1 9 9 41 9 9 401 DateStr PIC X(15) VALUE ALL "-".
5 , 5 , - - - - - - - - - - - - -- - - - - - - - - - - - -
MOVE 1 TO StrPtrSTRING DayStr DELIMITED BY SPACES "," DELIMITED BY SIZE INTO DateStr WITH POINTER StrPtrEND-STRING.STRING MonthStr DELIMITED BY SPACES "," DELIMITED BY SIZE INTO DateStr WITH POINTER StrPtrEND-STRING.STRING YearStr DELIMITED BY SIZE INTO DateStr WITH POINTER StrPtrEND-STRING.
STRING Example 2STRING Example 2
01 StrPtr PIC 99.
01 DayStr PIC XX. 5 5
01 MonthStr PIC X(9). J U N EJ U N E
01 YearStr PIC X(4). 1 9 9 41 9 9 401 DateStr PIC X(15) VALUE ALL "-".
5 , J U N E , 5 , J U N E , - - - - - - - -- - - - - - - -
MOVE 1 TO StrPtrSTRING DayStr DELIMITED BY SPACES "," DELIMITED BY SIZE INTO DateStr WITH POINTER StrPtrEND-STRING.STRING MonthStr DELIMITED BY SPACES "," DELIMITED BY SIZE INTO DateStr WITH POINTER StrPtrEND-STRING.STRING YearStr DELIMITED BY SIZE INTO DateStr WITH POINTER StrPtrEND-STRING.
STRING Example 2STRING Example 2
01 StrPtr PIC 99.
01 DayStr PIC XX. 5 5
01 MonthStr PIC X(9). J U N EJ U N E
01 YearStr PIC X(4). 1 9 9 41 9 9 401 DateStr PIC X(15) VALUE ALL "-".
5 , J U N E , 1 9 9 4 5 , J U N E , 1 9 9 4 - - - -- - - -
MOVE 1 TO StrPtrSTRING DayStr DELIMITED BY SPACES "," DELIMITED BY SIZE INTO DateStr WITH POINTER StrPtrEND-STRING.STRING MonthStr DELIMITED BY SPACES "," DELIMITED BY SIZE INTO DateStr WITH POINTER StrPtrEND-STRING.STRING YearStr DELIMITED BY SIZE INTO DateStr WITH POINTER StrPtrEND-STRING.
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 DELIMITED BY SPACES INTO Field2END-STRING.DISPLAY Field2.
STRING Example 3STRING Example 3
This is the destination stringThis is the destination string
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 DELIMITED BY SPACES INTO Field2END-STRING.DISPLAY Field2.
STRING Example 3STRING Example 3
WhereWhereis the destination stringis the destination string
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 DELIMITED BY SIZE INTO Field2END-STRING.DISPLAY Field2.
STRING Example 4STRING Example 4
This is the destination stringThis is the destination string
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 DELIMITED BY SIZE INTO Field2END-STRING.DISPLAY Field2.
STRING Example 4STRING Example 4
Where does this goWhere does this goation stringation string
01 StringFields. 02 Field1 PIC X(18) VALUE "Where does this go". 02 Field2 PIC X(30) VALUE "This is the destination string". 02 Field3 PIC X(15) VALUE "Here is another".
01 StrPointers. 02 StrPtr PIC 99. 02 NewPtr PIC 9.
MOVE 6 TO StrPtr.STRING Field1, Field3 DELIMITED BY SPACE INTO Field2 WITH POINTER StrPtr ON OVERFLOW DISPLAY "String Error" NOT ON OVERFLOW DISPLAY Field2END-STRING.
STRING Example 5STRING Example 5
This is the destination stringThis is the destination string
01 StringFields. 02 Field1 PIC X(18) VALUE "Where does this go". 02 Field2 PIC X(30) VALUE "This is the destination string". 02 Field3 PIC X(15) VALUE "Here is another".
01 StrPointers. 02 StrPtr PIC 99. 02 NewPtr PIC 9.
MOVE 6 TO StrPtr.STRING Field1, Field3 DELIMITED BY SPACE INTO Field2 WITH POINTER StrPtr ON OVERFLOW DISPLAY "String Error" NOT ON OVERFLOW DISPLAY Field2END-STRING.
STRING Example 5STRING Example 5
This This WhereHereWhereHerestination stringstination string
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 Field4END-STRING.DISPLAY Field4
STRING Example 6STRING 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 Field4END-STRING.DISPLAY Field4
STRING Example 6STRING Example 6
WhereThisHereWhereThisHere
01 StringFields. 02 Field1 PIC X(18) VALUE "Where does this go". 02 Field2 PIC X(30) VALUE "This is the destination string". 02 Field3 PIC X(15) VALUE "Here is another".
01 StrPointers. 02 StrPtr PIC 99. 02 NewPtr PIC 9.
MOVE 4 TO NewPtr.STRING Field1 DELIMITED BY "this" Field3 DELIMITED BY SPACE "END" DELIMITED BY SIZE INTO Field2END-STRING.
STRING Example 7STRING Example 7
This is the destination stringThis is the destination string
01 StringFields. 02 Field1 PIC X(18) VALUE "Where does this go". 02 Field2 PIC X(30) VALUE "This is the destination string". 02 Field3 PIC X(15) VALUE "Here is another".
01 StrPointers. 02 StrPtr PIC 99. 02 NewPtr PIC 9.
MOVE 4 TO NewPtr.STRING Field1 DELIMITED BY "this" Field3 DELIMITED BY SPACE "END" DELIMITED BY SIZE INTO Field2END-STRING.
STRING Example 7STRING Example 7
Where does HereENDWhere does HereENDation stringation string
01 StringFields. 02 Field1 PIC X(18) VALUE "Where does this go". 02 Field2 PIC X(30) VALUE "This is the destination string". 02 Field3 PIC X(15) VALUE "Here is another".
01 StrPointers. 02 StrPtr PIC 99. 02 NewPtr PIC 9.
MOVE 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 Field2END-STRING.
STRING Example 8STRING Example 8
This is the destination stringThis is the destination string
01 StringFields. 02 Field1 PIC X(18) VALUE "Where does this go". 02 Field2 PIC X(30) VALUE "This is the destination string". 02 Field3 PIC X(15) VALUE "Here is another".
01 StrPointers. 02 StrPtr PIC 99. 02 NewPtr PIC 9.
MOVE 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 Field2END-STRING.
STRING Example 8STRING Example 8
ThiThiWhere Where he destination stringhe destination string
UNSTRUNSTRING ING
UNSTRING Syntax.UNSTRING Syntax.
UNSTRING FullName DELIMITED BY ALL SPACES INTO FirstName, SecondName, SurnameEND-UNSTRING
UNSTRING CustAddress DELIMITED BY "," INTO AdrLine(1), AdrLine(2), AdrLine(3), AdrLine(4), AdrLine(5), AdrLine(6) TALLYING IN AdrLinesUsedEND-UNSTRING.
395
How the UNSTRING How the UNSTRING worksworks
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.
396
UNSTRING UNSTRING TerminationTermination
The UNSTRING statement terminates when:-
All the characters in the Source String have been examinedOR
All the Destination Strings have been processed
OR
Some error condition is encountered.
397
UNSTRING UNSTRING clauses.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 INOnly one TALLYING clause can be used with each UNSTRING. It holds a count of the number of Destination Strings affected by the UNSTRING operation.
398
The UNSTRING clauses 2.The UNSTRING clauses 2.
WITH POINTERThe Pointer#i holds the position of the next non-delimiter character to be examined in the Source String.
Pointer#i must be large enough to hold a value one greater than the size of the Source String.
DELIMITER INA DELIMITER IN clause is associated with a particular Destination String. HoldDelim$i holds the Delimiter that was encountered in the Source String.
ALLWhen the ALL phrase is used, contiguous delimiters are treated as if only one delimiter had been encountered.
UNSTRING Example 1UNSTRING Example 1
01 DayStr PIC XX.
01 MonthStr PIC XX.
01 YearStr PIC XX.
01 DateStr PIC X(8). 1 9 - 0 5 - 8 01 9 - 0 5 - 8 0
ACCEPT DateStr.UNSTRING DateStr INTO DayStr, MonthStr, YearStr ON OVERFLOW DISPLAY "Chars Left"END-UNSTRING.
UNSTRING Example 1UNSTRING Example 1
01 DayStr PIC XX. 1 91 9
01 MonthStr PIC XX.
01 YearStr PIC XX.
01 DateStr PIC X(8). 1 91 9 - 0 5 - 8 0 - 0 5 - 8 0
ACCEPT DateStr.UNSTRING DateStr INTO DayStr, MonthStr, YearStr ON OVERFLOW DISPLAY "Chars Left"END-UNSTRING.
UNSTRING Example 1UNSTRING Example 1
01 DayStr PIC XX. 1 91 9
01 MonthStr PIC XX. - 0- 0
01 YearStr PIC XX.
01 DateStr PIC X(8). 1 9 1 9 - 0- 0 5 - 8 0 5 - 8 0
ACCEPT DateStr.UNSTRING DateStr INTO DayStr, MonthStr, YearStr ON OVERFLOW DISPLAY "Chars Left"END-UNSTRING.
UNSTRING Example 1UNSTRING Example 1
01 DayStr PIC XX. 1 91 9
01 MonthStr PIC XX. - 0- 0
01 YearStr PIC XX. 5 -5 -
01 DateStr PIC X(8). 1 9 - 0 1 9 - 0 5 -5 - 8 0 8 0
ACCEPT DateStr.UNSTRING DateStr INTO DayStr, MonthStr, YearStr ON OVERFLOW DISPLAY "Chars Left"END-UNSTRING.
UNSTRING Example 1UNSTRING Example 1
01 DayStr PIC XX. 1 91 9
01 MonthStr PIC XX. - 0- 0
01 YearStr PIC XX. 5 -5 -
01 DateStr PIC X(8). 1 9 - 0 5 - 8 01 9 - 0 5 - 8 0
ACCEPT DateStr.UNSTRING DateStr INTO DayStr, MonthStr, YearStr ON OVERFLOW DISPLAY "Chars Left"END-UNSTRING.
Chars LeftChars Left Chars LeftChars Left
UNSTRING Example 2UNSTRING 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 01 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 2UNSTRING Example 2
01 DayStr PIC XX. 1 91 9
01 MonthStr PIC XX.
01 YearStr PIC XX. 01 DateStr PIC X(8).
1 91 9 s t o ps t o p 0 5 s t o p 8 0 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 2UNSTRING Example 2
01 DayStr PIC XX. 1 91 9
01 MonthStr PIC XX. 0 50 5
01 YearStr PIC XX. 01 DateStr PIC X(8).
1 9 s t o p 1 9 s t o p 0 50 5 s t o ps t o p 8 0 8 0
ACCEPT DateStr.UNSTRING DateStr DELIMITED BY "stop" INTO DayStr, MonthStr, YearStr ON OVERFLOW DISPLAY "Chars Left"END-UNSTRING.
UNSTRING Example 2UNSTRING Example 2
01 DayStr PIC XX. 1 91 9
01 MonthStr PIC XX. 0 50 5
01 YearStr PIC XX. 8 08 001 DateStr PIC X(8).
1 9 s t o p 0 5 s t o p 1 9 s t o p 0 5 s t o p 8 08 0
ACCEPT DateStr.UNSTRING DateStr DELIMITED BY "stop" INTO DayStr, MonthStr, YearStr ON OVERFLOW DISPLAY "Chars Left"END-UNSTRING.
UNSTRING Example 3UNSTRING Example 3
01 DayStr PIC XX. 1 91 9
01 MonthStr PIC XX.
01 YearStr PIC XX.
01 DateStr PIC X(8). 1 91 9 -- 0 5 / 8 0 0 5 / 8 0
ACCEPT DateStr.UNSTRING DateStr DELIMITED BY "/" OR "-" INTO DayStr DELIMITER IN Hold1 MonthStr DELIMITER IN Hold2 YearStrEND-UNSTRING.DISPLAY DayStr SPACE MonthStr SPACE YearStr.DISPLAY Hold1 SPACE Hold2
UNSTRING Example 3UNSTRING Example 3
01 DayStr PIC XX. 1 91 9
01 MonthStr PIC XX. 0 50 5
01 YearStr PIC XX.
01 DateStr PIC X(8). 1 9 - 1 9 - 0 50 5 // 8 0 8 0
ACCEPT DateStr.UNSTRING DateStr DELIMITED BY "/" OR "-" INTO DayStr DELIMITER IN Hold1 MonthStr DELIMITER IN Hold2 YearStrEND-UNSTRING.DISPLAY DayStr SPACE MonthStr SPACE YearStr.DISPLAY Hold1 SPACE Hold2
UNSTRING Example 3UNSTRING Example 3
01 DayStr PIC XX. 1 91 9
01 MonthStr PIC XX. 0 50 5
01 YearStr PIC XX. 8 08 0
01 DateStr PIC X(8). 1 9 - 0 5 / 1 9 - 0 5 / 8 08 0
ACCEPT DateStr.UNSTRING DateStr DELIMITED BY "/" OR "-" INTO DayStr DELIMITER IN Hold1 MonthStr DELIMITER IN Hold2 YearStrEND-UNSTRING.DISPLAY DayStr SPACE MonthStr SPACE YearStr.DISPLAY Hold1 SPACE Hold2
UNSTRING Example 3UNSTRING Example 3
01 DayStr PIC XX. 1 91 9
01 MonthStr PIC XX. 0 50 5
01 YearStr PIC XX. 8 08 0
01 DateStr PIC X(8). 1 9 - 0 5 / 8 01 9 - 0 5 / 8 0
ACCEPT DateStr.UNSTRING DateStr DELIMITED BY "/" OR "-" INTO DayStr DELIMITER IN Hold1 MonthStr DELIMITER IN Hold2 YearStrEND-UNSTRING.DISPLAY DayStr SPACE MonthStr SPACE YearStr.DISPLAY Hold1 SPACE Hold2
19 05 8019 05 80- /- /19 05 8019 05 80- /- /
UNSTRING Example 4UNSTRING Example 4
01 DayStr PIC XX.
01 MonthStr PIC XX.
01 YearStr PIC XX.
01 DateStr PIC X(8). 1 9 - 0 5 / 8 01 9 - 0 5 / 8 0
ACCEPT DateStr.UNSTRING DateStr DELIMITED BY "/" OR "-" INTO DayStr DELIMITER IN Hold1 MonthStr DELIMITER IN Hold1 YearStrEND-UNSTRING.DISPLAY DayStr SPACE MonthStr SPACE YearStr.DISPLAY Hold1
UNSTRING Example 4UNSTRING Example 4
01 DayStr PIC XX. 1 91 9
01 MonthStr PIC XX. 0 50 5
01 YearStr PIC XX. 8 08 0
01 DateStr PIC X(8). 1 9 - 0 5 / 8 01 9 - 0 5 / 8 0
ACCEPT DateStr.UNSTRING DateStr DELIMITED BY "/" OR "-" INTO DayStr DELIMITER IN Hold1 MonthStr DELIMITER IN Hold1 YearStrEND-UNSTRING.DISPLAY DayStr SPACE MonthStr SPACE YearStr.DISPLAY Hold1
19 05 8019 05 80//19 05 8019 05 80//
UNSTRING Example 5UNSTRING Example 5
01 DayStr PIC XX.
01 MonthStr PIC XX.
01 YearStr PIC XX.
01 DateStr PIC X(11). 1 5 - - - 0 7 - - 9 41 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 5UNSTRING Example 5
01 DayStr PIC XX. 1 51 5
01 MonthStr PIC XX. 0 70 7
01 YearStr PIC XX. 9 49 4
01 DateStr PIC X(11). 1 51 5 - - -- - - 0 70 7 - -- - 9 49 4
ACCEPT DateStr.UNSTRING DateStr DELIMITED BY ALL "-" INTO DayStr, MonthStr, YearStr ON OVERFLOW DISPLAY "Chars Left"END-UNSTRING.
UNSTRING Example 6UNSTRING Example 6
01 DayStr PIC XX.
01 MonthStr PIC XX.
01 YearStr PIC XX.
01 DateStr PIC X(11). 1 5 - - - 0 7 - - 9 41 5 - - - 0 7 - - 9 4
ACCEPT DateStr.UNSTRING DateStr DELIMITED BY "-" INTO DayStr, MonthStr, YearStr ON OVERFLOW DISPLAY "Chars Left"END-UNSTRING.
UNSTRING Example 6UNSTRING Example 6
01 DayStr PIC XX. 1 51 5
01 MonthStr PIC XX.
01 YearStr PIC XX.
01 DateStr PIC X(11). 1 51 5 - - - - - 0 7 - - 9 4- 0 7 - - 9 4
ACCEPT DateStr.UNSTRING DateStr DELIMITED BY "-" INTO DayStr, MonthStr, YearStr ON OVERFLOW DISPLAY "Chars Left"END-UNSTRING.
Chars LeftChars LeftChars LeftChars Left
UNSTRING Example 7UNSTRING Example 701 OldName PIC X(80).
01 TempName. 02 NameInitial PIC X. 02 FILLER PIC X(15).
01 NewName PIC X(30).
01 Pointers. 02 StrPtr PIC 99 VALUE 1. 02 UnstrPtr PIC 99 VALUE 1. 88 NameProcessed VALUE 81.
PROCEDURE DIVISION.ProcessName. ACCEPT OldName. PERFORM UNTIL NameProcessed UNSTRING OldName DELIMITED BY ALL SPACES INTO TempName WITH POINTER UnstrPtr END-UNSTRING Display TempName END-PERFORM STOP RUN.
Tim John RobertsTim John Roberts
UNSTRING Example 7UNSTRING Example 701 OldName PIC X(80).
01 TempName. 02 NameInitial PIC X. 02 FILLER PIC X(15).
01 NewName PIC X(30).
01 Pointers. 02 StrPtr PIC 99 VALUE 1. 02 UnstrPtr PIC 99 VALUE 1. 88 NameProcessed VALUE 81.
PROCEDURE DIVISION.ProcessName. ACCEPT OldName. PERFORM UNTIL NameProcessed UNSTRING OldName DELIMITED BY ALL SPACES INTO TempName WITH POINTER UnstrPtr END-UNSTRING Display TempName END-PERFORM STOP RUN.
TimTimTimTim
TimTim John Roberts John Roberts
T imT im
UNSTRING Example 7UNSTRING Example 701 OldName PIC X(80).
01 TempName. 02 NameInitial PIC X. 02 FILLER PIC X(15).
01 NewName PIC X(30).
01 Pointers. 02 StrPtr PIC 99 VALUE 1. 02 UnstrPtr PIC 99 VALUE 1. 88 NameProcessed VALUE 81.
PROCEDURE DIVISION.ProcessName. ACCEPT OldName. PERFORM UNTIL NameProcessed UNSTRING OldName DELIMITED BY ALL SPACES INTO TempName WITH POINTER UnstrPtr END-UNSTRING Display TempName END-PERFORM STOP RUN.
JohnJohnJohnJohn
Tim Tim JohnJohn Roberts Roberts
J ohnJ ohn
UNSTRING Example 7UNSTRING Example 701 OldName PIC X(80).
01 TempName. 02 NameInitial PIC X. 02 FILLER PIC X(15).
01 NewName PIC X(30).
01 Pointers. 02 StrPtr PIC 99 VALUE 1. 02 UnstrPtr PIC 99 VALUE 1. 88 NameProcessed VALUE 81.
PROCEDURE DIVISION.ProcessName. ACCEPT OldName. PERFORM UNTIL NameProcessed UNSTRING OldName DELIMITED BY ALL SPACES INTO TempName WITH POINTER UnstrPtr END-UNSTRING Display TempName END-PERFORM STOP RUN.
RobertsRobertsRobertsRoberts
Tim John Tim John RobertsRoberts
R obertsR oberts
UNSTRING Example 8UNSTRING Example 8
OldName
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.
Tim John RobertsTim John Roberts
UNSTRING Example 8UNSTRING Example 8
OldName
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.
TimTim John Roberts John Roberts
T imT im
UNSTRING Example 8UNSTRING Example 8
OldName
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.
Tim John RobertsTim John Roberts
TT im im
T .T .
UNSTRING Example 8UNSTRING Example 8
OldName
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.
Tim Tim JohnJohn Roberts Roberts
J ohnJ ohn
T .T .
UNSTRING Example 8UNSTRING Example 8
OldName
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.
Tim John RobertsTim John Roberts
J J ohnohn
T . T . J .J .
UNSTRING Example 8UNSTRING Example 8
OldName
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.
Tim John Tim John RobertsRoberts
R obertsR oberts
T . J .T . J .
UNSTRING Example UNSTRING Example 88
OldName
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.
Tim John RobertsTim John Roberts
R obertsR oberts
T . J . T . J . RobertsRoberts
IntroductioIntroductionn
to to Sequential Sequential
FilesFiles
430
COBOL's COBOL's forteforte
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.
431
Files, Records, Files, Records, Fields.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.
432
Files, Records, Files, Records, Fields.Fields.
StudId StudName DateOfBirthStudId StudName DateOfBirth9723456 COUGHLAN 100919619724567 RYAN 311219769534118 COFFEY 230619649423458 O'BRIEN 031119799312876 SMITH 12121976
StudId StudName DateOfBirthStudId StudName DateOfBirth9723456 COUGHLAN 100919619724567 RYAN 311219769534118 COFFEY 230619649423458 O'BRIEN 031119799312876 SMITH 12121976
STUDENTS.DATSTUDENTS.DAT
DATA DIVISION.FILE SECTION.FD StudentFile.01 StudentDetails. 02 StudId PIC 9(7). 02 StudName PIC X(8). 02 DateOfBirth PIC X(8).
DATA DIVISION.FILE SECTION.FD StudentFile.01 StudentDetails. 02 StudId PIC 9(7). 02 StudName PIC X(8). 02 DateOfBirth PIC X(8).
occurrencesoccurrences
Record Type Record Type (Template)(Template)(Structure)(Structure)
433
How files are How files are processed.processed.
Files are repositories of data that reside on backing storage (hard disk or magnetic tape).
A file may consist of hundreds of thousands or even millions of records.
Suppose we want to keep information about all the TV license holders in the country. Suppose each record is about 150 characters/bytes long. If we estimate the number of licenses at 1 million this gives us a size for the file of 150 X 1,000,000 = 150 megabytes.
If we want to process a file of this size we cannot do it by loading the whole file into the computer’s memory at once.
Files are processed by reading them into the computer’s memory one record at a time.
434
Record Record BuffersBuffers
To process a file records are read from the file into the computer’s memory one record at a time.
The computer uses the programmers description of the record (i.e. the record template) to set aside sufficient memory to store one instance of the record.
Memory allocated for storing a record is usually called a “record buffer”
The record buffer is the only connection between the program and the records in the file.
435
Record Record BuffersBuffers
IDENTIFICATION DIVISION.etc.ENVIRONMENT DIVISION.etc.DATA DIVISION.FILE SECTION.
ProgramProgram
RecordBufferRecordBuffer DeclarationDeclaration
STUDENTS.DAT
DISK Record Instance
436
Implications of Implications of ‘Buffers’‘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 Creating a Student RecordRecord
01 StudentDetails.
Student Id. 02 StudentId PIC 9(7).
Student Name. 02 StudentName.
Surname 03 Surname PIC X(8).
Initials 03 Initials PIC XX. Date of Birth 02 DaateOfBirth.
Year of Birth 03 YOBirth PIC 99.
Month of Birth 03 MOBirth PIC 99.
Day of Birth 03 DOBirth PIC 99. Course Code 02 CourseCode PIC X(4).
Value of grant 02 Grant PIC 9(4).
Gender 02 Gender PIC X.
01 StudentDetails.
Student Id. 02 StudentId PIC 9(7).
Student Name. 02 StudentName.
Surname 03 Surname PIC X(8).
Initials 03 Initials PIC XX. Date of Birth 02 DaateOfBirth.
Year of Birth 03 YOBirth PIC 99.
Month of Birth 03 MOBirth PIC 99.
Day of Birth 03 DOBirth PIC 99. Course Code 02 CourseCode PIC X(4).
Value of grant 02 Grant PIC 9(4).
Gender 02 Gender PIC X.
Student Details.Student Details.
438
Describing the record buffer in COBOLDescribing the record buffer in COBOL
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.
DATA DIVISION.FILE SECTION.FD StudentFile.01 StudentDetails. 02 StudentId PIC 9(7). 02 StudentName. 03 Surname PIC X(8). 03 Initials PIC XX. 02 DateOfBirth. 03 YOBirth PIC 9(2). 03 MOBirth PIC 9(2). 03 DOBirth PIC 9(2). 02 CourseCode PIC X(4). 02 Grant PIC 9(4). 02 Gender PIC X.
DATA DIVISION.FILE SECTION.FD StudentFile.01 StudentDetails. 02 StudentId PIC 9(7). 02 StudentName. 03 Surname PIC X(8). 03 Initials PIC XX. 02 DateOfBirth. 03 YOBirth PIC 9(2). 03 MOBirth PIC 9(2). 03 DOBirth PIC 9(2). 02 CourseCode PIC X(4). 02 Grant PIC 9(4). 02 Gender PIC X.
439
STUDENTS.DAT
The Select and Assign The Select and Assign Clause.Clause.
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.
ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL. SELECT StudentFile ASSIGN TO “STUDENTS.DAT”.
DATA DIVISION.FILE SECTION.FD StudentFile.01 StudentDetails. 02 StudentId PIC 9(7). 02 StudentName. 03 Surname PIC X(8). 03 Initials PIC XX. 02 DateOfBirth. 03 YOBirth PIC 9(2). 03 MOBirth PIC 9(2). 03 DOBirth PIC 9(2). 02 CourseCode PIC X(4). 02 Grant PIC 9(4). 02 Gender PIC X.
ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL. SELECT StudentFile ASSIGN TO “STUDENTS.DAT”.
DATA DIVISION.FILE SECTION.FD StudentFile.01 StudentDetails. 02 StudentId PIC 9(7). 02 StudentName. 03 Surname PIC X(8). 03 Initials PIC XX. 02 DateOfBirth. 03 YOBirth PIC 9(2). 03 MOBirth PIC 9(2). 03 DOBirth PIC 9(2). 02 CourseCode PIC X(4). 02 Grant PIC 9(4). 02 Gender PIC X.
DISK
440
Select and Assign Select and Assign Syntax.Syntax.
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.
SELECT FileName ASSIGN TO ExternalFileReference
[ORGANIZATION IS LINE
RECORD SEQUENTIAL].
441
COBOL file handling COBOL file handling VerbsVerbs
OPENBefore 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.
READThe 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.
CLOSEYou 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.
442
OPEN and CLOSE verb OPEN and CLOSE verb syntaxsyntax
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.
OPEN InternalFileName ...
INPUT
OUTPUT
EXTEND
443
The READ verb 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.
444
READ verb READ verb syntaxsyntax
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.
READ InternalFilename NEXT RECORD
INTO Identifier
AT END StatementBlock
END - READ
445
PERFORM UNTIL StudentRecord = HIGH-VALUES READ StudentRecords AT END MOVE HIGH-VALUES TO StudentRecord END-READEND-PERFORM.
FF rr aa nn kk CC uu rr tt aa ii nn99 33 33 44 55 66 77 LL MM 00 55 11
StudentID StudentName Course.
StudentRecord
FF rr aa nn kk CC uu rr tt aa ii nn99 33 33 44 55 66 77 LL MM 00 55 11T h o m a s H e a l y9 3 8 3 7 1 5 L M 0 6 8T o n y O ‘ B r i a n9 3 4 7 2 9 2 L M 0 5 1B i l l y D o w n e s9 3 7 8 8 1 1 L M 0 2 1
EOF
How the READ How the READ worksworks
446
TT hh oo mm aa ss HH ee aa ll yy 99 33 88 33 77 11 55 LL MM 00 66 88
StudentID StudentName Course.
StudentRecord
F r a n k C u r t a i n9 3 3 4 5 6 7 L M 0 5 1
TT hh oo mm aa ss HH ee aa ll yy99 33 88 33 77 11 55 LL MM 00 66 88T o n y O ‘ B r i a n9 3 4 7 2 9 2 L M 0 5 1B i l l y D o w n e s9 3 7 8 8 1 1 L M 0 2 1
EOF
PERFORM UNTIL StudentRecord = HIGH-VALUES READ StudentRecords AT END MOVE HIGH-VALUES TO StudentRecord END-READEND-PERFORM.
How the READ How the READ worksworks
447
TT oo nn yy OO ‘‘ BB rr ii aa nn 99 33 44 77 22 99 22 LL MM 00 55 11
StudentID StudentName Course.
StudentRecord
F r a n k C u r t a i n9 3 3 4 5 6 7 L M 0 5 1T h o m a s H e a l y9 3 8 3 7 1 5 L M 0 6 8TT oo nn yy OO ‘‘ BB rr ii aa nn99 33 44 77 22 99 22 LL MM 00 55 11B i l l y D o w n e s9 3 7 8 8 1 1 L M 0 2 1
EOF
PERFORM UNTIL StudentRecord = HIGH-VALUES READ StudentRecords AT END MOVE HIGH-VALUES TO StudentRecord END-READEND-PERFORM.
How the READ How the READ worksworks
448
BB ii ll ll yy DD oo ww nn ee ss 99 33 77 88 88 11 11 LL MM 00 22 11
StudentID StudentName Course.
StudentRecord
F r a n k C u r t a i n9 3 3 4 5 6 7 L M 0 5 1T h o m a s H e a l y9 3 8 3 7 1 5 L M 0 6 8T o n y O ‘ B r i a n9 3 4 7 2 9 2 L M 0 5 1
BB ii ll ll yy DD oo ww nn ee ss99 33 77 88 88 11 11 LL MM 00 22 11
EOF
PERFORM UNTIL StudentRecord = HIGH-VALUES READ StudentRecords AT END MOVE HIGH-VALUES TO StudentRecord END-READEND-PERFORM.
How the READ How the READ worksworks
449
StudentID StudentName Course.
StudentRecord
F r a n k C u r t a i n9 3 3 4 5 6 7 L M 0 5 1T h o m a s H e a l y9 3 8 3 7 1 5 L M 0 6 8T o n y O ‘ B r i a n9 3 4 7 2 9 2 L M 0 5 1B i l l y D o w n e s9 3 7 8 8 1 1 L M 0 2 1
EOF
HIGH-VALUES
PERFORM UNTIL StudentRecord = HIGH-VALUES READ StudentRecords AT END MOVE HIGH-VALUES TO StudentRecord END-READEND-PERFORM.
How the READ How the READ worksworks
450
WRITE WRITE Syntax.Syntax.
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.
WRITE
ADVANCING
AdvanceNum
MnemonicName
PAGE
RecordName FROM Identifier
BEFORE
AFTER
LINE
LINES
FF rr aa nn kk CC uu rr tt aa ii nn99 33 33 44 55 66 77 LL MM 00 55 11
StudentID StudentName Course.
StudentRecord
FF rr aa nn kk CC uu rr tt aa ii nn99 33 33 44 55 66 77 LL MM 00 55 11
EOF
How the WRITE How the WRITE worksworks
OPEN OUTPUT StudentFile. MOVE "9334567Frank Curtain LM051" TO StudentDetails. WRITE StudentDetails. MOVE "9383715Thomas Healy LM068" TO StudentDetails. WRITE StudentDetails. CLOSE StudentFile. STOP RUN.
OPEN OUTPUT StudentFile. MOVE "9334567Frank Curtain LM051" TO StudentDetails. WRITE StudentDetails. MOVE "9383715Thomas Healy LM068" TO StudentDetails. WRITE StudentDetails. CLOSE StudentFile. STOP RUN.
Students.Dat
TT hh oo mm aa ss HH ee aa ll yy 99 33 88 33 77 11 55 LL MM 00 66 88
StudentID StudentName Course.
StudentRecord
F r a n k C u r t a i n9 3 3 4 5 6 7 L M 0 5 1
TT hh oo mm aa ss HH ee aa ll yy99 33 88 33 77 11 55 LL MM 00 66 88
EOF
How the WRITE How the WRITE worksworks
OPEN OUTPUT StudentFile. MOVE "9334567Frank Curtain LM051" TO StudentDetails. WRITE StudentDetails. MOVE "9383715Thomas Healy LM068" TO StudentDetails. WRITE StudentDetails. CLOSE StudentFile. STOP RUN.
OPEN OUTPUT StudentFile. MOVE "9334567Frank Curtain LM051" TO StudentDetails. WRITE StudentDetails. MOVE "9383715Thomas Healy LM068" TO StudentDetails. WRITE StudentDetails. CLOSE StudentFile. STOP RUN.
Students.Dat
$ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. SeqWrite.AUTHOR. Michael Coughlan.
ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL. SELECT StudentFile ASSIGN TO "STUDENTS.DAT"
ORGANIZATION IS LINE SEQUENTIAL.
DATA DIVISION.FILE SECTION.FD StudentFile.01 StudentDetails. 02 StudentId PIC 9(7). 02 StudentName. 03 Surname PIC X(8). 03 Initials PIC XX. 02 DateOfBirth. 03 YOBirth PIC 9(2). 03 MOBirth PIC 9(2). 03 DOBirth PIC 9(2). 02 CourseCode PIC X(4). 02 Grant PIC 9(4). 02 Gender PIC X.
PROCEDURE DIVISION.Begin. OPEN OUTPUT StudentFile. DISPLAY "Enter student details using template below. Enter no data to end.". PERFORM GetStudentDetails. PERFORM UNTIL StudentDetails = SPACES WRITE StudentDetails PERFORM GetStudentDetails END-PERFORM. CLOSE StudentFile. STOP RUN.
GetStudentDetails. DISPLAY "NNNNNNNSSSSSSSSIIYYMMDDCCCCGGGGS". ACCEPT StudentDetails.
$ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. SeqWrite.AUTHOR. Michael Coughlan.
ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL. SELECT StudentFile ASSIGN TO "STUDENTS.DAT"
ORGANIZATION IS LINE SEQUENTIAL.
DATA DIVISION.FILE SECTION.FD StudentFile.01 StudentDetails. 02 StudentId PIC 9(7). 02 StudentName. 03 Surname PIC X(8). 03 Initials PIC XX. 02 DateOfBirth. 03 YOBirth PIC 9(2). 03 MOBirth PIC 9(2). 03 DOBirth PIC 9(2). 02 CourseCode PIC X(4). 02 Grant PIC 9(4). 02 Gender PIC X.
PROCEDURE DIVISION.Begin. OPEN OUTPUT StudentFile. DISPLAY "Enter student details using template below. Enter no data to end.". PERFORM GetStudentDetails. PERFORM UNTIL StudentDetails = SPACES WRITE StudentDetails PERFORM GetStudentDetails END-PERFORM. CLOSE StudentFile. STOP RUN.
GetStudentDetails. DISPLAY "NNNNNNNSSSSSSSSIIYYMMDDCCCCGGGGS". ACCEPT StudentDetails.
$ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. SeqRead.AUTHOR. Michael Coughlan.
ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL. SELECT StudentFile ASSIGN TO “STUDENTS.DAT”
ORGANIZATION IS LINE SEQUENTIAL.
DATA DIVISION.FILE SECTION.FD StudentFile.01 StudentDetails. 02 StudentId PIC 9(7). 02 StudentName. 03 Surname PIC X(8). 03 Initials PIC XX. 02 DateOfBirth. 03 YOBirth PIC 9(2). 03 MOBirth PIC 9(2). 03 DOBirth PIC 9(2). 02 CourseCode PIC X(4). 02 Grant PIC 9(4). 02 Gender PIC X.
PROCEDURE DIVISION.Begin. OPEN INPUT StudentFile READ StudentFile AT END MOVE HIGH-VALUES TO StudentDetails END-READ PERFORM UNTIL StudentDetails = HIGH-VALUES DISPLAY StudentId SPACE StudentName SPACE CourseCode READ StudentFile AT END MOVE HIGH-VALUES TO StudentDetails END-READ END-PERFORM CLOSE StudentFile STOP RUN.
$ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. SeqRead.AUTHOR. Michael Coughlan.
ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL. SELECT StudentFile ASSIGN TO “STUDENTS.DAT”
ORGANIZATION IS LINE SEQUENTIAL.
DATA DIVISION.FILE SECTION.FD StudentFile.01 StudentDetails. 02 StudentId PIC 9(7). 02 StudentName. 03 Surname PIC X(8). 03 Initials PIC XX. 02 DateOfBirth. 03 YOBirth PIC 9(2). 03 MOBirth PIC 9(2). 03 DOBirth PIC 9(2). 02 CourseCode PIC X(4). 02 Grant PIC 9(4). 02 Gender PIC X.
PROCEDURE DIVISION.Begin. OPEN INPUT StudentFile READ StudentFile AT END MOVE HIGH-VALUES TO StudentDetails END-READ PERFORM UNTIL StudentDetails = HIGH-VALUES DISPLAY StudentId SPACE StudentName SPACE CourseCode READ StudentFile AT END MOVE HIGH-VALUES TO StudentDetails END-READ END-PERFORM CLOSE StudentFile STOP RUN.
ProcesProcessingsing
SequenSequentialtial
Files Files
PROCEDURE DIVISION.Begin.
OPEN OUTPUT StudentFileDISPLAY "Enter student details using template below. Press CR to end.". PERFORM GetStudentDetailsPERFORM UNTIL StudentDetails = SPACES
WRITE StudentDetailsPERFORM GetStudentDetails
END-PERFORMCLOSE StudentFileSTOP RUN.
GetStudentDetails.DISPLAY "NNNNNNNSSSSSSSSIIYYMMDDCCCCGGGGS".ACCEPT StudentDetails.
PROCEDURE DIVISION.Begin.
OPEN OUTPUT StudentFileDISPLAY "Enter student details using template below. Press CR to end.". PERFORM GetStudentDetailsPERFORM UNTIL StudentDetails = SPACES
WRITE StudentDetailsPERFORM GetStudentDetails
END-PERFORMCLOSE StudentFileSTOP RUN.
GetStudentDetails.DISPLAY "NNNNNNNSSSSSSSSIIYYMMDDCCCCGGGGS".ACCEPT StudentDetails.
Enter student details using template below. Press CR to end.NNNNNNNSSSSSSSSIIYYMMDDCCCCGGGGS9456789COUGHLANMS580812LM510598MNNNNNNNSSSSSSSSIIYYMMDDCCCCGGGGS9367892RYAN TG521210LM601222FNNNNNNNSSSSSSSSIIYYMMDDCCCCGGGGS9368934WILSON HR520323LM610786MNNNNNNNSSSSSSSSIIYYMMDDCCCCGGGGSCarriageReturn
Enter student details using template below. Press CR to end.NNNNNNNSSSSSSSSIIYYMMDDCCCCGGGGS9456789COUGHLANMS580812LM510598MNNNNNNNSSSSSSSSIIYYMMDDCCCCGGGGS9367892RYAN TG521210LM601222FNNNNNNNSSSSSSSSIIYYMMDDCCCCGGGGS9368934WILSON HR520323LM610786MNNNNNNNSSSSSSSSIIYYMMDDCCCCGGGGSCarriageReturn
Run of SeqWrite $ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. SeqWrite.AUTHOR. Michael Coughlan.
ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL. SELECT StudentFile ASSIGN TO "STUDENTS.DAT"
ORGANIZATION IS LINE SEQUENTIAL.
DATA DIVISION.FILE SECTION.FD StudentFile.01 StudentDetails. 02 StudentId PIC 9(7). 02 StudentName. 03 Surname PIC X(8). 03 Initials PIC XX. 02 DateOfBirth. 03 YOBirth PIC 9(2). 03 MOBirth PIC 9(2). 03 DOBirth PIC 9(2). 02 CourseCode PIC X(4). 02 Grant PIC 9(4). 02 Gender PIC X.
$ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. SeqWrite.AUTHOR. Michael Coughlan.
ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL. SELECT StudentFile ASSIGN TO "STUDENTS.DAT"
ORGANIZATION IS LINE SEQUENTIAL.
DATA DIVISION.FILE SECTION.FD StudentFile.01 StudentDetails. 02 StudentId PIC 9(7). 02 StudentName. 03 Surname PIC X(8). 03 Initials PIC XX. 02 DateOfBirth. 03 YOBirth PIC 9(2). 03 MOBirth PIC 9(2). 03 DOBirth PIC 9(2). 02 CourseCode PIC X(4). 02 Grant PIC 9(4). 02 Gender PIC X.
PROCEDURE DIVISION.Begin. OPEN INPUT StudentFile READ StudentFile AT END MOVE HIGH-VALUES TO StudentDetails END-READ PERFORM UNTIL StudentDetails = HIGH-VALUES DISPLAY StudentId SPACE StudentName SPACE CourseCode READ StudentFile AT END MOVE HIGH-VALUES TO StudentDetails END-READ END-PERFORM CLOSE StudentFile STOP RUN.
PROCEDURE DIVISION.Begin. OPEN INPUT StudentFile READ StudentFile AT END MOVE HIGH-VALUES TO StudentDetails END-READ PERFORM UNTIL StudentDetails = HIGH-VALUES DISPLAY StudentId SPACE StudentName SPACE CourseCode READ StudentFile AT END MOVE HIGH-VALUES TO StudentDetails END-READ END-PERFORM CLOSE StudentFile STOP RUN.
$ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. SeqRead.AUTHOR. Michael Coughlan.
ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL. SELECT StudentFile ASSIGN TO "STUDENTS.DAT"
ORGANIZATION IS LINE SEQUENTIAL.
DATA DIVISION.FILE SECTION.FD StudentFile.01 StudentDetails. 02 StudentId PIC 9(7). 02 StudentName. 03 Surname PIC X(8). 03 Initials PIC XX. 02 DateOfBirth. 03 YOBirth PIC 9(2). 03 MOBirth PIC 9(2). 03 DOBirth PIC 9(2). 02 CourseCode PIC X(4). 02 Grant PIC 9(4). 02 Gender PIC X.
$ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. SeqRead.AUTHOR. Michael Coughlan.
ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL. SELECT StudentFile ASSIGN TO "STUDENTS.DAT"
ORGANIZATION IS LINE SEQUENTIAL.
DATA DIVISION.FILE SECTION.FD StudentFile.01 StudentDetails. 02 StudentId PIC 9(7). 02 StudentName. 03 Surname PIC X(8). 03 Initials PIC XX. 02 DateOfBirth. 03 YOBirth PIC 9(2). 03 MOBirth PIC 9(2). 03 DOBirth PIC 9(2). 02 CourseCode PIC X(4). 02 Grant PIC 9(4). 02 Gender PIC X.
9456789 COUGHLANMS LM51
9367892 RYAN TG LM60
9368934 WILSON HR LM61
9456789 COUGHLANMS LM51
9367892 RYAN TG LM60
9368934 WILSON HR LM61
RUN OF SeqRead
458
Organization and Organization and AccessAccess
Two important characteristics of files are– DATA ORGANIZATIONDATA ORGANIZATION– METHOD OF ACCESSMETHOD 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.
459
Sequential Sequential OrganizationOrganization
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 OrderedOrdered
orUnorderedUnordered (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.
460
Ordered and Unordered Ordered and Unordered FilesFiles
RecordA
RecordB
RecordG
RecordH
RecordK
RecordM
RecordN
RecordA
RecordB
RecordG
RecordH
RecordK
RecordM
RecordN
Ordered File
RecordM
RecordH
RecordB
RecordN
RecordA
RecordK
RecordG
RecordM
RecordH
RecordB
RecordN
RecordA
RecordK
RecordG
Unordered File
In an ordered file the records are sequenced on some field in the record.
RecordF
RecordP
RecordW
RecordF
RecordP
RecordW
TransactionFile
RecordM
RecordH
RecordB
RecordN
RecordA
RecordK
RecordG
RecordM
RecordH
RecordB
RecordN
RecordA
RecordK
RecordG
Unordered FilePROGRAM
PROGRAMFILE SECTION.
PROCEDURE DIVISION.
OPEN EXTEND UF.
OPEN INPUT TF.
READ TF.
MOVE TFRec TO UFRec.
WRITE UFRec.
FILE SECTION.
PROCEDURE DIVISION.
OPEN EXTEND UF.
OPEN INPUT TF.
READ TF.
MOVE TFRec TO UFRec.
WRITE UFRec.
TFRecTFRec
UFRecUFRec
Adding records to unordered Adding records to unordered filesfiles
RecordFRecordF
RecordP
RecordW
RecordFRecordF
RecordP
RecordW
TransactionFile
RecordM
RecordH
RecordB
RecordN
RecordA
RecordK
RecordG
RecordFRecordF
RecordM
RecordH
RecordB
RecordN
RecordA
RecordK
RecordG
RecordFRecordF
Unordered FilePROGRAM
PROGRAMFILE SECTION.
PROCEDURE DIVISION.
OPEN EXTEND UF.
OPEN INPUT TF.
READ TF.
MOVE TFRec TO UFRec.
WRITE UFRec.
FILE SECTION.
PROCEDURE DIVISION.
OPEN EXTEND UF.
OPEN INPUT TF.
READ TF.
MOVE TFRec TO UFRec.
WRITE UFRec.
RecordFRecordF
RecordFRecordF
Adding records to unordered Adding records to unordered filesfiles
RecordFRecordF
RecordPRecordP
RecordWRecordW
RecordFRecordF
RecordPRecordP
RecordWRecordW
TransactionFile
RecordM
RecordH
RecordB
RecordN
RecordA
RecordK
RecordG
RecordFRecordF
RecordPRecordP
RecordWRecordW
RecordM
RecordH
RecordB
RecordN
RecordA
RecordK
RecordG
RecordFRecordF
RecordPRecordP
RecordWRecordW
Unordered File
RESULTRESULT
Adding records to unordered Adding records to unordered filesfiles
464
Problems with Unordered Sequential Problems with Unordered Sequential FilesFiles
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
465
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?
Problems with Unordered Sequential FilesProblems with Unordered Sequential Files
Deleting records from unordered Deleting records from unordered files?files?
RecordBRecordB
RecordM
RecordK
RecordBRecordB
RecordM
RecordK
Transaction File
RecordMRecordM
RecordH
RecordB
RecordN
RecordA
RecordK
RecordMRecordM
RecordH
RecordB
RecordN
RecordA
RecordK
Unordered File
New File
Delete UFDelete UFRecord?Record?
RecordMRecordMRecordMRecordM
NONO
RecordBRecordB
RecordM
RecordK
RecordBRecordB
RecordM
RecordK
Transaction File
RecordM
RecordHRecordH
RecordB
RecordN
RecordA
RecordK
RecordM
RecordHRecordH
RecordB
RecordN
RecordA
RecordK
Unordered File
New File
Delete UFDelete UFRecord?Record?
RecordM
RecordHRecordH
RecordM
RecordHRecordHNONO
Deleting records from unordered Deleting records from unordered files?files?
RecordBRecordB
RecordM
RecordK
RecordBRecordB
RecordM
RecordK
Transaction File
RecordM
RecordH
RecordBRecordB
RecordN
RecordA
RecordK
RecordM
RecordH
RecordBRecordB
RecordN
RecordA
RecordK
Unordered File
New File
Delete UFDelete UFRecord?Record?
RecordM
RecordH
RecordM
RecordHYESYES
Deleting records from unordered Deleting records from unordered files?files?
RecordB
RecordMRecordM
RecordK
RecordB
RecordMRecordM
RecordK
Transaction File
RecordM
RecordH
RecordB
RecordNRecordN
RecordA
RecordK
RecordM
RecordH
RecordB
RecordNRecordN
RecordA
RecordK
Unordered File
New File
Delete UFDelete UFRecord?Record?
RecordM
RecordH
RecordNRecordN
RecordM
RecordH
RecordNRecordN
NONO
But wait...We should have deleted RecordM. Too late. It’s already been written to the new file.
Deleting records from unordered Deleting records from unordered files?files?
RecordB
RecordK
RecordM
RecordB
RecordK
RecordM
Transaction File
RecordA
RecordB
RecordG
RecordH
RecordK
RecordM
RecordN
RecordA
RecordB
RecordG
RecordH
RecordK
RecordM
RecordN
Ordered File
New FilePROGRAM
FILE SECTION.
PROCEDURE DIVISION.OPEN INPUT TF.OPEN INPUT OFOPEN OUTPUT NF.READ TF.READ OF.IF TFKey NOT = OFKeyMOVE OFRec TO NFRecWRITE NFRecREAD OF
ELSEREAD TFREAD OF
END-IF.
FILE SECTION.
PROCEDURE DIVISION.OPEN INPUT TF.OPEN INPUT OFOPEN OUTPUT NF.READ TF.READ OF.IF TFKey NOT = OFKeyMOVE OFRec TO NFRecWRITE NFRecREAD OF
ELSEREAD TFREAD OF
END-IF.
TFRecTFRec
OFRecOFRec
NFRecNFRec
Deleting records from an ordered Deleting records from an ordered filefile
RecordBRecordB
RecordK
RecordM
RecordBRecordB
RecordK
RecordM
Transaction File
RecordARecordA
RecordB
RecordG
RecordH
RecordK
RecordM
RecordN
RecordARecordA
RecordB
RecordG
RecordH
RecordK
RecordM
RecordN
Ordered File
New FilePROGRAM
RecordARecordARecordARecordAFILE SECTION.
PROCEDURE DIVISION.OPEN INPUT TF.OPEN INPUT OFOPEN OUTPUT NF.READ TF.READ OF.IF TFRec NOT = OFRecMOVE OFRec TO NFRecWRITE NFRecREAD OF
ELSEREAD TFREAD OF
END-IF.
FILE SECTION.
PROCEDURE DIVISION.OPEN INPUT TF.OPEN INPUT OFOPEN OUTPUT NF.READ TF.READ OF.IF TFRec NOT = OFRecMOVE OFRec TO NFRecWRITE NFRecREAD OF
ELSEREAD TFREAD OF
END-IF.
RecordBRecordB
RecordARecordA
RecordARecordA
Deleting records from an ordered Deleting records from an ordered filefile
Problem !!How can we
recognize which record we want
to delete?
By its Key Field
RecordB
RecordK
RecordM
RecordB
RecordK
RecordM
Transaction File
RecordA
RecordBRecordB
RecordG
RecordH
RecordK
RecordM
RecordN
RecordA
RecordBRecordB
RecordG
RecordH
RecordK
RecordM
RecordN
Ordered File
New FilePROGRAM
FILE SECTION.
PROCEDURE DIVISION.OPEN INPUT TF.OPEN INPUT OFOPEN OUTPUT NF.READ TF.READ OF.IF TFKey NOT = OFKeyMOVE OFRec TO NFRecWRITE NFRecREAD OF
ELSEREAD TFREAD OF
END-IF.
FILE SECTION.
PROCEDURE DIVISION.OPEN INPUT TF.OPEN INPUT OFOPEN OUTPUT NF.READ TF.READ OF.IF TFKey NOT = OFKeyMOVE OFRec TO NFRecWRITE NFRecREAD OF
ELSEREAD TFREAD OF
END-IF.
RecordBRecordB
RecordBRecordB
RecordARecordA
Deleting records from an ordered Deleting records from an ordered filefile
RecordARecordA
RecordB
RecordKRecordK
RecordM
RecordB
RecordKRecordK
RecordM
Transaction File
RecordA
RecordB
RecordGRecordG
RecordH
RecordK
RecordM
RecordN
RecordA
RecordB
RecordGRecordG
RecordH
RecordK
RecordM
RecordN
Ordered File
New FilePROGRAM
RecordA
RecordGRecordG
RecordA
RecordGRecordG
FILE SECTION.
PROCEDURE DIVISION.OPEN INPUT TF.OPEN INPUT OFOPEN OUTPUT NF.READ TF.READ OF.IF TFKey NOT = OFKeyMOVE OFRec TO NFRecWRITE NFRecREAD OF
ELSEREAD TFREAD OF
END-IF.
FILE SECTION.
PROCEDURE DIVISION.OPEN INPUT TF.OPEN INPUT OFOPEN OUTPUT NF.READ TF.READ OF.IF TFKey NOT = OFKeyMOVE OFRec TO NFRecWRITE NFRecREAD OF
ELSEREAD TFREAD OF
END-IF.
RecordKRecordK
RecordGRecordG
RecordGRecordG
Deleting records from an ordered Deleting records from an ordered filefile
RecordBRecordB
RecordKRecordK
RecordMRecordM
RecordBRecordB
RecordKRecordK
RecordMRecordM
Transaction File
RecordARecordA
RecordBRecordB
RecordGRecordG
RecordHRecordH
RecordKRecordK
RecordMRecordM
RecordNRecordN
RecordARecordA
RecordBRecordB
RecordGRecordG
RecordHRecordH
RecordKRecordK
RecordMRecordM
RecordNRecordN
Ordered File
New File
RESULTRESULT
RecordARecordA
RecordGRecordG
RecordHRecordH
RecordNRecordN
RecordARecordA
RecordGRecordG
RecordHRecordH
RecordNRecordN
Deleting records from an ordered Deleting records from an ordered filefile
RecordB
RecordH
RecordK
RecordB
RecordH
RecordK
Transaction File
RecordA
RecordB
RecordG
RecordH
RecordK
RecordM
RecordN
RecordA
RecordB
RecordG
RecordH
RecordK
RecordM
RecordN
Ordered File
New FilePROGRAM
FILE SECTION.
PROCEDURE DIVISION.OPEN INPUT TF.OPEN INPUT OFOPEN OUTPUT NF.READ TF.READ OF.IF TFKey = OFKeyUpdate OFRec with TFRecMOVE OFRec+ TO NFRecWRITE NFRecREAD TFREAD OF
ELSEMOVE OFRec TO NFRecWRITE NFRec
READ OFEND-IF.
FILE SECTION.
PROCEDURE DIVISION.OPEN INPUT TF.OPEN INPUT OFOPEN OUTPUT NF.READ TF.READ OF.IF TFKey = OFKeyUpdate OFRec with TFRecMOVE OFRec+ TO NFRecWRITE NFRecREAD TFREAD OF
ELSEMOVE OFRec TO NFRecWRITE NFRec
READ OFEND-IF.
TFRecTFRec
OFRecOFRec
NFRecNFRec
Updating records in an ordered Updating records in an ordered filefile
RecordBRecordB
RecordH
RecordK
RecordBRecordB
RecordH
RecordK
Transaction File
RecordARecordA
RecordB
RecordG
RecordH
RecordK
RecordM
RecordN
RecordARecordA
RecordB
RecordG
RecordH
RecordK
RecordM
RecordN
Ordered File
New FilePROGRAM
RecordARecordARecordARecordAFILE SECTION.
PROCEDURE DIVISION.OPEN INPUT TF.OPEN INPUT OFOPEN OUTPUT NF.READ TF.READ OF.IF TFKey = OFKeyUpdate OFRec with TFRecMOVE OFRec+ TO NFRecWRITE NFRecREAD TFREAD OF
ELSEMOVE OFRec TO NFRecWRITE NFRec
READ OFEND-IF.
FILE SECTION.
PROCEDURE DIVISION.OPEN INPUT TF.OPEN INPUT OFOPEN OUTPUT NF.READ TF.READ OF.IF TFKey = OFKeyUpdate OFRec with TFRecMOVE OFRec+ TO NFRecWRITE NFRecREAD TFREAD OF
ELSEMOVE OFRec TO NFRecWRITE NFRec
READ OFEND-IF.
RecordBRecordB
RecordARecordA
RecordARecordA
Updating records in an ordered Updating records in an ordered filefile
RecordB
RecordH
RecordK
RecordB
RecordH
RecordK
Transaction File
RecordA
RecordBRecordB
RecordG
RecordH
RecordK
RecordM
RecordN
RecordA
RecordBRecordB
RecordG
RecordH
RecordK
RecordM
RecordN
Ordered File
New FilePROGRAM
RecordA
RecordB+RecordB+
RecordA
RecordB+RecordB+
FILE SECTION.
PROCEDURE DIVISION.OPEN INPUT TF.OPEN INPUT OFOPEN OUTPUT NF.READ TF.READ OF.IF TFKey = OFKeyUpdate OFRec with TFRecMOVE OFRec+ TO NFRecWRITE NFRecREAD TFREAD OF
ELSEMOVE OFRec TO NFRecWRITE NFRec
READ OFEND-IF.
FILE SECTION.
PROCEDURE DIVISION.OPEN INPUT TF.OPEN INPUT OFOPEN OUTPUT NF.READ TF.READ OF.IF TFKey = OFKeyUpdate OFRec with TFRecMOVE OFRec+ TO NFRecWRITE NFRecREAD TFREAD OF
ELSEMOVE OFRec TO NFRecWRITE NFRec
READ OFEND-IF.
RecordBRecordB
RecordBRecordB
RecordB+RecordB+
Updating records in an ordered Updating records in an ordered filefile
RecordB
RecordHRecordH
RecordK
RecordB
RecordHRecordH
RecordK
Transaction File
RecordA
RecordB
RecordGRecordG
RecordH
RecordK
RecordM
RecordN
RecordA
RecordB
RecordGRecordG
RecordH
RecordK
RecordM
RecordN
Ordered File
New FilePROGRAM
RecordA
RecordB+
RecordGRecordG
RecordA
RecordB+
RecordGRecordG
FILE SECTION.
PROCEDURE DIVISION.OPEN INPUT TF.OPEN INPUT OFOPEN OUTPUT NF.READ TF.READ OF.IF TFKey = OFKeyUpdate OFRec with TFRecMOVE OFRec+ TO NFRecWRITE NFRecREAD TFREAD OF
ELSEMOVE OFRec TO NFRecWRITE NFRec
READ OFEND-IF.
FILE SECTION.
PROCEDURE DIVISION.OPEN INPUT TF.OPEN INPUT OFOPEN OUTPUT NF.READ TF.READ OF.IF TFKey = OFKeyUpdate OFRec with TFRecMOVE OFRec+ TO NFRecWRITE NFRecREAD TFREAD OF
ELSEMOVE OFRec TO NFRecWRITE NFRec
READ OFEND-IF.
RecordHRecordH
RecordGRecordG
RecordGRecordG
Updating records in an ordered Updating records in an ordered filefile
RecordC
RecordF
RecordP
RecordC
RecordF
RecordP
Transaction File
RecordA
RecordB
RecordG
RecordH
RecordK
RecordM
RecordN
RecordA
RecordB
RecordG
RecordH
RecordK
RecordM
RecordN
Ordered File
New FilePROGRAM
FILE SECTION.
PROCEDURE DIVISION.OPEN INPUT TF.OPEN INPUT OFOPEN OUTPUT NF.READ TF.READ OF.IF TFKey < OFKeyMOVE TFRec TO NFRecWRITE NFRecREAD TF
ELSEMOVE OFRec TO NFRecWRITE NFRec
READ OFEND-IF.
FILE SECTION.
PROCEDURE DIVISION.OPEN INPUT TF.OPEN INPUT OFOPEN OUTPUT NF.READ TF.READ OF.IF TFKey < OFKeyMOVE TFRec TO NFRecWRITE NFRecREAD TF
ELSEMOVE OFRec TO NFRecWRITE NFRec
READ OFEND-IF.
TFRecTFRec
OFRecOFRec
NFRecNFRec
Inserting records into an ordered Inserting records into an ordered filefile
RecordCRecordC
RecordF
RecordP
RecordCRecordC
RecordF
RecordP
Transaction File
RecordARecordA
RecordB
RecordG
RecordH
RecordK
RecordM
RecordN
RecordARecordA
RecordB
RecordG
RecordH
RecordK
RecordM
RecordN
Ordered File
New FilePROGRAM
RecordARecordARecordARecordAFILE SECTION.
PROCEDURE DIVISION.OPEN INPUT TF.OPEN INPUT OFOPEN OUTPUT NF.READ TF.READ OF.IF TFKey < OFKeyMOVE TFRec TO NFRecWRITE NFRecREAD TF
ELSEMOVE OFRec TO NFRecWRITE NFRecREAD OF
END-IF.
FILE SECTION.
PROCEDURE DIVISION.OPEN INPUT TF.OPEN INPUT OFOPEN OUTPUT NF.READ TF.READ OF.IF TFKey < OFKeyMOVE TFRec TO NFRecWRITE NFRecREAD TF
ELSEMOVE OFRec TO NFRecWRITE NFRecREAD OF
END-IF.
RecordCRecordC
RecordARecordA
RecordARecordA
Inserting records into an ordered Inserting records into an ordered filefile
RecordC
RecordF
RecordP
RecordC
RecordF
RecordP
Transaction File
RecordA
RecordBRecordB
RecordG
RecordH
RecordK
RecordM
RecordN
RecordA
RecordBRecordB
RecordG
RecordH
RecordK
RecordM
RecordN
Ordered File
New FilePROGRAM
RecordA
RecordBRecordB
RecordA
RecordBRecordB
FILE SECTION.
PROCEDURE DIVISION.OPEN INPUT TF.OPEN INPUT OFOPEN OUTPUT NF.READ TF.READ OF.IF TFKey < OFKeyMOVE TFRec TO NFRecWRITE NFRecREAD TF
ELSEMOVE OFRec TO NFRecWRITE NFRecREAD OF
END-IF.
FILE SECTION.
PROCEDURE DIVISION.OPEN INPUT TF.OPEN INPUT OFOPEN OUTPUT NF.READ TF.READ OF.IF TFKey < OFKeyMOVE TFRec TO NFRecWRITE NFRecREAD TF
ELSEMOVE OFRec TO NFRecWRITE NFRecREAD OF
END-IF.
RecordCRecordC
RecordBRecordB
RecordBRecordB
Inserting records into an ordered Inserting records into an ordered filefile
RecordC
RecordF
RecordP
RecordC
RecordF
RecordP
Transaction File
RecordA
RecordB
RecordGRecordG
RecordH
RecordK
RecordM
RecordN
RecordA
RecordB
RecordGRecordG
RecordH
RecordK
RecordM
RecordN
Ordered File
New FilePROGRAM
RecordA
RecordB
RecordCRecordC
RecordA
RecordB
RecordCRecordC
FILE SECTION.
PROCEDURE DIVISION.OPEN INPUT TF.OPEN INPUT OFOPEN OUTPUT NF.READ TF.READ OF.IF TFKey < OFKeyMOVE TFRec TO NFRecWRITE NFRecREAD TF
ELSEMOVE OFRec TO NFRecWRITE NFRecREAD OF
END-IF.
FILE SECTION.
PROCEDURE DIVISION.OPEN INPUT TF.OPEN INPUT OFOPEN OUTPUT NF.READ TF.READ OF.IF TFKey < OFKeyMOVE TFRec TO NFRecWRITE NFRecREAD TF
ELSEMOVE OFRec TO NFRecWRITE NFRecREAD OF
END-IF.
RecordCRecordC
RecordGRecordG
RecordCRecordC
Inserting records into an ordered Inserting records into an ordered filefile
RecordC
RecordFRecordF
RecordP
RecordC
RecordFRecordF
RecordP
Transaction File
RecordA
RecordB
RecordG
RecordH
RecordK
RecordM
RecordN
RecordA
RecordB
RecordG
RecordH
RecordK
RecordM
RecordN
Ordered File
New FilePROGRAM
RecordA
RecordB
RecordC
RecordFRecordF
RecordA
RecordB
RecordC
RecordFRecordF
FILE SECTION.
PROCEDURE DIVISION.OPEN INPUT TF.OPEN INPUT OFOPEN OUTPUT NF.READ TF.READ OF.IF TFKey < OFKeyMOVE TFRec TO NFRecWRITE NFRecREAD TF
ELSEMOVE OFRec TO NFRecWRITE NFRecREAD OF
END-IF.
FILE SECTION.
PROCEDURE DIVISION.OPEN INPUT TF.OPEN INPUT OFOPEN OUTPUT NF.READ TF.READ OF.IF TFKey < OFKeyMOVE TFRec TO NFRecWRITE NFRecREAD TF
ELSEMOVE OFRec TO NFRecWRITE NFRecREAD OF
END-IF.
RecordFRecordF
RecordGRecordG
RecordFRecordF
Inserting records into an ordered Inserting records into an ordered filefile
RecordC
RecordF
RecordPRecordP
RecordC
RecordF
RecordPRecordP
Transaction File
RecordA
RecordB
RecordG
RecordH
RecordK
RecordM
RecordN
RecordA
RecordB
RecordG
RecordH
RecordK
RecordM
RecordN
Ordered File
New FilePROGRAM
RecordA
RecordB
RecordC
RecordF
RecordGRecordG
RecordA
RecordB
RecordC
RecordF
RecordGRecordG
FILE SECTION.
PROCEDURE DIVISION.OPEN INPUT TF.OPEN INPUT OFOPEN OUTPUT NF.READ TF.READ OF.IF TFKey < OFKeyMOVE TFRec TO NFRecWRITE NFRecREAD TF
ELSEMOVE OFRec TO NFRecWRITE NFRecREAD OF
END-IF.
FILE SECTION.
PROCEDURE DIVISION.OPEN INPUT TF.OPEN INPUT OFOPEN OUTPUT NF.READ TF.READ OF.IF TFKey < OFKeyMOVE TFRec TO NFRecWRITE NFRecREAD TF
ELSEMOVE OFRec TO NFRecWRITE NFRecREAD OF
END-IF.
RecordPRecordP
RecordGRecordG
RecordGRecordG
Inserting records into an ordered Inserting records into an ordered filefile
485
AdvancAdvanceded
SequeSequentialntial
Files 1.Files 1.
486
Single Record Type Single Record Type FilesFiles
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.
487
Multiple Record Type Multiple Record Type FilesFiles
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.
488
Implications of a multiple record transaction Implications of a multiple record transaction file.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).
489
Describing multiple record Describing multiple record filesfiles
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.
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!
DATA DIVISION.FILE SECTION.FD TransactionFile.01 InsertionRec. 02 StudentId PIC 9(7). 02 StudentName. 03 Surname PIC X(8). 03 Initials PIC XX. 02 DateOfBirth. 03 YOBirth PIC 9(2). 03 MOBirth PIC 9(2). 03 DOBirth PIC 9(2). 02 CourseCode PIC X(4). 02 Grant PIC 9(4). 02 Gender PIC X.
01 DeleteRec. 02 StudentId PIC 9(7).
01 UpdateRec. 02 StudentId PIC 9(7). 02 OldCourseCode PIC X(4). 02 NewCourseCode PIC X(4).
Multiple record descriptions - One record Multiple record descriptions - One record bufferbuffer
Multiple record descriptions in a file are IMPLICITLY redefinitions of the single record buffer.
9 2 3 0 1 6 5 H E N N E S S Y R M 7 1 0 9 1 5 L M 5 1 0 5 5 0 F
TransactionFile BufferTransactionFile Buffer
Multiple record descriptions in a file are IMPLICITLY redefinitions of the single record buffer.
InsertionRecInsertionRecStudentId StudentName DateOfBirth CourseCode Grant Gender InsertionRecInsertionRecStudentId StudentName DateOfBirth CourseCode Grant Gender
9 2 3 0 1 6 5 H E N N E S S Y R M 7 1 0 9 1 5 L M 5 1 0 5 5 0 F
TransactionFile BufferTransactionFile Buffer
Multiple record descriptions in a file are IMPLICITLY redefinitions of the single record buffer.
InsertionRecInsertionRecStudentId StudentName DateOfBirth CourseCode Grant Gender InsertionRecInsertionRecStudentId StudentName DateOfBirth CourseCode Grant Gender
StudentId
DeletionRecDeletionRec StudentId
DeletionRecDeletionRec
9 2 3 0 1 6 5 H E N N E S S Y R M 7 1 0 9 1 5 L M 5 1 0 5 5 0 F
TransactionFile BufferTransactionFile Buffer
Multiple record descriptions in a file are IMPLICITLY redefinitions of the single record buffer.
InsertionRecInsertionRecStudentId StudentName DateOfBirth CourseCode Grant Gender InsertionRecInsertionRecStudentId StudentName DateOfBirth CourseCode Grant Gender
StudentId
DeletionRecDeletionRec StudentId
DeletionRecDeletionRec
StudentId OldCourseCode NewCourseCode
UpdateRecUpdateRec StudentId OldCourseCode NewCourseCode
UpdateRecUpdateRec
9 2 3 0 1 6 5 H E N N E S S Y R M 7 1 0 9 1 5 L M 5 1 0 5 5 0 F
TransactionFile BufferTransactionFile Buffer
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? InsertionRecInsertionRecStudentId StudentName DateOfBirth CourseCode Grant Gender InsertionRecInsertionRecStudentId StudentName DateOfBirth CourseCode Grant Gender
StudentId
DeletionRecDeletionRec StudentId
DeletionRecDeletionRec
StudentId OldCourseCode NewCourseCode
UpdateRecUpdateRec StudentId OldCourseCode NewCourseCode
UpdateRecUpdateRec
9 2 3 0 1 6 5 H E N N E S S Y R M 7 1 0 9 1 5 L M 5 1 0 5 5 0 F
TransactionFile BufferTransactionFile Buffer
496
The Transaction Type The Transaction Type CodeCode
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.The Revised FD. 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 .
DATA DIVISION.FILE SECTION.FD TransactionFile.01 InsertionRec. 02 TransCode PIC X. 02 StudentId PIC 9(7). 02 StudentName. 03 Surname PIC X(8). 03 Initials PIC XX. 02 DateOfBirth. 03 YOBirth PIC 9(2). 03 MOBirth PIC 9(2). 03 DOBirth PIC 9(2). 02 CourseCode PIC X(4). 02 Grant PIC 9(4). 02 Gender PIC X.
01 DeleteRec. 02 TransCode PIC X. 02 StudentId PIC 9(7).
01 UpdateRec. 02 TransCode PIC X. 02 StudentId PIC 9(7). 02 OldCourseCode PIC X(4). 02 NewCourseCode PIC X(4).
The Final The Final FD.FD.
DATA DIVISION.FILE SECTION.FD TransactionFile.01 InsertionRec. 88 EndOfTransFile VALUE HIGH-VALUES. 02 TransCode PIC X. 88 Insertion VALUE "I". 88 Deletion VALUE "D". 88 Update VALUE "U". 02 StudentId PIC 9(7). 02 StudentName. 03 Surname PIC X(8). 03 Initials PIC XX. 02 DateOfBirth. 03 YOBirth PIC 9(2). 03 MOBirth PIC 9(2). 03 DOBirth PIC 9(2). 02 CourseCode PIC X(4). 02 Grant PIC 9(4). 02 Gender PIC X.
01 DeleteRec. 02 FILLER PIC X(8).
01 UpdateRec. 02 FILLER PIC X(8). 02 OldCourseCode PIC X(4). 02 NewCourseCode PIC X(4).
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.
What happens when we display the OldCourseCode? What happens if we now read an Update record into
the buffer?
InsertionRecInsertionRecTransCode StudentId StudentName DateOfBirth CourseCode Grant Gender InsertionRecInsertionRecTransCode StudentId StudentName DateOfBirth CourseCode Grant Gender
FILLER
DeletionRecDeletionRec FILLER
DeletionRecDeletionRec
FILLER OldCourseCode NewCourseCode
UpdateRecUpdateRecFILLER OldCourseCode NewCourseCode
UpdateRecUpdateRec
I 9 2 3 0 1 6 5 H E N N E S S Y R M 7 1 0 9 1 5 L M 5 1 0 5 5 0 F
TransactionFile BufferTransactionFile Buffer
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?
InsertionRecInsertionRecTransCode StudentId StudentName DateOfBirth CourseCode Grant Gender InsertionRecInsertionRecTransCode StudentId StudentName DateOfBirth CourseCode Grant Gender
FILLER
DeletionRecDeletionRec FILLER
DeletionRecDeletionRec
FILLER OldCourseCode NewCourseCode
UpdateRecUpdateRec FILLER OldCourseCode NewCourseCode
UpdateRecUpdateRec
U 9 3 1 5 6 8 2 L M 6 1 L M 5 1 R M 7 1 0 9 1 5 L M 5 1 0 5 5 0 F
TransactionFile BufferTransactionFile Buffer
501
Printing a Printing a Report.Report.
A report is made up of groups of printed lines of different types.
What types of line are required for the Student Details Report?
A program is required which will print a report.A program is required which will print a report.
The report, called the Student Details Report, will The report, called the Student Details Report, will be based on the file Students.Dat.be based on the file Students.Dat.
The report will show the Name, StudentId, Gender The report will show the Name, StudentId, Gender and CourseCode of each student in the file.and CourseCode of each student in the file.
502
Report Print Report Print Lines.Lines.
Page Heading.
– UL Student Details Report
Page Footing.
– Page : PageNum
Column Headings.
– Student Id. Student Name Gender Course
Student Detail Line.
– StudentId. StudentName Gender CourseCode
Report Footing.
– *** End of Student Details Report ***
Describing Print Describing Print Lines.Lines.
01 PageHeading. 02 FILLER PIC X(7) VALUE SPACES. 02 FILLER PIC X(25) VALUE "UL Student Details Report".
01 PageFooting. 02 FILLER PIC X(19) VALUE SPACES. 02 FILLER PIC X(7) VALUE "Page : ". 02 FILLER PIC 99.
01 ColumnHeadings PIC X(36) VALUE " StudentId StudentName Gender Course".
01 StudentDetailLine. 02 PrnStudId PIC BB9(7). 02 PrnStudName PIC BBX(10). 02 PrnGender PIC BBBBX. 02 PrnCourse PIC BBBBX(4).
01 ReportFooting PIC X(38) VALUE "*** End of Student Details Report ***".
The Print Lines are all different record types!
504
The File The File BufferBuffer
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.
In previous lectures we saw that the file bufferis 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?
ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL. SELECT Printer ASSIGN TO “LPT1”.
DATA DIVISION.FILE SECTION.FD Printer.01 PrintLine. ????????????????
505
No No VALUEVALUE clause in the clause in the FILE SECTIONFILE 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).
506
A A SolutionSolution
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.
We get round the problem as follows;We get round the problem as follows;
ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL. SELECT ReportFile ASSIGN TO “STUDENTS.RPT”.
DATA DIVISION.FILE SECTION.FD ReportFile.01 PrintLine PIC X(38).
WORKING-STORAGE SECTION.01 PageHeading. 02 FILLER PIC X(7) VALUE SPACES. 02 FILLER PIC X(25) VALUE "UL Student Details Report".
01 PageFooting. 02 FILLER PIC X(19) VALUE SPACES. 02 FILLER PIC X(7) VALUE "Page : ". 02 FILLER PIC 99.
01 ColumnHeadings PIC X(36) VALUE " StudentId StudentName Gender Course".
01 StudentDetailLine. 02 PrnStudId PIC BB9(7). 02 PrnStudName PIC BBX(10). 02 PrnGender PIC BBBBX. 02 PrnCourse PIC BBBBX(4).
01 ReportFooting PIC X(38) VALUE "*** End of Student Details Report ***".
STUDENTS.RPT
DISK
508
WRITE Syntax WRITE Syntax revisited.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.
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 Report".
01 StudentTotalLine. 02 FILLER PIC X(17) VALUE "Total Students = ". 02 PrnStudentCount PIC Z,ZZ9.
01 MaleTotalLine. 02 FILLER PIC X(17) VALUE "Total Males = ". 02 PrnMaleCount PIC Z,ZZ9.
01 FemaleTotalLine. 02 FILLER PIC X(17) VALUE "Total Females = ". 02 PrnFemaleCount PIC Z,ZZ9.
MOVE StudentCount TO PrnStudentCountMOVE MaleCount TO PrnMaleCountMOVE FemaleCount TO PrnFemaleCountWRITE PrintLine FROM HeadingLine AFTER ADVANCING PAGEWRITE PrintLine FROM StudentTotalLine AFTER ADVANCING 2 LINESWRITE PrintLine FROM MaleTotalLine AFTER ADVANCING 2 LINESWRITE PrintLine FROM FemaleTotalLine AFTER ADVANCING 2 LINES.
STUDENTS.RPT
DISK
510
SortSortandandMerMergege
511
The StudentFile is a sequential file sequenced upon ascending StudentId.
Write a program to display the number of students taking each course. How?
DATA DIVISION.DATA DIVISION.FILE SECTION.FILE SECTION.FD StudentFile.FD StudentFile.01 StudentDetails.01 StudentDetails. 02 StudentId PIC 9(7). 02 StudentId PIC 9(7). 02 StudentName. 02 StudentName. 03 Surname PIC X(8). 03 Surname PIC X(8). 03 Initials PIC XX. 03 Initials PIC XX. 02 DateOfBirth. 02 DateOfBirth. 03 YOBirth PIC 9(2). 03 YOBirth PIC 9(2). 03 MOBirth PIC 9(2). 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.
Simplified Sort Simplified Sort Syntax.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.
FD SalesFile.01 SalesRec. 02 FILLER PIC X(10).
SD WorkFile.01 WorkRec. 02 WSalesmanNum PIC 9(5). 02 FILLER PIC X(5).
FD SortedSalesFile.01 SortedSalesRec. 02 SalesmanNum PIC 9(5). 02 ItemType PIC X. 02 QtySold PIC 9(4).
PROCEDURE DIVISION.Begin. SORT WorkFile ON ASCENDING KEY WSalesmanNum USING SalesFile GIVING SortedSalesFile.
OPEN INPUT SortedSalesFile.
Sort Sort Example.Example.
ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL. SELECT WorkFile ASSIGN TO "WORK.TMP".
SD WorkFile.01 WorkRecord. 02 ProvinceCode PIC 9. 02 SalesmanCode PIC 9(5). 02 FILLER PIC X(19).
PROCEDURE DIVISION.Begin. SORT WorkFile ON ASCENDING KEY ProvinceCode DESCENDING KEY SalesmanCode USING UnsortedSales GIVING SortedSales.
OPEN INPUT SortedSales.
ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL. SELECT WorkFile ASSIGN TO "WORK.TMP".
SD WorkFile.01 WorkRecord. 02 ProvinceCode PIC 9. 02 SalesmanCode PIC 9(5). 02 FILLER PIC X(19).
PROCEDURE DIVISION.Begin. SORT WorkFile ON ASCENDING KEY ProvinceCode DESCENDING KEY SalesmanCode USING UnsortedSales GIVING SortedSales.
OPEN INPUT SortedSales.
SORTSORTProcessProcess
WorkFileWorkFile
How the SORT works.How the SORT works.
SORT WorkFile ON ASCENDING KEY WSalesmanNum USING SalesFile GIVING SortedSalesFile.
SalesFileSalesFile SortedSalesFileSortedSalesFile
UnsortedRecords
SortedRecords
SORTSORTProcessProcess
How the INPUT PROCEDURE How the INPUT PROCEDURE works.works.
SORT WorkFile ON ASCENDING KEY WSalesmanNum INPUT PROCEDURE IS SelectHatSales GIVING SortedSalesFile.
WorkFileWorkFile
SalesFileSalesFile SortedSalesFileSortedSalesFile
SortedRecords
SelectHatSalesSelectHatSales
UnsortedHat
Records
UnsortedRecords
517
OPEN INPUT InFileNameREAD InFileName RECORDPERFORM UNTIL Condition RELEASE SDWorkRec READ InFileName RECORDEND-PERFORMCLOSE InFile
OPEN INPUT InFileNameREAD InFileName RECORDPERFORM UNTIL Condition RELEASE SDWorkRec READ InFileName RECORDEND-PERFORMCLOSE InFile
INPUT PROCEDURE INPUT PROCEDURE TemplateTemplate
FD SalesFile.01 SalesRec. 88 EndOfSales VALUE HIGH-VALUES. 02 FILLER PIC 9(5). 02 FILLER PIC X. 88 HatRecord VALUE "H". 02 FILLER PIC X(4).SD WorkFile.01 WorkRec. 02 WSalesmanNum PIC 9(5). 02 FILLER PIC X(5).FD SortedSalesFile.01 SortedSalesRec. 02 SalesmanNum PIC 9(5). 02 ItemType PIC X. 02 QtySold PIC 9(4).PROCEDURE DIVISION.Begin. SORT WorkFile ON ASCENDING KEY WSalesmanNum INPUT PROCEDURE IS SelectHatSales GIVING SortedSalesFile.
FD SalesFile.01 SalesRec. 88 EndOfSales VALUE HIGH-VALUES. 02 FILLER PIC 9(5). 02 FILLER PIC X. 88 HatRecord VALUE "H". 02 FILLER PIC X(4).SD WorkFile.01 WorkRec. 02 WSalesmanNum PIC 9(5). 02 FILLER PIC X(5).FD SortedSalesFile.01 SortedSalesRec. 02 SalesmanNum PIC 9(5). 02 ItemType PIC X. 02 QtySold PIC 9(4).PROCEDURE DIVISION.Begin. SORT WorkFile ON ASCENDING KEY WSalesmanNum INPUT PROCEDURE IS SelectHatSales GIVING SortedSalesFile.
INPUT PROCEDURE - ExampleINPUT PROCEDURE - Example
New Version New Version
SelectHatSales. OPEN INPUT SalesFile
READ SalesFile AT END SET EndOfSales TO TRUE END-READ PERFORM UNTIL EndOfSales IF HatRecord RELEASE WorkRec FROM SalesRec END-IF READ SalesFile AT END SET EndOfSales TO TRUE END-READ END-PERFORM
CLOSE SalesFile.
SelectHatSales. OPEN INPUT SalesFile
READ SalesFile AT END SET EndOfSales TO TRUE END-READ PERFORM UNTIL EndOfSales IF HatRecord RELEASE WorkRec FROM SalesRec END-IF READ SalesFile AT END SET EndOfSales TO TRUE END-READ END-PERFORM
CLOSE SalesFile.
Old Version Old Version SelectHatSales SECTION.BeginHatSales. OPEN INPUT SalesFile READ SalesFile AT END SET EndOfSales TO TRUE END-READ PERFORM GetHatSales UNTIL EndOfSales CLOSE SalesFile GO TO SelectHatSalesExit.
GetHatSales. IF HatRecord RELEASE WorkRec FROM SalesRec END-IF READ SalesFile AT END SET EndOfSales TO TRUE END-READ.
SelectHatSalesExit EXIT.
SelectHatSales SECTION.BeginHatSales. OPEN INPUT SalesFile READ SalesFile AT END SET EndOfSales TO TRUE END-READ PERFORM GetHatSales UNTIL EndOfSales CLOSE SalesFile GO TO SelectHatSalesExit.
GetHatSales. IF HatRecord RELEASE WorkRec FROM SalesRec END-IF READ SalesFile AT END SET EndOfSales TO TRUE END-READ.
SelectHatSalesExit EXIT.
ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL. SELECT WorkFile ASSIGN TO "WORK.TMP".
SD WorkFile.01 WorkRecord. 88 EndOfWorkFile VALUE HIGH-VALUES. 02 ProvinceCode PIC 9. 88 ProvinceIsUlster VALUE 4. 02 SalesmanCode PIC 9(5). 02 FILLER PIC X(19).FD UnsortedSales.01 FILLER PIC X(25).FD SortedSales.01 SortedRec. 88 EndOfSalesFile VALUE HIGH-VALUES. 02 ProvinceCode PIC 9. 02 SalesmanCode PIC 9(5). 02 ItemCode PIC 9(7). 02 ItemCost PIC 9(3)V99. 02 QtySold PIC 9(7).
ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL. SELECT WorkFile ASSIGN TO "WORK.TMP".
SD WorkFile.01 WorkRecord. 88 EndOfWorkFile VALUE HIGH-VALUES. 02 ProvinceCode PIC 9. 88 ProvinceIsUlster VALUE 4. 02 SalesmanCode PIC 9(5). 02 FILLER PIC X(19).FD UnsortedSales.01 FILLER PIC X(25).FD SortedSales.01 SortedRec. 88 EndOfSalesFile VALUE HIGH-VALUES. 02 ProvinceCode PIC 9. 02 SalesmanCode PIC 9(5). 02 ItemCode PIC 9(7). 02 ItemCost PIC 9(3)V99. 02 QtySold PIC 9(7).
PROCEDURE DIVISION.Begin. SORT WorkFile ON ASCENDING KEY ProvinceCode SalesmanCode INPUT PROCEDURE IS SelectUlsterRecs GIVING SortedSales.
OPEN INPUT SortedSales.
SelectUlsterRecs. OPEN INPUT UnsortedSales READ UnsortedSales INTO WorkRec AT END SET EndOfSalesFile TO TRUE END-READ
PERFORM UNTIL EndOfSalesFile IF ProvinceIsUlster RELEASE WorkRec END-IF READ UnsortedSales INTO WorkRec AT END SET EndOfSalesFile TO TRUE END-READ END-PERFORM
CLOSE UnsortedSales
PROCEDURE DIVISION.Begin. SORT WorkFile ON ASCENDING KEY ProvinceCode SalesmanCode INPUT PROCEDURE IS SelectUlsterRecs GIVING SortedSales.
OPEN INPUT SortedSales.
SelectUlsterRecs. OPEN INPUT UnsortedSales READ UnsortedSales INTO WorkRec AT END SET EndOfSalesFile TO TRUE END-READ
PERFORM UNTIL EndOfSalesFile IF ProvinceIsUlster RELEASE WorkRec END-IF READ UnsortedSales INTO WorkRec AT END SET EndOfSalesFile TO TRUE END-READ END-PERFORM
CLOSE UnsortedSales
Full Sort Full Sort Syntax.Syntax.
ProcedureName is the name of a section or paragraph.
SummariseSalesSummariseSales
SORTSORTProcessProcess
WorkFileWorkFile
How the OUTPUT PROCEDURE How the OUTPUT PROCEDURE works.works.
SORT WorkFile ON ASCENDING KEY WSalesmanNum USING SalesFile OUTPUT PROCEDURE IS SummariseSales.
SalesFileSalesFile SalesSummaryFileSalesSummaryFile
UnsortedRecords
SalesmanSummary
RecordSortedRecords
OPEN OUTPUT OutFileRETURN SDWorkFile RECORDPERFORM UNTIL Condition WRITE OutRec RETURN SDWorkFile RECORDEND-PERFORMCLOSE OutFile
OUTPUT PROCEDURE OUTPUT PROCEDURE TemplateTemplate
FD SalesFile.01 SalesRec PIC X(10).SD WorkFile.01 WorkRec. 88 EndOfWorkFile VALUE HIGH-VALUES. 02 WSalesmanNum PIC 9(5). 02 FILLER PIC X. 02 WQtySold PIC X(4).FD SalesSummaryFile.01 SummaryRec. 02 SalesmanNum PIC 9(5). 02 TotalQtySold PIC 9(6).PROCEDURE DIVISION.Begin. SORT WorkFile ON ASCENDING KEY WSalesmanNum USING SalesFile OUTPUT PROCEDURE IS SummariseSales. OPEN INPUT SalesSummaryFile. PERFORM PrintSummaryReport.`
FD SalesFile.01 SalesRec PIC X(10).SD WorkFile.01 WorkRec. 88 EndOfWorkFile VALUE HIGH-VALUES. 02 WSalesmanNum PIC 9(5). 02 FILLER PIC X. 02 WQtySold PIC X(4).FD SalesSummaryFile.01 SummaryRec. 02 SalesmanNum PIC 9(5). 02 TotalQtySold PIC 9(6).PROCEDURE DIVISION.Begin. SORT WorkFile ON ASCENDING KEY WSalesmanNum USING SalesFile OUTPUT PROCEDURE IS SummariseSales. OPEN INPUT SalesSummaryFile. PERFORM PrintSummaryReport.`
Output PROCEDURE - ExampleOutput PROCEDURE - Example
SummariseSales. OPEN OUTPUT SalesSummaryFile RETURN WorkFile AT END SET EndOfWorkFile TO TRUE END-RETURN PERFORM UNTIL EndOfWorkFile MOVE WSalesmanNum TO SalesmanNum MOVE ZEROS TO TotalQtySold PERFORM UNTIL WSalesManNum NOT = SalesmanNum OR EndOfWorkFile ADD WQtySold TO TotalQtySold RETURN WorkFile AT END SET EndOfWorkFile TO TRUE END-RETURN END-PERFORM WRITE SummaryRec END-PERFORM CLOSE SalesSummaryFile.
SummariseSales. OPEN OUTPUT SalesSummaryFile RETURN WorkFile AT END SET EndOfWorkFile TO TRUE END-RETURN PERFORM UNTIL EndOfWorkFile MOVE WSalesmanNum TO SalesmanNum MOVE ZEROS TO TotalQtySold PERFORM UNTIL WSalesManNum NOT = SalesmanNum OR EndOfWorkFile ADD WQtySold TO TotalQtySold RETURN WorkFile AT END SET EndOfWorkFile TO TRUE END-RETURN END-PERFORM WRITE SummaryRec END-PERFORM CLOSE SalesSummaryFile.
528
RELEASE and RETURN RELEASE and RETURN SyntaxSyntax
Write
Read
Feeding the SORT from the Feeding the SORT from the keyboard.keyboard.
SORT WorkFile ON ASCENDING KEY WStudentId INPUT PROCEDURE IS GetStudentDetails GIVING StudentFile.
WorkFileWorkFile
StudentFileStudentFile
SortedStudentRecords
SORTSORTProcessProcess
GetStudentDetailsGetStudentDetails
UnsortedStudentRecords
8965125COUGHLAN
ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL. SELECT StudentFile ASSIGN TO "SORTSTUD.DAT"
ORGANIZATION IS LINE SEQUENTIAL. SELECT WorkFile ASSIGN TO "WORK.TMP".DATA DIVISION.FILE SECTION.FD StudentFile.01 StudentDetails PIC X(32).SD WorkFile.01 WorkRec. 02 WStudentId PIC 9(7). 02 FILLER PIC X(25).PROCEDURE DIVISION.Begin. SORT WorkFile ON ASCENDING KEY WStudentId INPUT PROCEDURE IS GetStudentDetails GIVING StudentFile. STOP RUN.GetStudentDetails. DISPLAY "Enter student details using template below." DISPLAY "Enter no data to end.". DISPLAY "NNNNNNNSSSSSSSSIIYYMMDDCCCCGGGGS". ACCEPT WorkRec. PERFORM UNTIL WorkRec = SPACES RELEASE WorkRec ACCEPT WorkRec END-PERFORM.
ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL. SELECT StudentFile ASSIGN TO "SORTSTUD.DAT"
ORGANIZATION IS LINE SEQUENTIAL. SELECT WorkFile ASSIGN TO "WORK.TMP".DATA DIVISION.FILE SECTION.FD StudentFile.01 StudentDetails PIC X(32).SD WorkFile.01 WorkRec. 02 WStudentId PIC 9(7). 02 FILLER PIC X(25).PROCEDURE DIVISION.Begin. SORT WorkFile ON ASCENDING KEY WStudentId INPUT PROCEDURE IS GetStudentDetails GIVING StudentFile. STOP RUN.GetStudentDetails. DISPLAY "Enter student details using template below." DISPLAY "Enter no data to end.". DISPLAY "NNNNNNNSSSSSSSSIIYYMMDDCCCCGGGGS". ACCEPT WorkRec. PERFORM UNTIL WorkRec = SPACES RELEASE WorkRec ACCEPT WorkRec END-PERFORM.
531
MERGE MERGE Syntax.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 DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL. SELECT StudentFile ASSIGN TO "STUDENTS.DAT" ORGANIZATION IS LINE SEQUENTIAL. SELECT InsertionsFile ASSIGN TO "TRANSINS.DAT" ORGANIZATION IS LINE SEQUENTIAL. SELECT NewStudentFile ASSIGN TO "STUDENTS.NEW" ORGANIZATION IS LINE SEQUENTIAL. SELECT WorkFile ASSIGN TO "WORK.TMP".
DATA DIVISION.FILE SECTION.FD StudentFile.01 StudentRec PIC X(32).FD InsertionsFile.01 InsertionRec PIC X(32).FD NewStudentFile.01 NewStudentRec PIC X(32).SD WorkFile.01 WorkRec. 02 WStudentId PIC 9(7). 02 FILLER PIC X(25).
PROCEDURE DIVISION.Begin. MERGE WorkFile ON ASCENDING KEY WStudentId USING InsertionsFile, StudentFile GIVING NewStudentFile. STOP RUN.
ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL. SELECT StudentFile ASSIGN TO "STUDENTS.DAT" ORGANIZATION IS LINE SEQUENTIAL. SELECT InsertionsFile ASSIGN TO "TRANSINS.DAT" ORGANIZATION IS LINE SEQUENTIAL. SELECT NewStudentFile ASSIGN TO "STUDENTS.NEW" ORGANIZATION IS LINE SEQUENTIAL. SELECT WorkFile ASSIGN TO "WORK.TMP".
DATA DIVISION.FILE SECTION.FD StudentFile.01 StudentRec PIC X(32).FD InsertionsFile.01 InsertionRec PIC X(32).FD NewStudentFile.01 NewStudentRec PIC X(32).SD WorkFile.01 WorkRec. 02 WStudentId PIC 9(7). 02 FILLER PIC X(25).
PROCEDURE DIVISION.Begin. MERGE WorkFile ON ASCENDING KEY WStudentId USING InsertionsFile, StudentFile GIVING NewStudentFile. STOP RUN.
IntroductioIntroduction ton to
Direct Direct AccessAccessFiles.Files.
Sequential Files - Adding a Sequential Files - Adding a RecordRecord
Rec085Rec085Rec300Rec300Rec150Rec150Rec005Rec005Rec090Rec090Rec045Rec045Rec100Rec100Rec001Rec001Rec325Rec325
^Z^Z
OrderedOrdered
Rec001Rec001Rec005Rec005Rec045Rec045Rec090Rec090Rec100Rec100Rec150Rec150Rec300Rec300Rec325Rec325
^Z^Z
UnorderedUnordered
Sequential Files - Adding a Sequential Files - Adding a RecordRecord
Rec085Rec085Rec300Rec300Rec150Rec150Rec005Rec005Rec090Rec090Rec045Rec045Rec100Rec100Rec001Rec001Rec325Rec325Rec085Rec085
^Z^Z
New-OrderedNew-Ordered
Rec001Rec001Rec005Rec005Rec045Rec045Rec085Rec085Rec090Rec090Rec100Rec100Rec150Rec150Rec300Rec300Rec325Rec325
^Z^Z
Extend-UnorderedExtend-Unordered
Sequential Files - Deleting a Sequential Files - Deleting a RecordRecord
Rec150Rec150Rec300Rec300Rec150Rec150Rec005Rec005Rec090Rec090Rec045Rec045Rec100Rec100Rec001Rec001Rec325Rec325
^Z^Z
OrderedOrdered
Rec001Rec001Rec005Rec005Rec045Rec045Rec090Rec090Rec100Rec100Rec150Rec150Rec300Rec300Rec325Rec325
^Z^Z
UnorderedUnordered
Sequential Files - Deleting a Sequential Files - Deleting a RecordRecord
Rec150Rec150Rec300Rec300Rec005Rec005Rec090Rec090Rec045Rec045Rec100Rec100Rec001Rec001Rec325Rec325
^Z^Z
New-OrderedNew-Ordered
Rec001Rec001Rec005Rec005Rec045Rec045Rec090Rec090Rec100Rec100Rec300Rec300Rec325Rec325
^Z^Z
New-UnorderedNew-Unordered
Sequential Files - Amending a Sequential Files - Amending a RecordRecord
Rec045Rec045Rec300Rec300Rec150Rec150Rec005Rec005Rec090Rec090Rec045Rec045Rec100Rec100Rec001Rec001Rec325Rec325
^Z^Z
OrderedOrdered
Rec001Rec001Rec005Rec005Rec045Rec045Rec090Rec090Rec100Rec100Rec150Rec150Rec300Rec300Rec325Rec325
^Z^Z
UnorderedUnordered
Sequential Files - Amending a Sequential Files - Amending a RecordRecord
Rec045Rec045Rec300Rec300Rec150Rec150Rec005Rec005Rec090Rec090Rec045Rec045Rec100Rec100Rec001Rec001Rec325Rec325
^Z^Z
New-OrderedNew-Ordered
Rec001Rec001Rec005Rec005Rec045Rec045 Rec090Rec090Rec100Rec100Rec150 Rec150 Rec300Rec300Rec325 Rec325
^Z^Z
New-UnorderedNew-Unordered
Relative Files – Relative Files – OrganizationOrganization
Rec001Rec001freefree
Rec003Rec003Rec004Rec004
freefreefreefree
Rec007 Rec007
Rec325Rec325Rec326Rec326
freefreeRec328Rec328
1
2
3
4
5
6
7
325
326
327
328
Relative RecordNumber
Relative Files - Adding a Relative Files - Adding a RecordRecord
Rec001Rec001freefree
Rec003Rec003Rec004Rec004
freefreefreefree
Rec007 Rec007
Rec325Rec325Rec326Rec326
freefreeRec328Rec328
1
2
3
4
5
6
7
325
326
327
328
Relative RecordNumber
Rec327Rec327
Relative Files - Adding a Relative Files - Adding a RecordRecord
Rec001Rec001freefree
Rec003Rec003Rec004Rec004
freefreefreefree
Rec007 Rec007
Rec325Rec325Rec326Rec326Rec327Rec327Rec328Rec328
1
2
3
4
5
6
7
325
326
327
328
Relative RecordNumber
Rec327Rec327
Relative Files - Deleting a Relative Files - Deleting a RecordRecord
Rec001Rec001freefree
Rec003Rec003Rec004Rec004
freefreefreefree
Rec007 Rec007
Rec325Rec325Rec326Rec326
freefreeRec328Rec328
1
2
3
4
5
6
7
325
326
327
328
Relative RecordNumber
Rec325Rec325
Relative Files - Deleting a Relative Files - Deleting a RecordRecord
Rec001Rec001freefree
Rec003Rec003Rec004Rec004
freefreefreefree
Rec007 Rec007
deleted/freedeleted/freeRec326Rec326
freefreeRec328Rec328
1
2
3
4
5
6
7
325
326
327
328
Relative RecordNumber
Rec325Rec325
Relative Files - Amending a Relative Files - Amending a RecordRecord
Rec001Rec001freefree
Rec003Rec003Rec004Rec004
freefreefreefree
Rec007 Rec007
Rec325Rec325Rec326Rec326
freefreeRec328Rec328
1
2
3
4
5
6
7
325
326
327
328
Relative RecordNumber
Rec007Rec007
Relative Files - Amending a Relative Files - Amending a RecordRecord
Rec001Rec001freefree
Rec003Rec003Rec004Rec004
freefreefreefree
Rec007 Rec007
Rec325Rec325Rec326Rec326
freefreeRec328Rec328
1
2
3
4
5
6
7
325
326
327
328
Relative RecordNumber
Rec007Rec007
Indexed Files - Indexed Files - OrganizationOrganization
H R ZH R Z
L O RL O RC F HC F H T W ZT W Z
Mi Nf Ni Nt Oi Ot
Index Records
Data Records
Indexed Files - Reading Record Indexed Files - Reading Record NiNi
H H RR Z Z
L O RL O RC F HC F H T W ZT W Z
Mi Nf Ni Nt Oi Ot
Index Records
Data Records
Indexed Files - Reading Record Indexed Files - Reading Record NiNi
H R ZH R Z
L L OO R RC F HC F H T W ZT W Z
Mi Nf Ni Nt Oi Ot
Index Records
Data Records
Indexed Files - Reading Record Indexed Files - Reading Record NiNi
H R ZH R Z
L O RL O RC F HC F H T W ZT W Z
Mi Nf Ni Nt Oi Ot
Index Records
Data Records
551
Sequential Sequential Files.Files.
Slow - when the hit rate is low. Complicated to change (insert, delete,
amend)
Fast - when the hit rate is high. Most storage efficient. Simple organization. Recovers space from deleted records.
Disadvantages.Disadvantages.
Advantages.Advantages.
552
Relative Relative Files.Files.
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.
Fastest Direct Access organization. Very little storage overhead. Can be read sequentially.
Disadvantages.Disadvantages.
Advantages.Advantages.
553
Indexed Indexed Files.Files.
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.
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.
Disadvantages.Disadvantages.
Advantages.Advantages.
RelatiRelative ve
Files.Files.
Creating a Relative Creating a Relative FileFile
$ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. CreateRelativeFromSeq.* Creates a Relative file from a sequential file.ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL. SELECT SupplierFile ASSIGN TO "SUPP.DAT" ORGANIZATION IS RELATIVE ACCESS MODE IS RANDOM RELATIVE KEY IS SupplierKey FILE STATUS IS SupplierStatus. SELECT SupplierFileSeq ASSIGN TO "INSUPP.DAT".
DATA DIVISION.FILE SECTION.FD SupplierFile.01 SupplierRecord. 02 SupplierCode PIC 99. 02 SupplierName PIC X(20). 02 SupplierAddress PIC X(60).
FD SupplierFileSeq.01 SupplierRecordSeq. 88 EndOfFile VALUE HIGH-VALUES. 02 SupplierCodeSeq PIC 99. 02 SupplierNameSeq PIC X(20). 02 SupplierAddressSeq PIC X(60).
WORKING-STORAGE SECTION.01 SupplierStatus PIC X(2).01 SupplierKey PIC 99.
$ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. CreateRelativeFromSeq.* Creates a Relative file from a sequential file.ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL. SELECT SupplierFile ASSIGN TO "SUPP.DAT" ORGANIZATION IS RELATIVE ACCESS MODE IS RANDOM RELATIVE KEY IS SupplierKey FILE STATUS IS SupplierStatus. SELECT SupplierFileSeq ASSIGN TO "INSUPP.DAT".
DATA DIVISION.FILE SECTION.FD SupplierFile.01 SupplierRecord. 02 SupplierCode PIC 99. 02 SupplierName PIC X(20). 02 SupplierAddress PIC X(60).
FD SupplierFileSeq.01 SupplierRecordSeq. 88 EndOfFile VALUE HIGH-VALUES. 02 SupplierCodeSeq PIC 99. 02 SupplierNameSeq PIC X(20). 02 SupplierAddressSeq PIC X(60).
WORKING-STORAGE SECTION.01 SupplierStatus PIC X(2).01 SupplierKey PIC 99.
$ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. CreateRelativeFromSeq.* Creates a Relative file from a sequential file.ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL. SELECT SupplierFile ASSIGN TO "SUPP.DAT" ORGANIZATION IS RELATIVE ACCESS MODE IS RANDOM RELATIVE KEY IS SupplierKeySupplierKey FILE STATUS IS SupplierStatusSupplierStatus. SELECT SupplierFileSeq ASSIGN TO "INSUPP.DAT".
DATA DIVISION.FILE SECTION.FD SupplierFile.01 SupplierRecord. 02 SupplierCode PIC 99. 02 SupplierName PIC X(20). 02 SupplierAddress PIC X(60).
FD SupplierFileSeq.01 SupplierRecordSeq. 88 EndOfFile VALUE HIGH-VALUES. 02 SupplierCodeSeq PIC 99. 02 SupplierNameSeq PIC X(20). 02 SupplierAddressSeq PIC X(60).
WORKING-STORAGE SECTION.01 SupplierStatusSupplierStatus PIC X(2).01 SupplierKeySupplierKey PIC 99.
$ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. CreateRelativeFromSeq.* Creates a Relative file from a sequential file.ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL. SELECT SupplierFile ASSIGN TO "SUPP.DAT" ORGANIZATION IS RELATIVE ACCESS MODE IS RANDOM RELATIVE KEY IS SupplierKeySupplierKey FILE STATUS IS SupplierStatusSupplierStatus. SELECT SupplierFileSeq ASSIGN TO "INSUPP.DAT".
DATA DIVISION.FILE SECTION.FD SupplierFile.01 SupplierRecord. 02 SupplierCode PIC 99. 02 SupplierName PIC X(20). 02 SupplierAddress PIC X(60).
FD SupplierFileSeq.01 SupplierRecordSeq. 88 EndOfFile VALUE HIGH-VALUES. 02 SupplierCodeSeq PIC 99. 02 SupplierNameSeq PIC X(20). 02 SupplierAddressSeq PIC X(60).
WORKING-STORAGE SECTION.01 SupplierStatusSupplierStatus PIC X(2).01 SupplierKeySupplierKey PIC 99.
Creating a Relative Creating a Relative FileFile
Creating a Relative Creating a Relative FileFile
PROCEDURE DIVISION.Begin. OPEN OUTPUT SupplierFile. OPEN INPUT SupplierFileSeq.
READ SupplierFileSeq AT END SET EndOfFile TO TRUE END-READ PERFORM UNTIL EndOfFile MOVE SupplierCodeSeq TO SupplierKey MOVE SupplierRecordSeq TO SupplierRecord WRITE SupplierRecord INVALID KEY DISPLAY "SUPP STATUS :-", SupplierStatus END-WRITE READ SupplierFileSeq AT END SET EndOfFile TO TRUE END-READ END-PERFORM.
CLOSE SupplierFile, SupplierFileSeq. STOP RUN.
PROCEDURE DIVISION.Begin. OPEN OUTPUT SupplierFile. OPEN INPUT SupplierFileSeq.
READ SupplierFileSeq AT END SET EndOfFile TO TRUE END-READ PERFORM UNTIL EndOfFile MOVE SupplierCodeSeq TO SupplierKey MOVE SupplierRecordSeq TO SupplierRecord WRITE SupplierRecord INVALID KEY DISPLAY "SUPP STATUS :-", SupplierStatus END-WRITE READ SupplierFileSeq AT END SET EndOfFile TO TRUE END-READ END-PERFORM.
CLOSE SupplierFile, SupplierFileSeq. STOP RUN.
Reading a Relative Reading a Relative File.File.
$ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. ReadRelative.* Reads a Relative file directly or in sequence
ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL.SELECT SupplierFile ASSIGN TO "SUPP.DAT" ORGANIZATION IS RELATIVE ACCESS MODE IS DYNAMIC RELATIVE KEY IS SupplierKeySupplierKey FILE STATUS IS SupplierStatusSupplierStatus.
DATA DIVISION.FILE SECTION.FD SupplierFile.01 SupplierRecord. 88 EndOfFile VALUE HIGH-VALUES. 02 SupplierCode PIC 99. 02 SupplierName PIC X(20). 02 SupplierAddress PIC X(60).
WORKING-STORAGE SECTION.01 SupplierStatusSupplierStatus PIC X(2). 88 RecordFound VALUE "00".01 SupplierKey SupplierKey PIC 99.01 PrnSupplierRecord. 02 PrnSupplierCode PIC BB99. 02 PrnSupplierName PIC BBX(20). 02 PrnSupplierAddress PIC BBX(50).01 ReadType PIC 9. 88 DirectRead VALUE 1. 88 SequentialRead VALUE 2.
$ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. ReadRelative.* Reads a Relative file directly or in sequence
ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL.SELECT SupplierFile ASSIGN TO "SUPP.DAT" ORGANIZATION IS RELATIVE ACCESS MODE IS DYNAMIC RELATIVE KEY IS SupplierKeySupplierKey FILE STATUS IS SupplierStatusSupplierStatus.
DATA DIVISION.FILE SECTION.FD SupplierFile.01 SupplierRecord. 88 EndOfFile VALUE HIGH-VALUES. 02 SupplierCode PIC 99. 02 SupplierName PIC X(20). 02 SupplierAddress PIC X(60).
WORKING-STORAGE SECTION.01 SupplierStatusSupplierStatus PIC X(2). 88 RecordFound VALUE "00".01 SupplierKey SupplierKey PIC 99.01 PrnSupplierRecord. 02 PrnSupplierCode PIC BB99. 02 PrnSupplierName PIC BBX(20). 02 PrnSupplierAddress PIC BBX(50).01 ReadType PIC 9. 88 DirectRead VALUE 1. 88 SequentialRead VALUE 2.
Reading a Relative Reading a Relative File.File.
PROCEDURE DIVISION.BEGIN. OPEN INPUT SupplierFile. DISPLAY "Enter Read type (Direct=1, Seq=2)-> " WITH NO ADVANCING. ACCEPT ReadType. IF DirectRead DISPLAY "Enter supplier key (2 digits)-> " WITH NO ADVANCING ACCEPT SupplierKey READ SupplierFile INVALID KEY DISPLAY "SUPP STATUS :-", SupplierStatus END-READ PERFORM DisplayRecord END-IF IF SequentialRead READ SupplierFile NEXT RECORD AT END SET EndOfFile TO TRUE END-READ PERFORM UNTIL EndOfFile PERFORM DisplayRecord READ SupplierFile NEXT RECORD AT END SET EndOfFile TO TRUE END-READ END-PERFORM END-IF CLOSE SupplierFile. STOP RUN.
DisplayRecord. IF RecordFound MOVE SupplierCode TO PrnSupplierCode MOVE SupplierName TO PrnSupplierName MOVE SupplierAddress TO PrnSupplierAddress DISPLAY PrnSupplierRecord END-IF.
PROCEDURE DIVISION.BEGIN. OPEN INPUT SupplierFile. DISPLAY "Enter Read type (Direct=1, Seq=2)-> " WITH NO ADVANCING. ACCEPT ReadType. IF DirectRead DISPLAY "Enter supplier key (2 digits)-> " WITH NO ADVANCING ACCEPT SupplierKey READ SupplierFile INVALID KEY DISPLAY "SUPP STATUS :-", SupplierStatus END-READ PERFORM DisplayRecord END-IF IF SequentialRead READ SupplierFile NEXT RECORD AT END SET EndOfFile TO TRUE END-READ PERFORM UNTIL EndOfFile PERFORM DisplayRecord READ SupplierFile NEXT RECORD AT END SET EndOfFile TO TRUE END-READ END-PERFORM END-IF CLOSE SupplierFile. STOP RUN.
DisplayRecord. IF RecordFound MOVE SupplierCode TO PrnSupplierCode MOVE SupplierName TO PrnSupplierName MOVE SupplierAddress TO PrnSupplierAddress DISPLAY PrnSupplierRecord END-IF.
Reading a Relative Reading a Relative File.File.
RUN OF REL-EG2.EXE USING SEQUENTIAL READINGEnter Read type (Direct=1, Seq=2)-> 2 01 VESTRON VIDEOS OVER THE SEA SOMEWHERE IN LONDON 02 EMI STUDIOS HOLLYWOOD, CALIFORNIA, USA 03 BBC WILDLIFE BUSH HOUSE, LONDON, ENGLAND 04 CBS STUDIOS HOLLYWOOD, CALIFORNIA, USA 05 YACHTING MONTHLY TREE HOUSE, LONDON, ENGLAND 06 VIRGIN VIDEOS IS THIS ONE ALSO LOCATED IN ENGLAND 07 CIC VIDEOS NEW YORK PLAZZA, NEW YORK, USA
RUN OF REL-EG2.EXE USING DIRECT READEnter Read type (Direct=1, Seq=2)-> 1Enter supplier key (2 digits)-> 05 05 YACHTING MONTHLY TREE HOUSE, LONDON, ENGLAND
RUN OF REL-EG2.EXE USING SEQUENTIAL READINGEnter Read type (Direct=1, Seq=2)-> 2 01 VESTRON VIDEOS OVER THE SEA SOMEWHERE IN LONDON 02 EMI STUDIOS HOLLYWOOD, CALIFORNIA, USA 03 BBC WILDLIFE BUSH HOUSE, LONDON, ENGLAND 04 CBS STUDIOS HOLLYWOOD, CALIFORNIA, USA 05 YACHTING MONTHLY TREE HOUSE, LONDON, ENGLAND 06 VIRGIN VIDEOS IS THIS ONE ALSO LOCATED IN ENGLAND 07 CIC VIDEOS NEW YORK PLAZZA, NEW YORK, USA
RUN OF REL-EG2.EXE USING DIRECT READEnter Read type (Direct=1, Seq=2)-> 1Enter supplier key (2 digits)-> 05 05 YACHTING MONTHLY TREE HOUSE, LONDON, ENGLAND
561
Select and Assign for Relative FilesSelect and Assign for Relative Files
562
FDs for Relative FDs for Relative FilesFiles
563
Relative File Verbs - Relative File Verbs - OPENOPEN
564
Relative File Verbs - Relative File Verbs - READREAD
565
Relative File Verbs - Write and RewriteRelative File Verbs - Write and Rewrite
566
Relative File Verbs - DELETERelative File Verbs - DELETE
567
Relative File Verbs - Relative File Verbs - STARTSTART
Error Handling Using Declaratives. Error Handling Using Declaratives.
PROCEDURE DIVISION.DECLARATIVES.SectionOne SECTION. USE clause for this section.ParOne1. ???????????????? ????????????????ParOne2. ???????????????? ????????????????
SectionTwo SECTION. USE clause for this section.ParTwo1. ???????????????? ????????????????ParTwo2. ???????????????? ????????????????END-DECLARATIVES.Main SECTION.Begin.
PROCEDURE DIVISION.DECLARATIVES.SectionOne SECTION. USE clause for this section.ParOne1. ???????????????? ????????????????ParOne2. ???????????????? ????????????????
SectionTwo SECTION. USE clause for this section.ParTwo1. ???????????????? ????????????????ParTwo2. ???????????????? ????????????????END-DECLARATIVES.Main SECTION.Begin.
Error Handling Using Declaratives. Error Handling Using Declaratives.
PROCEDURE DIVISION.DECLARATIVES.FileError SECTION. USE AFTER ERROR PROCEDURE ON RelativeFile.CheckFileStatus. EVALUATE TRUE WHEN RecordDoesNotExist DISPLAY "Record does not exist" WHEN RecordAlreadyExists DISPLAY "Record already exists" WHEN FileNotOpen OPEN I-O RelativeFile END-EVALUATE.END-DECLARATIVES.Main SECTION.Begin.
PROCEDURE DIVISION.DECLARATIVES.FileError SECTION. USE AFTER ERROR PROCEDURE ON RelativeFile.CheckFileStatus. EVALUATE TRUE WHEN RecordDoesNotExist DISPLAY "Record does not exist" WHEN RecordAlreadyExists DISPLAY "Record already exists" WHEN FileNotOpen OPEN I-O RelativeFile END-EVALUATE.END-DECLARATIVES.Main SECTION.Begin.
IndexIndexeded
Files.Files.
Creating an Indexed FileCreating an Indexed File
$ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. CreateIndexedFromSeq.* Creates an indexed file from a sequential file.
ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL. SELECT VideoFile ASSIGN TO "VIDEO.DAT" ORGANIZATION IS INDEXED ACCESS MODE IS RANDOM RECORD KEY IS VideoCode ALTERNATE RECORD KEY IS VideoTitle WITH DUPLICATES FILE STATUS IS VideoStatus. SELECT SeqVideoFile ASSIGN TO "INVIDEO.DAT".
DATA DIVISION.FILE SECTION.FD VideoFile.01 VideoRecord. 02 VideoCode PIC 9(5). 02 VideoTitle PIC X(40). 02 VideoSupplierCode PIC 99.FD SeqVideoFile.01 SeqVideoRecord. 88 EndOfFile VALUE HIGH-VALUES. 02 SeqVideoCode PIC 9(5). 02 SeqVideoTitle PIC X(40). 02 SeqVideoSupplierCode PIC 99.
WORKING-STORAGE SECTION.01 VideoStatus PIC X(2).
$ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. CreateIndexedFromSeq.* Creates an indexed file from a sequential file.
ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL. SELECT VideoFile ASSIGN TO "VIDEO.DAT" ORGANIZATION IS INDEXED ACCESS MODE IS RANDOM RECORD KEY IS VideoCode ALTERNATE RECORD KEY IS VideoTitle WITH DUPLICATES FILE STATUS IS VideoStatus. SELECT SeqVideoFile ASSIGN TO "INVIDEO.DAT".
DATA DIVISION.FILE SECTION.FD VideoFile.01 VideoRecord. 02 VideoCode PIC 9(5). 02 VideoTitle PIC X(40). 02 VideoSupplierCode PIC 99.FD SeqVideoFile.01 SeqVideoRecord. 88 EndOfFile VALUE HIGH-VALUES. 02 SeqVideoCode PIC 9(5). 02 SeqVideoTitle PIC X(40). 02 SeqVideoSupplierCode PIC 99.
WORKING-STORAGE SECTION.01 VideoStatus PIC X(2).
PROCEDURE DIVISION.Begin. OPEN INPUT SeqVideoFile. OPEN OUTPUT VideoFile.
READ SeqVideoFile AT END SET EndOfFile TO TRUE END-READ. PERFORM UNTIL EndOfFile WRITE VideoRecord FROM SeqVideoRecord INVALID KEY DISPLAY "VIDEO STATUS :- ", VideoStatus END-WRITE READ SeqVideoFile AT END SET EndOfFile TO TRUE END-READ END-PERFORM.
CLOSE VideoFile, SeqVideoFile. STOP RUN.
PROCEDURE DIVISION.Begin. OPEN INPUT SeqVideoFile. OPEN OUTPUT VideoFile.
READ SeqVideoFile AT END SET EndOfFile TO TRUE END-READ. PERFORM UNTIL EndOfFile WRITE VideoRecord FROM SeqVideoRecord INVALID KEY DISPLAY "VIDEO STATUS :- ", VideoStatus END-WRITE READ SeqVideoFile AT END SET EndOfFile TO TRUE END-READ END-PERFORM.
CLOSE VideoFile, SeqVideoFile. STOP RUN.
Creating an Indexed Creating an Indexed FileFile
Reading an Indexed File - Sequentially.Reading an Indexed File - Sequentially.
$ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. ReadingIndexedFile.* Sequential reading of an indexed file
ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL. SELECT VideoFile ASSIGN TO "VIDEO.DAT" ORGANIZATION IS INDEXED ACCESS MODE IS DYNAMIC RECORD KEY IS VideoCode ALTERNATE RECORD KEY IS VideoTitle WITH DUPLICATES FILE STATUS IS VideoStatus.
DATA DIVISION.FILE SECTION.FD VideoFile01 VideoRecord. 88 EndOfFile VALUE HIGH-VALUE. 02 VideoCode PIC 9(5). 02 VideoTitle PIC X(40). 02 SupplierCode PIC 99.
WORKING-STORAGE SECTION.01 VideoStatus PIC X(2).01 RequiredSequence PIC 9. 88 VideoCodeSequence VALUE 1. 88 VideoTitleSequence VALUE 2.01 PrnVideoRecord. 02 PrnVideoCode PIC 9(5). 02 PrnVideoTitle PIC BBBBX(40). 02 PrnSupplierCode PIC BBBB99.
$ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. ReadingIndexedFile.* Sequential reading of an indexed file
ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL. SELECT VideoFile ASSIGN TO "VIDEO.DAT" ORGANIZATION IS INDEXED ACCESS MODE IS DYNAMIC RECORD KEY IS VideoCode ALTERNATE RECORD KEY IS VideoTitle WITH DUPLICATES FILE STATUS IS VideoStatus.
DATA DIVISION.FILE SECTION.FD VideoFile01 VideoRecord. 88 EndOfFile VALUE HIGH-VALUE. 02 VideoCode PIC 9(5). 02 VideoTitle PIC X(40). 02 SupplierCode PIC 99.
WORKING-STORAGE SECTION.01 VideoStatus PIC X(2).01 RequiredSequence PIC 9. 88 VideoCodeSequence VALUE 1. 88 VideoTitleSequence VALUE 2.01 PrnVideoRecord. 02 PrnVideoCode PIC 9(5). 02 PrnVideoTitle PIC BBBBX(40). 02 PrnSupplierCode PIC BBBB99.
Reading an Indexed File - Sequentially.Reading an Indexed File - Sequentially.
PROCEDURE DIVISION.Begin. OPEN INPUT VideoFile.
DISPLAY "Enter key : 1=VideoCode, 2=VideoTitle ->" WITH NO ADVANCING. ACCEPT RequiredSequence.
IF VideoTitleSequence MOVE SPACES TO VideoTitle START VideoFile KEY IS GREATER THAN VideoTitle INVALID KEY DISPLAY "VIDEO STATUS :- ", VideoStatus END-START END-IF
READ VideoFile NEXT RECORD AT END SET EndOfFile TO TRUE END-READ. PERFORM UNTIL EndOfFile MOVE VideoCode TO PrnVideoCode MOVE VideoTitle TO PrnVideoTitle MOVE SupplierCode TO PrnSupplierCode DISPLAY PrnVideoRecord READ VideoFile NEXT RECORD AT END SET EndOfFile TO TRUE END-READ END-PERFORM.
CLOSE VideoFile. STOP RUN.
PROCEDURE DIVISION.Begin. OPEN INPUT VideoFile.
DISPLAY "Enter key : 1=VideoCode, 2=VideoTitle ->" WITH NO ADVANCING. ACCEPT RequiredSequence.
IF VideoTitleSequence MOVE SPACES TO VideoTitle START VideoFile KEY IS GREATER THAN VideoTitle INVALID KEY DISPLAY "VIDEO STATUS :- ", VideoStatus END-START END-IF
READ VideoFile NEXT RECORD AT END SET EndOfFile TO TRUE END-READ. PERFORM UNTIL EndOfFile MOVE VideoCode TO PrnVideoCode MOVE VideoTitle TO PrnVideoTitle MOVE SupplierCode TO PrnSupplierCode DISPLAY PrnVideoRecord READ VideoFile NEXT RECORD AT END SET EndOfFile TO TRUE END-READ END-PERFORM.
CLOSE VideoFile. STOP RUN.
Reading an Indexed File - Sequentially.Reading an Indexed File - Sequentially.
RUN OF INDEX-EG2.EXE USING VIDEOCODE KEYEnter key : 1=VideoCode, 2=VideoTitle ->100121 FLIGHT OF THE CONDOR, THE 0300333 PREDATOR 0200444 LIVING EARTH, THE 0301001 COMMANDO 0201100 ROBOCOP 0102001 LEOPARD HUNTS IN DARKNESS, A 0302121 DIRTY DANCING 0403031 COMPETENT CREW 0503032 YACHT MASTER 0504041 OPEN OCEAN SAILING 0504042 PRINCESS BRIDE, THE 0604444 LIFE ON EARTH 0305051 OVERBOARD 0106061 HOPE AND GLORY 0707071 AMONG THE WILD CHIMPANZEES 0308081 WHALE NATION 0309091 BESTSELLER 0710001 WICKED WALTZING 0411111 TERMINATOR, THE 0213301 MASSACRE AT MASAI MARA 0314032 KNOTTY PROBLEMS FOR SAILORS 0517001 ALIEN 0717002 ALIENS 0717041 GARFIELD TAKES A HIKE 0618001 SURVIVING THE STORM 0519444 PINOCCIO 02
RUN OF INDEX-EG2.EXE USING VIDEOCODE KEYEnter key : 1=VideoCode, 2=VideoTitle ->100121 FLIGHT OF THE CONDOR, THE 0300333 PREDATOR 0200444 LIVING EARTH, THE 0301001 COMMANDO 0201100 ROBOCOP 0102001 LEOPARD HUNTS IN DARKNESS, A 0302121 DIRTY DANCING 0403031 COMPETENT CREW 0503032 YACHT MASTER 0504041 OPEN OCEAN SAILING 0504042 PRINCESS BRIDE, THE 0604444 LIFE ON EARTH 0305051 OVERBOARD 0106061 HOPE AND GLORY 0707071 AMONG THE WILD CHIMPANZEES 0308081 WHALE NATION 0309091 BESTSELLER 0710001 WICKED WALTZING 0411111 TERMINATOR, THE 0213301 MASSACRE AT MASAI MARA 0314032 KNOTTY PROBLEMS FOR SAILORS 0517001 ALIEN 0717002 ALIENS 0717041 GARFIELD TAKES A HIKE 0618001 SURVIVING THE STORM 0519444 PINOCCIO 02
RUN OF INDEX-EG2 USING VIDEOTITLE KEYEnter key : 1=VideoCode, 2=VideoTitle ->2 17001 ALIEN 0717002 ALIENS 0707071 AMONG THE WILD CHIMPANZEES 0309091 BESTSELLER 0701001 COMMANDO 0203031 COMPETENT CREW 0502121 DIRTY DANCING 0400121 FLIGHT OF THE CONDOR, THE 0317041 GARFIELD TAKES A HIKE 0606061 HOPE AND GLORY 0714032 KNOTTY PROBLEMS FOR SAILORS 0502001 LEOPARD HUNTS IN DARKNESS, A 0304444 LIFE ON EARTH 0300444 LIVING EARTH, THE 0313301 MASSACRE AT MASAI MARA 0304041 OPEN OCEAN SAILING 0505051 OVERBOARD 0119444 PINOCCIO 0200333 PREDATOR 0204042 PRINCESS BRIDE, THE 0601100 ROBOCOP 0118001 SURVIVING THE STORM 0511111 TERMINATOR, THE 0208081 WHALE NATION 0310001 WICKED WALTZING 0403032 YACHT MASTER 05
RUN OF INDEX-EG2 USING VIDEOTITLE KEYEnter key : 1=VideoCode, 2=VideoTitle ->2 17001 ALIEN 0717002 ALIENS 0707071 AMONG THE WILD CHIMPANZEES 0309091 BESTSELLER 0701001 COMMANDO 0203031 COMPETENT CREW 0502121 DIRTY DANCING 0400121 FLIGHT OF THE CONDOR, THE 0317041 GARFIELD TAKES A HIKE 0606061 HOPE AND GLORY 0714032 KNOTTY PROBLEMS FOR SAILORS 0502001 LEOPARD HUNTS IN DARKNESS, A 0304444 LIFE ON EARTH 0300444 LIVING EARTH, THE 0313301 MASSACRE AT MASAI MARA 0304041 OPEN OCEAN SAILING 0505051 OVERBOARD 0119444 PINOCCIO 0200333 PREDATOR 0204042 PRINCESS BRIDE, THE 0601100 ROBOCOP 0118001 SURVIVING THE STORM 0511111 TERMINATOR, THE 0208081 WHALE NATION 0310001 WICKED WALTZING 0403032 YACHT MASTER 05
Reading an Indexed File - Directly.Reading an Indexed File - Directly.
IDENTIFICATION DIVISION.PROGRAM-ID. ReadingIndexedFile.* Illustrates direct read on an indexed file by any key
ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL. SELECT VideoFile ASSIGN TO "VIDEO.DAT" ORGANIZATION IS INDEXED ACCESS MODE IS DYNAMIC RECORD KEY IS VideoCode ALTERNATE RECORD KEY IS VideoTitle WITH DUPLICATES FILE STATUS IS VideoStatus.
DATA DIVISION.FILE SECTION.FD VideoFile.01 VideoRecord. 02 VideoCode PIC 9(5). 02 VideoTitle PIC X(40). 02 SupplierCode PIC 99.
WORKING-STORAGE SECTION.01 VideoStatus PIC X(2). 88 RecordFound VALUE "00".01 RequiredKey PIC 9. 88 VideoCodeKey VALUE 1. 88 VideoTitleKey VALUE 2.01 PrnVideoRecord. 02 PrnVideoCode PIC 9(5). 02 PrnVideoTitle PIC BBBBX(40). 02 PrnSupplierCode PIC BBBB99.
IDENTIFICATION DIVISION.PROGRAM-ID. ReadingIndexedFile.* Illustrates direct read on an indexed file by any key
ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL. SELECT VideoFile ASSIGN TO "VIDEO.DAT" ORGANIZATION IS INDEXED ACCESS MODE IS DYNAMIC RECORD KEY IS VideoCode ALTERNATE RECORD KEY IS VideoTitle WITH DUPLICATES FILE STATUS IS VideoStatus.
DATA DIVISION.FILE SECTION.FD VideoFile.01 VideoRecord. 02 VideoCode PIC 9(5). 02 VideoTitle PIC X(40). 02 SupplierCode PIC 99.
WORKING-STORAGE SECTION.01 VideoStatus PIC X(2). 88 RecordFound VALUE "00".01 RequiredKey PIC 9. 88 VideoCodeKey VALUE 1. 88 VideoTitleKey VALUE 2.01 PrnVideoRecord. 02 PrnVideoCode PIC 9(5). 02 PrnVideoTitle PIC BBBBX(40). 02 PrnSupplierCode PIC BBBB99.
Reading an Indexed File - Directly.Reading an Indexed File - Directly.
PROCEDURE DIVISION.Begin. OPEN INPUT VideoFile. DISPLAY "Chose key VideoCode = 1, VideoTitle = 2 -> " WITH NO ADVANCING. ACCEPT RequiredKey. IF VideoCodeKey DISPLAY "Enter Video Code (5 digits) -> " WITH NO ADVANCING ACCEPT VideoCode READ VideoFile KEY IS VideoCode INVALID KEY DISPLAY "VIDEO STATUS :- ", VideoStatus END-READ END-IF IF VideoTitleKey DISPLAY "Enter Video Title (40 chars) -> " WITH NO ADVANCING ACCEPT VideoTitle READ VideoFile KEY IS VideoTitle INVALID KEY DISPLAY "VIDEO STATUS :- ", VideoStatus END-READ END-IF IF RecordFound MOVE VideoCode TO PrnVideoCode MOVE VideoTitle TO PrnVideoTitle MOVE SupplierCode TO PrnSupplierCode DISPLAY PrnVideoRecord END-IF. CLOSE VideoFile. STOP RUN.
PROCEDURE DIVISION.Begin. OPEN INPUT VideoFile. DISPLAY "Chose key VideoCode = 1, VideoTitle = 2 -> " WITH NO ADVANCING. ACCEPT RequiredKey. IF VideoCodeKey DISPLAY "Enter Video Code (5 digits) -> " WITH NO ADVANCING ACCEPT VideoCode READ VideoFile KEY IS VideoCode INVALID KEY DISPLAY "VIDEO STATUS :- ", VideoStatus END-READ END-IF IF VideoTitleKey DISPLAY "Enter Video Title (40 chars) -> " WITH NO ADVANCING ACCEPT VideoTitle READ VideoFile KEY IS VideoTitle INVALID KEY DISPLAY "VIDEO STATUS :- ", VideoStatus END-READ END-IF IF RecordFound MOVE VideoCode TO PrnVideoCode MOVE VideoTitle TO PrnVideoTitle MOVE SupplierCode TO PrnSupplierCode DISPLAY PrnVideoRecord END-IF. CLOSE VideoFile. STOP RUN.
Reading an Indexed File - Directly.Reading an Indexed File - Directly.
RUN OF INDEX-EG3.EXE USING VIDEOCODEChose key VideoCode = 1, VideoTitle = 2 -> 1Enter Video Code (5 digits) -> 0212102121 DIRTY DANCING 04
RUN OF INDEX-EG3.EXE USING VIDEOCODEChose key VideoCode = 1, VideoTitle = 2 -> 1Enter Video Code (5 digits) -> 0505105051 OVERBOARD 01
RUN OF INDEX-EG3.EXE USING VIDEOTITLEChose key VideoCode = 1, VideoTitle = 2 -> 2Enter Video Title (40 chars) -> OVERBOARD05051 OVERBOARD 01
RUN OF INDEX-EG3.EXE USING VIDEOTITLEChose key VideoCode = 1, VideoTitle = 2 -> 2Enter Video Title (40 chars) -> DIRTY DANCING02121 DIRTY DANCING 04
RUN OF INDEX-EG3.EXE USING NON EXISTANT VIDEOCODEChose key VideoCode = 1, VideoTitle = 2 -> 1Enter Video Code (5 digits) -> 44444VIDEO STATUS :- 23
RUN OF INDEX-EG3.EXE USING VIDEOCODEChose key VideoCode = 1, VideoTitle = 2 -> 1Enter Video Code (5 digits) -> 0212102121 DIRTY DANCING 04
RUN OF INDEX-EG3.EXE USING VIDEOCODEChose key VideoCode = 1, VideoTitle = 2 -> 1Enter Video Code (5 digits) -> 0505105051 OVERBOARD 01
RUN OF INDEX-EG3.EXE USING VIDEOTITLEChose key VideoCode = 1, VideoTitle = 2 -> 2Enter Video Title (40 chars) -> OVERBOARD05051 OVERBOARD 01
RUN OF INDEX-EG3.EXE USING VIDEOTITLEChose key VideoCode = 1, VideoTitle = 2 -> 2Enter Video Title (40 chars) -> DIRTY DANCING02121 DIRTY DANCING 04
RUN OF INDEX-EG3.EXE USING NON EXISTANT VIDEOCODEChose key VideoCode = 1, VideoTitle = 2 -> 1Enter Video Code (5 digits) -> 44444VIDEO STATUS :- 23
579
Select and Assign for Indexed Select and Assign for Indexed FilesFiles
Indexed Files - Primary Indexed Files - Primary KeyKey
30 60 9930 60 99
40 50 6040 50 6010 20 3010 20 30 70 80 9970 80 99
41 43 44 45 46 49
Index Buckets
Level 1Level 1
Level 0Level 0
Level 2Level 2
Data BucketsData Buckets
Indexed Files - Alternate Indexed Files - Alternate KeyKey
H R ZH R Z
L O RL O RC F HC F H T W ZT W Z
Mi Nf Ni Nt Oi Ot
Index Buckets
Level 1Level 1
Level 0Level 0
Level 2Level 2
Base BucketsBase Buckets
50 51 54 55 56 59 Ii Ef Bi Nt Jt At
Data BucketsData Buckets
Indexed Files - Alternate Indexed Files - Alternate KeyKey
H R ZH R Z
L O RL O RC F HC F H T W ZT W Z
Mi Nf Ni Nt Oi Ot
Index Buckets
Level 1Level 1
Level 0Level 0
Level 2Level 2
Base BucketsBase Buckets
50 51 54 55 56 59 Ii Ef Bi Nt Jt At
Data BucketsData Buckets
Ot45
Nf65
Mi71
583
FDs for Indexed FDs for Indexed FilesFiles
584
Indexed File Verbs - Indexed File Verbs - OPENOPEN
585
Indexed File Verbs - Indexed File Verbs - READREAD
586
Indexed File Verbs - Write and Indexed File Verbs - Write and RewriteRewrite
587
Indexed File Verbs - Indexed File Verbs - DELETEDELETE
588
Indexed File Verbs - STARTIndexed File Verbs - START
The CALL The CALL VerbVerb
590
CALL CALL SyntaxSyntax
CALL CALL Example.Example.
IDENTIFICATION DIVISION.IDENTIFICATION DIVISION.PROGRAM-ID DateValidate IS INITIAL.PROGRAM-ID DateValidate IS INITIAL.DATA DIVISION.DATA DIVISION.WORKING-STORAGE SECTION.WORKING-STORAGE SECTION. ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
LINKAGE SECTION.LINKAGE SECTION.01 DateParam PIC X(8).01 DateParam PIC X(8).01 DateResult PIC 9.01 DateResult PIC 9.
PROCEDURE DIVISION USING DateParam, DateResult.PROCEDURE DIVISION USING DateParam, DateResult.Begin. Begin. ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?? ? ? ? ? ? ? ? ? ? ? ? EXIT PROGRAM.EXIT PROGRAM.
??????.??????. ? ? ? ? ? ? ? ? ? ? ? ?? ? ? ? ? ? ? ? ? ? ? ?
CALL "DateValidate"CALL "DateValidate"USING BY CONTENT TempDateUSING BY CONTENT TempDateUSING BY REFERENCE DateCheckResult.USING BY REFERENCE DateCheckResult.
592
CALL CALL ParametersParameters
CALL "ProgramName" USING P1, P2, P3, P4.CALL "ProgramName" USING P1, P2, P3, P4.
PROCEDURE DIVISION USING P2, P4, P1, P3.PROCEDURE DIVISION USING P2, P4, P1, P3.
593
CALL CALL ParametersParameters
CALL "ProgramName" USING P1, P2, P3, P4.CALL "ProgramName" USING P1, P2, P3, P4.
PROCEDURE DIVISION USING P2, P4, P1, P3.PROCEDURE DIVISION USING P2, P4, P1, P3.
Positions Correspond - Not NamesPositions Correspond - Not Names
Parameter Passing MechanismsParameter Passing Mechanisms
CALL .. BYCALL .. BYREFERENCEREFERENCE
CALLedCALLedProgramProgram
Parameter Passing Parameter Passing MechanismsMechanisms
CALL .. BYCALL .. BYREFERENCEREFERENCE
CALLedCALLedProgramProgram
Address of Address of
Data ItemData Item
DirectionDirectionof Data Flowof Data Flow
Parameter Passing Parameter Passing MechanismsMechanisms
CALL .. BYCALL .. BYREFERENCEREFERENCE
CALLedCALLedProgramProgram
Address of Address of
Data ItemData Item
CALL .. BYCALL .. BYCONTENTCONTENT
CALLedCALLedProgramProgram
Copy ofCopy ofData ItemData Item
DirectionDirectionof Data Flowof Data Flow
Parameter Passing Parameter Passing MechanismsMechanisms
CALL .. BYCALL .. BYREFERENCEREFERENCE
CALLedCALLedProgramProgram
Address of Address of
Data ItemData Item
CALL .. BYCALL .. BYCONTENTCONTENT
CALLedCALLedProgramProgram
Copy ofCopy ofData ItemData Item
Address of Address of CopyCopy
Data Data ItemItem
DirectionDirectionof Data Flowof Data Flow
DirectionDirectionof Data Flowof Data Flow
Avoiding “State Memory” - The IS INITIAL Avoiding “State Memory” - The IS INITIAL phrase.phrase.
$ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. Steadfast IS INITIALIS INITIAL.
DATA DIVISION.WORKING-STORAGE SECTION.01 RunningTotal PIC 9(7) VALUE 50.
LINKAGE SECTION.01 ParamValue PIC 99.
PROCEDURE DIVISION USING ParamValue.Begin. ADD ParamValue TO RunningTotal. DISPLAY "Total = ", RunningTotal. EXIT PROGRAM.
$ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. Steadfast IS INITIALIS INITIAL.
DATA DIVISION.WORKING-STORAGE SECTION.01 RunningTotal PIC 9(7) VALUE 50.
LINKAGE SECTION.01 ParamValue PIC 99.
PROCEDURE DIVISION USING ParamValue.Begin. ADD ParamValue TO RunningTotal. DISPLAY "Total = ", RunningTotal. EXIT PROGRAM.
12
Total = 62
5
Total = 55
12
Total = 62
Avoiding “State Memory” - The IS INITIAL phrase.Avoiding “State Memory” - The IS INITIAL phrase.
$ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. Fickle.
DATA DIVISION.WORKING-STORAGE SECTION.01 RunningTotal PIC 9(7) VALUE 50.
LINKAGE SECTION.01 ParamValue PIC 99.
PROCEDURE DIVISION USING ParamValue.Begin. ADD ParamValue TO RunningTotal. DISPLAY "Total = ", RunningTotal. EXIT PROGRAM.
$ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. Fickle.
DATA DIVISION.WORKING-STORAGE SECTION.01 RunningTotal PIC 9(7) VALUE 50.
LINKAGE SECTION.01 ParamValue PIC 99.
PROCEDURE DIVISION USING ParamValue.Begin. ADD ParamValue TO RunningTotal. DISPLAY "Total = ", RunningTotal. EXIT PROGRAM.
12
Total = 62
5
Total = 67
12
Total = 79
The CANCEL The CANCEL command.command.
$ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. Fickle.
DATA DIVISION.WORKING-STORAGE SECTION.01 RunningTotal PIC 9(7) VALUE 50.
LINKAGE SECTION.01 ParamValue PIC 99.
PROCEDURE DIVISION USING ParamValue.Begin. ADD ParamValue TO RunningTotal. DISPLAY "Total = ", RunningTotal. EXIT PROGRAM.
$ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. Fickle.
DATA DIVISION.WORKING-STORAGE SECTION.01 RunningTotal PIC 9(7) VALUE 50.
LINKAGE SECTION.01 ParamValue PIC 99.
PROCEDURE DIVISION USING ParamValue.Begin. ADD ParamValue TO RunningTotal. DISPLAY "Total = ", RunningTotal. EXIT PROGRAM.
12
Total = 62
12
Total = 62
CALL "Fickle" USING BY CONTENT IncValue.CALL "Fickle" USING BY CONTENT IncValue.CANCELCANCEL "Fickle" "Fickle"CALL "Fickle" USING BY CONTENT IncValue.CALL "Fickle" USING BY CONTENT IncValue.
Contained Sub-Contained Sub-ProgramsPrograms
$ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. MainProgram. ? ? ? ? ? ? ? ? ?01 TableItem IS GLOBALIS GLOBAL.
PROCEDURE DIVISION. ? ? ? ? ? ? ? ? ? CALL PutToTable USING BY CONTENT DataItem ? ? ? ? ? ? ? ? ? CALL ReportFromTable. EXIT PROGRAM.
IDENTIFICATION DIVISION.PROGRAM-ID. PutToTable. ? ? ? ? ? ? ? ? ?END-PROGRAM PutToTable.
IDENTIFICATION DIVISION.PROGRAM-ID. ReportFromTable. ? ? ? ? ? ? ? ? ?END-PROGRAM ReportFromTable.END-PROGRAM MainProgram.
$ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. MainProgram. ? ? ? ? ? ? ? ? ?01 TableItem IS GLOBALIS GLOBAL.
PROCEDURE DIVISION. ? ? ? ? ? ? ? ? ? CALL PutToTable USING BY CONTENT DataItem ? ? ? ? ? ? ? ? ? CALL ReportFromTable. EXIT PROGRAM.
IDENTIFICATION DIVISION.PROGRAM-ID. PutToTable. ? ? ? ? ? ? ? ? ?END-PROGRAM PutToTable.
IDENTIFICATION DIVISION.PROGRAM-ID. ReportFromTable. ? ? ? ? ? ? ? ? ?END-PROGRAM ReportFromTable.END-PROGRAM MainProgram.
Contained Sub-Contained Sub-ProgramsPrograms
$ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. MainProgram. ? ? ? ? ? ? ? ? ?01 TableItem IS GLOBALIS GLOBAL.
PROCEDURE DIVISION. ? ? ? ? ? ? ? ? ? CALL PutToTable USING BY CONTENT DataItem ? ? ? ? ? ? ? ? ? CALL ReportFromTable. EXIT PROGRAM.
IDENTIFICATION DIVISION.PROGRAM-ID. PutToTable. ? ? ? ? ? ? ? ? ?END-PROGRAM PutToTable.
IDENTIFICATION DIVISION.PROGRAM-ID. ReportFromTable. ? ? ? ? ? ? ? ? ?END-PROGRAM ReportFromTable.END-PROGRAM MainProgram.
$ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. MainProgram. ? ? ? ? ? ? ? ? ?01 TableItem IS GLOBALIS GLOBAL.
PROCEDURE DIVISION. ? ? ? ? ? ? ? ? ? CALL PutToTable USING BY CONTENT DataItem ? ? ? ? ? ? ? ? ? CALL ReportFromTable. EXIT PROGRAM.
IDENTIFICATION DIVISION.PROGRAM-ID. PutToTable. ? ? ? ? ? ? ? ? ?END-PROGRAM PutToTable.
IDENTIFICATION DIVISION.PROGRAM-ID. ReportFromTable. ? ? ? ? ? ? ? ? ?END-PROGRAM ReportFromTable.END-PROGRAM MainProgram.
$ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. MainProgram. ? ? ? ? ? ? ? ? ?01 TableItem IS GLOBALIS GLOBAL.
PROCEDURE DIVISION. ? ? ? ? ? ? ? ? ? CALL PutToTable USING BY CONTENT DataItem ? ? ? ? ? ? ? ? ? CALL ReportFromTable. EXIT PROGRAM.
IDENTIFICATION DIVISION.PROGRAM-ID. PutToTable. ? ? ? ? ? ? ? ? ?END-PROGRAM PutToTable.
IDENTIFICATION DIVISION.PROGRAM-ID. ReportFromTable. ? ? ? ? ? ? ? ? ?END-PROGRAM ReportFromTable.END-PROGRAM MainProgram.
$ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. MainProgram. ? ? ? ? ? ? ? ? ?01 TableItem IS GLOBALIS GLOBAL.
PROCEDURE DIVISION. ? ? ? ? ? ? ? ? ? CALL PutToTable USING BY CONTENT DataItem ? ? ? ? ? ? ? ? ? CALL ReportFromTable. EXIT PROGRAM.
IDENTIFICATION DIVISION.PROGRAM-ID. PutToTable. ? ? ? ? ? ? ? ? ?END-PROGRAM PutToTable.
IDENTIFICATION DIVISION.PROGRAM-ID. ReportFromTable. ? ? ? ? ? ? ? ? ?END-PROGRAM ReportFromTable.END-PROGRAM MainProgram.
Contained Sub-Contained Sub-ProgramsPrograms
The COMMON PROGRAM PhraseThe COMMON PROGRAM Phrase
$ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. MainProgram. ? ? ? ? ? ? ? ? ?01 TableItem IS GLOBALIS GLOBAL.PROCEDURE DIVISION. ? ? ? ? ? ? ? ? ? EXIT PROGRAM.
IDENTIFICATION DIVISION.PROGRAM-ID. PutToTable. ? ? ? ? ? ? ? ? ? CALL ReportFromTable. ? ? ? ? ? ? ? ? ? END-PROGRAM PutToTable.
IDENTIFICATION DIVISION.PROGRAM-ID. ReportFromTable IS COMMON PROGRAM. ? ? ? ? ? ? ? ? ? CALL PutToTable USING ???? ? ? ? ? ? ? ? ? ? END-PROGRAM ReportFromTable.END-PROGRAM MainProgram.
$ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. MainProgram. ? ? ? ? ? ? ? ? ?01 TableItem IS GLOBALIS GLOBAL.PROCEDURE DIVISION. ? ? ? ? ? ? ? ? ? EXIT PROGRAM.
IDENTIFICATION DIVISION.PROGRAM-ID. PutToTable. ? ? ? ? ? ? ? ? ? CALL ReportFromTable. ? ? ? ? ? ? ? ? ? END-PROGRAM PutToTable.
IDENTIFICATION DIVISION.PROGRAM-ID. ReportFromTable IS COMMON PROGRAM. ? ? ? ? ? ? ? ? ? CALL PutToTable USING ???? ? ? ? ? ? ? ? ? ? END-PROGRAM ReportFromTable.END-PROGRAM MainProgram.
The COMMON PROGRAM The COMMON PROGRAM PhrasePhrase
$ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. MainProgram. ? ? ? ? ? ? ? ? ?01 TableItem IS GLOBALIS GLOBAL.PROCEDURE DIVISION. ? ? ? ? ? ? ? ? ? EXIT PROGRAM.
IDENTIFICATION DIVISION.PROGRAM-ID. PutToTable. ? ? ? ? ? ? ? ? ? CALL ReportFromTable. ? ? ? ? ? ? ? ? ? END-PROGRAM PutToTable.
IDENTIFICATION DIVISION.PROGRAM-ID. ReportFromTable IS COMMON PROGRAM. ? ? ? ? ? ? ? ? ? CALL PutToTable USING ???? ? ? ? ? ? ? ? ? ? END-PROGRAM ReportFromTable.END-PROGRAM MainProgram.
$ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. MainProgram. ? ? ? ? ? ? ? ? ?01 TableItem IS GLOBALIS GLOBAL.PROCEDURE DIVISION. ? ? ? ? ? ? ? ? ? EXIT PROGRAM.
IDENTIFICATION DIVISION.PROGRAM-ID. PutToTable. ? ? ? ? ? ? ? ? ? CALL ReportFromTable. ? ? ? ? ? ? ? ? ? END-PROGRAM PutToTable.
IDENTIFICATION DIVISION.PROGRAM-ID. ReportFromTable IS COMMON PROGRAM. ? ? ? ? ? ? ? ? ? CALL PutToTable USING ???? ? ? ? ? ? ? ? ? ? END-PROGRAM ReportFromTable.END-PROGRAM MainProgram.
YESYES
The COMMON PROGRAM The COMMON PROGRAM PhrasePhrase
$ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. MainProgram. ? ? ? ? ? ? ? ? ?01 TableItem IS GLOBALIS GLOBAL.PROCEDURE DIVISION. ? ? ? ? ? ? ? ? ? EXIT PROGRAM.
IDENTIFICATION DIVISION.PROGRAM-ID. PutToTable. ? ? ? ? ? ? ? ? ? CALL ReportFromTable. ? ? ? ? ? ? ? ? ? END-PROGRAM PutToTable.
IDENTIFICATION DIVISION.PROGRAM-ID. ReportFromTable IS COMMON PROGRAM. ? ? ? ? ? ? ? ? ? CALL PutToTable USING ???? ? ? ? ? ? ? ? ? ? END-PROGRAM ReportFromTable.END-PROGRAM MainProgram.
$ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. MainProgram. ? ? ? ? ? ? ? ? ?01 TableItem IS GLOBALIS GLOBAL.PROCEDURE DIVISION. ? ? ? ? ? ? ? ? ? EXIT PROGRAM.
IDENTIFICATION DIVISION.PROGRAM-ID. PutToTable. ? ? ? ? ? ? ? ? ? CALL ReportFromTable. ? ? ? ? ? ? ? ? ? END-PROGRAM PutToTable.
IDENTIFICATION DIVISION.PROGRAM-ID. ReportFromTable IS COMMON PROGRAM. ? ? ? ? ? ? ? ? ? CALL PutToTable USING ???? ? ? ? ? ? ? ? ? ? END-PROGRAM ReportFromTable.END-PROGRAM MainProgram.
YESYES
NONO
Creating Abstract Data Creating Abstract Data Types?Types?
$ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. Stack.DATA DIVISION.WORKING-STORAGE SECTION.01 StackHolder IS GLOBAL. 02 StackItem OCCURS 20 TIMES PIC X(10).PROCEDURE DIVISION USING ????.Begin. EVALUATE TRUE WHEN PushStack CALL "Push" USING ??? WHEN PopStack CALL "Pop" USING ??? END-EVALUATE. EXIT PROGRAM.
IDENTIFICATION DIVISION.PROGRAM-ID. Push. ? ? ? ? ? ? ? ? ?END-PROGRAM Push.
IDENTIFICATION DIVISION.PROGRAM-ID. Pop. ? ? ? ? ? ? ? ? ?END-PROGRAM Pop.END-PROGRAM Stack.
$ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. Stack.DATA DIVISION.WORKING-STORAGE SECTION.01 StackHolder IS GLOBAL. 02 StackItem OCCURS 20 TIMES PIC X(10).PROCEDURE DIVISION USING ????.Begin. EVALUATE TRUE WHEN PushStack CALL "Push" USING ??? WHEN PopStack CALL "Pop" USING ??? END-EVALUATE. EXIT PROGRAM.
IDENTIFICATION DIVISION.PROGRAM-ID. Push. ? ? ? ? ? ? ? ? ?END-PROGRAM Push.
IDENTIFICATION DIVISION.PROGRAM-ID. Pop. ? ? ? ? ? ? ? ? ?END-PROGRAM Pop.END-PROGRAM Stack.
StackStack
PushPush
PopPop
MainMain
Creating Abstract Data Creating Abstract Data Types?Types?
$ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. Stack.DATA DIVISION.WORKING-STORAGE SECTION.01 StackHolder IS GLOBAL. 02 StackItem OCCURS 20 TIMES PIC X(10).PROCEDURE DIVISION USING ????.Begin. EVALUATE TRUE WHEN PushStack CALL "Push" USING ??? WHEN PopStack CALL "Pop" USING ??? END-EVALUATE. EXIT PROGRAM.
IDENTIFICATION DIVISION.PROGRAM-ID. Push. ? ? ? ? ? ? ? ? ?END-PROGRAM Push.
IDENTIFICATION DIVISION.PROGRAM-ID. Pop. ? ? ? ? ? ? ? ? ?END-PROGRAM Pop.END-PROGRAM Stack.
$ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. Stack.DATA DIVISION.WORKING-STORAGE SECTION.01 StackHolder IS GLOBAL. 02 StackItem OCCURS 20 TIMES PIC X(10).PROCEDURE DIVISION USING ????.Begin. EVALUATE TRUE WHEN PushStack CALL "Push" USING ??? WHEN PopStack CALL "Pop" USING ??? END-EVALUATE. EXIT PROGRAM.
IDENTIFICATION DIVISION.PROGRAM-ID. Push. ? ? ? ? ? ? ? ? ?END-PROGRAM Push.
IDENTIFICATION DIVISION.PROGRAM-ID. Pop. ? ? ? ? ? ? ? ? ?END-PROGRAM Pop.END-PROGRAM Stack.
StackStack
PushPush
PopPop
MainMain
Creating Abstract Data Creating Abstract Data Types?Types?
$ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. Stack.DATA DIVISION.WORKING-STORAGE SECTION.01 StackHolder IS GLOBAL. 02 StackItem OCCURS 20 TIMES PIC X(10).PROCEDURE DIVISION USING ????.Begin. EVALUATE TRUE WHEN PushStack CALL "Push" USING ??? WHEN PopStack CALL "Pop" USING ??? END-EVALUATE. EXIT PROGRAM.
IDENTIFICATION DIVISION.PROGRAM-ID. Push. ? ? ? ? ? ? ? ? ?END-PROGRAM Push.
IDENTIFICATION DIVISION.PROGRAM-ID. Pop. ? ? ? ? ? ? ? ? ?END-PROGRAM Pop.END-PROGRAM Stack.
$ SET SOURCEFORMAT"FREE"IDENTIFICATION DIVISION.PROGRAM-ID. Stack.DATA DIVISION.WORKING-STORAGE SECTION.01 StackHolder IS GLOBAL. 02 StackItem OCCURS 20 TIMES PIC X(10).PROCEDURE DIVISION USING ????.Begin. EVALUATE TRUE WHEN PushStack CALL "Push" USING ??? WHEN PopStack CALL "Pop" USING ??? END-EVALUATE. EXIT PROGRAM.
IDENTIFICATION DIVISION.PROGRAM-ID. Push. ? ? ? ? ? ? ? ? ?END-PROGRAM Push.
IDENTIFICATION DIVISION.PROGRAM-ID. Pop. ? ? ? ? ? ? ? ? ?END-PROGRAM Pop.END-PROGRAM Stack.
StackStack
PushPush
PopPop
MainMain
610
The IS EXTERNAL The IS EXTERNAL phrase.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 The IS EXTERNAL phrase.phrase.
WORKING-STORAGE SECTION.01 SharedRec IS EXTERNAL. 02 PartA PIC X(4). 02 PartB PIC 9(5).
ProgramAProgramA
01 SharedRec etc01 SharedRec etc
ProgramDProgramDProgramCProgramC01 SharedRec etc01 SharedRec etc
ProgramBProgramB
SharedRecSharedRec
Mike12345Mike12345
The IS EXTERNAL The IS EXTERNAL phrase.phrase.
WORKING-STORAGE SECTION.01 SharedRec IS EXTERNAL. 02 PartA PIC X(4). 02 PartB PIC 9(5).
ProgramAProgramA
01 SharedRec etc01 SharedRec etc
ProgramDProgramDProgramCProgramC01 SharedRec etc01 SharedRec etc
ProgramBProgramB
SharedRecSharedRecPUTPUT
Mike12345Mike12345
Mike12345Mike12345
The IS EXTERNAL The IS EXTERNAL phrase.phrase.
WORKING-STORAGE SECTION.01 SharedRec IS EXTERNAL. 02 PartA PIC X(4). 02 PartB PIC 9(5).
ProgramAProgramA
01 SharedRec etc01 SharedRec etc
ProgramDProgramDProgramCProgramC01 SharedRec etc01 SharedRec etc
ProgramBProgramB
SharedRecSharedRecPUTPUT GETGET
Mike12345Mike12345
Mike12345Mike12345
Mike12345Mike12345
COPY COPY VerbVerb
615
The COPY VerbThe 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.
616
The COPY verb2The 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.
617
Why use the COPY verb?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.
618
COPY formatCOPY format
COPY TextName
ExternalFileNameLiteral
OF
IN
LibraryName
LibraryNameLiteral
REPLACING
== PseudoText1 ==
Identifier1
Literal1
Word1
BY
== PseudoText2 ==
Identifier2
Literal2
Word2
Example COPY statements.
COPY "CopyFile2.CBL" REPLACING XYZ BY 120.
COPY Copyfile3 IN "EXLIB".
COPY "CopyFile3.CBL" IN "EXLIB".TextName
ExternalFileNameLiteral
ExternalFileNameLiteral
LibraryNameLiteral
LibraryNameLiteral
619
How the COPY worksHow the COPY works
If the REPLACING phrase is not used then the compiler simply copies the text into the client program without change.
If the COPY does use the REPLACING phrase then the text is copied and each properly matched occurrence of Pseudo-Text-1, Identifier-1, Literal-1 and Word-1 in the library text is replaced by the corresponding Pseudo-Text-2, Identifier-2, Literal-2 or Word-2 in the REPLACING phrase.
Pseudo-Text is any COBOL text encloded in double equal signs (e.g. ==ADD 1==).
It allows us to replace a series of words or characters as opposed to an individual identifier, literal or word.
620
How the REPLACING worksHow 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 aseparator commasemicolonspace
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.
621
Text-WordsText-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 SpaceA Pseudo-Text delimiterA Comma
Opening and closing parentheses Any other sequence of contiguous characters, bounded by separators.
622
Text-Word ExamplesText-Word Examples
MOVE1 Text Word
MOVE Total TO Print-Total4 Text Words - MOVE Total TO Print-Total
MOVE Total TO Print-Total.5 Text Words - MOVE Total TO Print-Total .
PIC S9(4)V9(6)9 Text words - PIC S9 ( 4 ) V9 ( 6 )
“PIC S9(4)V9(6)”1 Text word - “PIC S9(4)V9(6)”
623
IDENTIFICATION DIVISION. PROGRAM-ID. COPYEG1. AUTHOR. Michael Coughlan. ENVIRONMENT DIVISION. FILE-CONTROL. SELECT StudentFile ASSIGN TO "STUDENTS.DAT" ORGANIZATION IS LINE SEQUENTIAL. DATA DIVISION. FILE SECTION. FD StudentFile. COPY COPYFILE1. PROCEDURE DIVISION. BeginProg. OPEN INPUT StudentFile READ StudentFile AT END SET EndOfSF TO TRUE END-READ PERFORM UNTIL EndOfSF DISPLAY StudentNumber SPACE StudentName SPACE CourseCode SPACE FeesOwed SPACE AmountPaid READ StudentFile AT END SET EndOfSF TO TRUE END-READ END-PERFORM STOP RUN.
IDENTIFICATION DIVISION. PROGRAM-ID. COPYEG1. AUTHOR. Michael Coughlan. ENVIRONMENT DIVISION. FILE-CONTROL. SELECT StudentFile ASSIGN TO "STUDENTS.DAT" ORGANIZATION IS LINE SEQUENTIAL. DATA DIVISION. FILE SECTION. FD StudentFile. COPY COPYFILE1. PROCEDURE DIVISION. BeginProg. OPEN INPUT StudentFile READ StudentFile AT END SET EndOfSF TO TRUE END-READ PERFORM UNTIL EndOfSF DISPLAY StudentNumber SPACE StudentName SPACE CourseCode SPACE FeesOwed SPACE AmountPaid READ StudentFile AT END SET EndOfSF TO TRUE END-READ END-PERFORM STOP RUN.
01 StudentRec. 88 EndOfSF VALUE HIGH-VALUES. 02 StudentNumber PIC 9(7). 02 StudentName PIC X(60). 02 CourseCode PIC X(4). 02 FeesOwed PIC 9(4).
02 AmountPaid PIC 9(4)V99.
01 StudentRec. 88 EndOfSF VALUE HIGH-VALUES. 02 StudentNumber PIC 9(7). 02 StudentName PIC X(60). 02 CourseCode PIC X(4). 02 FeesOwed PIC 9(4).
02 AmountPaid PIC 9(4)V99.
COPY Example 1COPY Example 1
624
COPY Example 2COPY Example 2
02 StudName PIC X(20) OCCURS XYZ TIMES02 StudName PIC X(20) OCCURS XYZ TIMES. 02 StudName PIC X(20) OCCURS XYZ TIMES02 StudName PIC X(20) OCCURS XYZ TIMES.
Copyfile2.cbl
01 NameTable2.01 NameTable2.COPY "CopyFile2.CBL" REPLACING XYZ BY COPY "CopyFile2.CBL" REPLACING XYZ BY 120120..
01 NameTable2. 02 StudName PIC X(20) OCCURS 120 TIMES.
625
COPY Example 3COPY Example 3
02 CustOrder PIC 9(R).02 CustOrder PIC 9(R). 02 CustOrder PIC 9(R).02 CustOrder PIC 9(R).
Copyfile3.cbl
01 CopyData. 01 CopyData. COPY Copyfile3 REPLACING ==COPY Copyfile3 REPLACING ==RR== BY ==== BY ==44==.==.
01 CopyData. 02 CustOrder PIC 9(4).
626
COPY Example 4COPY Example 4
02 CustOrder2 PIC 9(6)V99.02 CustOrder2 PIC 9(6)V99. 02 CustOrder2 PIC 9(6)V99.02 CustOrder2 PIC 9(6)V99.
Copyfile4.cbl
01 CopyData. 01 CopyData. COPY CopyFile4 REPLACING ==COPY CopyFile4 REPLACING ==V99V99== BY ====. == BY ====.
01 CopyData. 02 CustOrder2 PIC 9(6).
627
COPY Example 5COPY Example 5
02 CustKey PIC X(3) VALUE "KEY".02 CustKey PIC X(3) VALUE "KEY".02 CustKey PIC X(3) VALUE "KEY".02 CustKey PIC X(3) VALUE "KEY".
Copyfile5.cbl
01 CopyData. 01 CopyData. COPY CopyFile5 REPLACING COPY CopyFile5 REPLACING "KEY""KEY" BY BY "ABC""ABC"..
01 CopyData. 02 CustKey PIC X(3) VALUE "ABC".
628
COPY Example 6COPY Example 6
02 CustKey PIC X(3) VALUE "KEY".02 CustKey PIC X(3) VALUE "KEY".02 CustKey PIC X(3) VALUE "KEY".02 CustKey PIC X(3) VALUE "KEY".
Copyfile5.cbl
01 CopyData. 01 CopyData. COPY CopyFile5 REPLACING COPY CopyFile5 REPLACING "CustKey""CustKey" BY BY "Cust""Cust"..
01 CopyData. 02 CustKey PIC X(3) VALUE "KEY". No Replacement
629
COPY Example 7COPY Example 7
02 CustKey PIC X(3) VALUE "KEY".02 CustKey PIC X(3) VALUE "KEY".02 CustKey PIC X(3) VALUE "KEY".02 CustKey PIC X(3) VALUE "KEY".
Copyfile5.cbl
01 CopyData. 01 CopyData. COPY CopyFile5 REPLACING COPY CopyFile5 REPLACING "KEY""KEY" BY == BY =="ABC"."ABC". 02 CustNum PIC 9(8)02 CustNum PIC 9(8)==. ==.
01 CopyData. 02 CustKey PIC X(3) VALUE "ABC". 02 CustNum PIC 9(8).
630
COPY Example 8COPY Example 8
02 CustKey PIC X(3) VALUE "KEY".02 CustKey PIC X(3) VALUE "KEY".02 CustKey PIC X(3) VALUE "KEY".02 CustKey PIC X(3) VALUE "KEY".
Copyfile5.cbl
* the ( is a textword replaced by @* the ( is a textword replaced by @
COPY copyfile5 REPLACING COPY copyfile5 REPLACING (( BY BY @@..
* the 3 between ( and ) is a textword replaced by the textword "three"* the 3 between ( and ) is a textword replaced by the textword "three"
COPY copyfile5 REPLACING COPY copyfile5 REPLACING 33 BY BY threethree..
* the ) is a textword replaced by &* the ) is a textword replaced by &
COPY copyfile5 REPLACING COPY copyfile5 REPLACING )) BY BY &&..
02 CustKey PIC X@3) VALUE "KEY".02 CustKey PIC X(three) VALUE "KEY".02 CustKey PIC X(3& VALUE "KEY".
631
COPY Example 9COPY Example 9
02 CustKey PIC X(3) VALUE "KEY".02 CustKey PIC X(3) VALUE "KEY".02 CustKey PIC X(3) VALUE "KEY".02 CustKey PIC X(3) VALUE "KEY".
Copyfile5.cbl
* the X before (3) is a textword replaced by pseudotext "Replace the X"* the X before (3) is a textword replaced by pseudotext "Replace the X"
COPY copyfile5 REPLACING COPY copyfile5 REPLACING XX BY == BY ==Replace the XReplace the X==.==.
* the pseudotext X(3) is replaced by X(19)* the pseudotext X(3) is replaced by X(19)
COPY copyfile5 REPLACING ==COPY copyfile5 REPLACING ==X(3)X(3)== == BY == BY ==X(19)X(19)==.==.
* the series of textwords X ( 3 ) is replaced by the series X ( 19 ) * the series of textwords X ( 3 ) is replaced by the series X ( 19 )
COPY copyfile5 REPLACING COPY copyfile5 REPLACING X(3)X(3) BY BY X(19)X(19)..
02 CustKey PIC Replace the X(3) VALUE KEY".02 CustKey PIC X(19) VALUE "KEY".02 CustKey PIC X(19) VALUE "KEY".
632
COPY Example 10COPY Example 10
02 CustKey PIC X(3) VALUE "KEY".02 CustKey PIC X(3) VALUE "KEY".02 CustKey PIC X(3) VALUE "KEY".02 CustKey PIC X(3) VALUE "KEY".
Copyfile5.cbl
* the textword PIC is replaced by the pseudotext Pic is Replaced* the textword PIC is replaced by the pseudotext Pic is Replaced
COPY copyfile5 REPLACING COPY copyfile5 REPLACING PICPIC BY == BY ==Pic is ReplacedPic is Replaced==.==.
* The P in PIC is not a textword by itself and so is not replaced* The P in PIC is not a textword by itself and so is not replaced
COPY copyfile5 REPLACING COPY copyfile5 REPLACING PP BY BY == ==But P in PIC not replacedBut P in PIC not replaced==.==.
02 CustKey Pic is Replaced X(3) VALUE "KEY". 02 CustKey PIC X(3) VALUE "KEY". No Replacement
DebugDebugging ging
PROCO PROCO MenusMenus
PROCO 1 - MenuF1=help F2=edit F3=check F4=animate F5=compile F6=run F7=library F8=build
F10=directory
PROCO 1 - MenuF1=help F2=edit F3=check F4=animate F5=compile F6=run F7=library F8=build
F10=directory
PROCO 2 - Alt MenuF1=help F2=screens F7=link F10=CoWriter
PROCO 3 - Ctrl MenuF1=help F3=update-menu F4=UseUpdatedMenu F5=batch-files F7=OS-command F8=config
F10=user-menu
PROCO 2 - Alt MenuF1=help F2=screens F7=link F10=CoWriter
PROCO 3 - Ctrl MenuF1=help F3=update-menu F4=UseUpdatedMenu F5=batch-files F7=OS-command F8=config
F10=user-menu
EDIT 1 -MenuF1=help F2=COBOL F3=InsertLine
F4=DeleteLine F5=RepeatLine F6=RestoreLine F7=RetypeChar F8=RestoreChar
F9=WordLeft F10=WordRight
EDIT 1 -MenuF1=help F2=COBOL F3=InsertLine
F4=DeleteLine F5=RepeatLine F6=RestoreLine F7=RetypeChar F8=RestoreChar
F9=WordLeft F10=WordRight
EDIT 2 - Alt MenuF1=help F2=library F3=load-file F4=save-
file F5=split-line F6=join-line F7=print F8=calculate F9=untype-word-left
F10=DeleteWord
EDIT 3 - Ctrl MenuF1=help F2=find F3=block F4=clear F5=margins F6=draw/forms F7=tags
F8=WordWrap F9=window F10=scroll <-/-> (move in window) Home/End (of text) PgUp/PgDn
EDIT 2 - Alt MenuF1=help F2=library F3=load-file F4=save-
file F5=split-line F6=join-line F7=print F8=calculate F9=untype-word-left
F10=DeleteWord
EDIT 3 - Ctrl MenuF1=help F2=find F3=block F4=clear F5=margins F6=draw/forms F7=tags
F8=WordWrap F9=window F10=scroll <-/-> (move in window) Home/End (of text) PgUp/PgDn
COBOL menuF1=help F2=check/animate F3=cmd-file
F7=locate-previous F8=locate-next F9=locate-current
COBOL menuF1=help F2=check/animate F3=cmd-file
F7=locate-previous F8=locate-next F9=locate-current
Checker MenuF1=help F2=check/anim F3=pause
F4=list F6=lang F7=ref F9/F10=directives
Checker MenuF1=help F2=check/anim F3=pause
F4=list F6=lang F7=ref F9/F10=directives
Animate-MenuF1=help F2=view F3=align F4=exchange F5=where F6=look-up F9/F10=word-</>
Escape Animate Step Wch Go Zoom nx-If Prfm Rst Brk Env Qury Find Locate Txt Do
Animate-MenuF1=help F2=view F3=align F4=exchange F5=where F6=look-up F9/F10=word-</>
Escape Animate Step Wch Go Zoom nx-If Prfm Rst Brk Env Qury Find Locate Txt Do
ALT key
CTRL key
ALT key
CTRL key
PROCO PROCO MenusMenus
Animate-MenuF1F1=help F2 F2=view F3F3=align F4F4=exchange F5F5=where F6 F6=look-up
F9/F10F9/F10=word-</> EscEscape AAnimate SStep WWch GGo ZZoom nx-IIf PPrfm RRst BBrk E Env QQury FFind L Locate TTxt
DDo