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

COBOL Programming

The document discusses a COBOL programming course. It covers the course objectives, what topics will be covered including the COBOL language divisions, data types, file descriptions, and data relationships. The DATA DIVISION of COBOL programs is described as defining the data processed, including file and program data with level indicators and level numbers denoting relationships.

Uploaded by

Aditi Bist
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
428 views

COBOL Programming

The document discusses a COBOL programming course. It covers the course objectives, what topics will be covered including the COBOL language divisions, data types, file descriptions, and data relationships. The DATA DIVISION of COBOL programs is described as defining the data processed, including file and program data with level indicators and level numbers denoting relationships.

Uploaded by

Aditi Bist
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 228

COBOL Programming

Interra IT 2
Nice to meet you!!!
Lets get to know each other
Objectives and expectations from the
course
What is covered in the course
Interra IT 3
What is covered
Identification and
Environment Divisions
The Data Division
Coding complete COBOL
programs: The Procedure
Division
Designing and debugging
batch COBOL programs
Moving data, printing
information and displaying
output
Computing In COBOL: The
arithmetic verbs and
intrinsic functions
Decision making: using
the IF and Evaluate
statements
Iteration: Beyond the
basic perform
Control break processing
Data validation
Array processing and table
handling
Sequential file processing
Sorting and merging
Indexed and relative file
processing (VSAM)
Do's and Don'ts (Coding
techniques)
Simple batch COBOL
program workshop

Interra IT 4
COBOL
1. An Introduction
Interra IT 5
A little bit of history
Developed in 1959 as standard
language to meet needs of business
Committee to develop language
convened by Department of Defense
Included representatives from
academia, business, computer
manufacturers

Interra IT 6
Future of COBOL
Likely to remain important language
Older COBOL programs need to be
updated
Still used by many for new program
development

Interra IT 7
Nature of COBOL
English like language
Easier than most (high level)
languages
Needs to be translated or compiled
into machine language in order to run
on the computer
Business-oriented language
Interra IT 8
Program Design
Two techniques used to develop
programs that are easier to
understand, test, debug and modify

Structured Programming

Top-Down Programming
Interra IT 9
Compiling a source

Source program in
symbolic language
Object program in
machine language
Translated
by compiler
Interra IT 10
Suites both types of programs
Interactive programs
Accept input data from keyboard
Input data processed immediately
Output (results) displayed on screen
immediately
Batch programs
Process large volumes of input at periodic
intervals
Input data read in from files
Output written to files

Interra IT 11
The FOUR divisions
Every COBOL program contains up to
four separate divisions in the
following order:
IDENTIFICATION DIVISION
ENVIRONMENT DIVISION
DATA DIVISION
PROCEDURE DIVISION
Interra IT 12
Hierarchy of COBOL divisions
The grammatical hierarchy follows this form:

Identification Division -> Paragraphs-> Entries -
>Clauses

Environment Division ->Sections->Paragraphs->
Entries->Clauses -> Phrases

Data Division ->Sections ->Entries ->Clauses-
>Phrases

Procedure Division-> Sections-> Paragraphs ->
Sentences-> Statements -> Phrases

Interra IT 13
COBOL DIVISIONS
2. IDENTIFICATION & ENVIRONMENT
DIVISIONS
Interra IT 14
Basic COBOL program
Originally, each COBOL instruction
coded on single line of 80 characters
Positions on line reserved for special
purposes
Rules may differ for your compiler
Rigid column rules dropped in 2002+
Interra IT 15
Coding rules
Columns 1-6 and 73-80 optional and
rarely used today
Column 7 for continuation, comment,
starting new page
Columns 8-72 for COBOL program
statements
Interra IT 16
Coding rules (contd.)
Column 7
* (asterisk) designates entire line as
comment
/ (slash) forces page break when
printing source listing
- (dash) to indicate continuation of
nonnumeric literal
Interra IT 17
Margin rules
Columns 8-72 divided into two areas
Area A - columns 8, 9, 10, 11
Area B - columns 12-72
Division, section and paragraph-
names must all begin in Area A
First letter of name must begin in column
8, 9, 10 or 11
Entry may extend into Area B
Interra IT 18
Margin rules (contd.)
All other statements, clauses, and
sentences begin anywhere in Area B
(column 12, 13, 14, etc.)
Select entries in ENVIRONMENT
DIVISION
Data description entries in DATA
DIVISION
All PROCEDURE DIVISION instructions
Interra IT 19
IDENTIFICATION DIVISION

Identifies program to operating system
Provides documentation about program
Interra IT 20
IDENTIFICATION DIVISION
Provides identifying information about
program
Divided into paragraphs
PROGRAM-ID only required paragraph
Other paragraphs optional

Interra IT 21
IDENTIFICATION DIVISION
Format
IDENTIFICATION DIVISION.
PROGRAM-ID. program-
name.
[AUTHOR. [comment-entry]
]
[other optional paragraphs]
Interra IT 22
Understanding Instruction Formats
Instruction formats describe syntax of
all parts of COBOL language
Describe required and optional
elements, ordering and punctuation
All formats in text are correct
although additional options may be
available
Interra IT 23
Rules for Instruction Formats
Uppercase words are COBOL reserved
words
Lowercase words are user-defined entries

IDENTIFICATION DIVISION.
PROGRAM-ID. program-name.

DIVISION is reserved word
program-name is user-defined data-name
Interra IT 24
Rules for Instruction Formats
Underlined words are required
Punctuation if specified is required

IDENTIFICATION DIVISION.
PROGRAM-ID. program-name.

IDENTIFICATION, DIVISION required
PROGRAM-ID is required paragraph
Periods required after division header,
paragraph name and program-name
Interra IT 25
Rules for Instruction Formats
Brackets [ ] mean item is optional, braces {
} mean one of enclosed items required
Ellipses (. . .) mean entry may be repeated


IDENTIFICATION DIVISION.
PROGRAM-ID. program-name.
[AUTHOR. [comment-entry] ]

AUTHOR paragraph optional
If included it may have any number of comment
entries
Interra IT 26
ENVIRONMENT DIVISION
Describes files and computer devices
used to process them, is optional
Required by programs that process
files
This division is machine-dependent
since devices differ from computer to
computer
Only division that may change if
program run on different computer
Interra IT 27
Sections of Environment Division
CONFIGURATION SECTION
Describes computer used to
compile/execute program
Optional and recommended that you
omit it
INPUT-OUTPUT SECTION
Describes input and output files and
devices used by program
Required for all programs using files
Interra IT 28
CONFIGURATION SECTION
SOURCE-COMPUTER paragraph
SPECIAL-NAMES paragraph


Interra IT 29
CONFIGURATION SECTION
ALPHABET clause:
ALPHABET alphabet-name-1 IS
Provides a means of relating an alphabet-
name to a specified character code set or
collating sequence.

Interra IT 30
CONFIGURATION SECTION
CURRENCY SIGN clause

CURRENCY SIGN IS literal-1
symbol in the PICTURE clause


Interra IT 31
INPUT-OUTPUT SECTION
Follows CONFIGURATION SECTION (if
coded)
Includes FILE-CONTROL paragraph
Contains one SELECT statement for each
file used by program
Each SELECT defines a file-name and
assigns device name to that file

Interra IT 32
INPUT-OUTPUT SECTION
Format
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT file-name-1
ASSIGN TO implementer-name-1
[ORGANIZATION IS SEQUENTIAL].

Interra IT 33
INPUT-OUTPUT SECTION
Other clauses.
ACCESS MODE
RECORD KEY
ALTERNATE RECORD KEY
FILE STATUS

Interra IT 34
COBOL 2002+ changes
Coding rules for Margins A and B will
be recommended not required.
PROGRAM-ID will be only paragraph
in IDENTIFICATION DIVISION. All
others can be specified as comments.
Length of user-defined words will be
increased from 30 to 60 characters.

Interra IT 35
Chapter Summary
IDENTIFICATION DIVISION
Defines program name
Program name up to eight characters, letters
and digits only, acceptable on all computers
PROGRAM-ID is only required paragraph, all
others optional
Use comments by coding an * in column 7

Interra IT 36
Chapter Summary
ENVIRONMENT DIVISION
INPUT-OUTPUT SECTION required for any
program using files
Only machine-dependent division since
device specification, file-name rules vary
among computers
Interra IT 37
COBOL DIVISIONS
3. DATA DIVISION
Interra IT 38
DATA DIVISION
The Data Division of a COBOL source
program describes, in a structured manner,
all the data to be processed by the object
program. The Data Division is optional in a
COBOL source program
This chapter outlines the structure of the
Data Division and explains the types of
data and how they are related in a COBOL
program.

Interra IT 39
DATA DIVISION
Data types
File data
Program data

Interra IT 40
DATA DIVISION
Data Relationships
A level indicator, with its descriptive entry, identifies each file
in a program. Level indicators represent the highest level of
any data hierarchy with which they are associated; FD is the
file description level indicator and SD is the sort-merge file
description level indicator.
A level-number, with its descriptive entry, indicates the
properties of specific data. Level-numbers can be used to
describe a data hierarchy; they can indicate that this data has
a special purpose, and while they can be associated with (and
subordinate to) level indicators, they can also be used
independently to describe internal data or data common to
two or more programs.

Interra IT 41
DATA DIVISION
File Description Entries - Format
FD file-name
RECORD CONTAINS integer-1 CHARACTERS
BLOCK CONTAINS integer-2 RECORDS
RECORDING MODE IS FIXED.
Interra IT 42
DATA DIVISION
File Description Entries - Format
FD file-name
RECORD CONTAINS integer-1 CHARACTERS
BLOCK CONTAINS integer-2 RECORDS
RECORDING MODE IS FIXED.

Interra IT 43
DATA DIVISION
Data Description Entries
A data description entry specifies the
characteristics of a data item.
Format:
level-number data-name-1 picture-clause
[VALUE] [USAGE].

Interra IT 44
DATA DIVISION
PICTURE clause example:

01 WS-DATA-ITEM-1 PIC A(12).
01 WS-DATA-ITEM-2 PIC S99999V99.
Interra IT 45
DATA DIVISION
USAGE clause example:
USAGE IS COMP-1.

Usage can be:
COMPUTATIONAL
DISPLAY
INDEX
POINTER

Interra IT 46
DATA DIVISION
Computational Items
BINARY - Specified for binary data items.
Such items have a decimal equivalent
consisting of the decimal digits 0 through 9,
plus a sign. Negative numbers are
represented as the two's complement of
the positive number with the same absolute
value.

Interra IT 47
DATA DIVISION
Computational Items
PACKED-DECIMAL - Specified for
internal decimal items. Appears in storage
in packed decimal format. There are 2
digits for each character position, except
for the trailing character position, which is
occupied by the low-order digit and the
sign. Such item can contain any of the
digits 0 through 9, plus a sign, representing
a value not exceeding 18 decimal digits.
Interra IT 48
DATA DIVISION
Computational Items
COMP - For the VS COBOL II compiler, the
COMPUTATIONAL phrase is synonymous
with BINARY.
COMP-1 - Specified for internal floating-
point items (single precision). COMP-1
items are 4 bytes long. The sign is
contained in the first bit of the leftmost byte
and the exponent is contained in the
remaining 7 bits. The last 3 bytes contain
the mantissa.
Interra IT 49
DATA DIVISION
Computational Items
COMP-2 - Specified for internal floating-
point items (double precision). COMP-2
items are 8 bytes long. The sign is
contained in the first bit of the leftmost byte
and the remaining 7 bits contain the
exponent. The remaining 7 bytes contain
the mantissa.

Interra IT 50
DATA DIVISION
Computational Items
COMP-3 (internal decimal) - For VS
COBOL II, this is the equivalent of
PACKED-DECIMAL.

Interra IT 51
DATA DIVISION
Computational Items
COMP-4 (binary) - For VS COBOL II this is
the equivalent of BINARY.
Interra IT 52
DATA DIVISION
Display Items
The data item is stored in character form, 1
character for each 8-bit byte. This
corresponds to the format used for printed
output. DISPLAY can be explicit or implicit.


Interra IT 53
DATA DIVISION
Index Item
An index data item is a 4-byte elementary
item (not necessarily connected with any
table) that can be used to save index-name
values for future reference. Through a SET
statement, an index data item can be
assigned an index-name value; such a
value corresponds to the occurrence
number in a table.

Interra IT 54
DATA DIVISION
Pointer item
A pointer data item is a 4-byte elementary
item that can be used to accomplish limited
base addressing. Pointer data items can be
compared for equality or moved to other
pointer items.

Interra IT 55
DATA DIVISION
VALUE clause example:
01 FILLER PIC 9(3) VALUE IS ALL
ZEROES.
Interra IT 56
DATA DIVISION
Types of constants
Numeric literal
Examples: .05 5280 199.99
Constant used for arithmetic operations
Nonnumeric (alphanumeric) literal
Examples: INVALID Enter your name
Constant used for all operations except
arithmetic
Figurative constant
SPACES ZEROS
Reserved word for commonly used values
Interra IT 57
DATA DIVISION
Rules for numeric literals
1. 1 to 18 digits.
2. + or - sign may be included to left of
first digit.
3. Decimal point permitted within
literal. May not follow last digit.

Valid numeric literals

23 +2359.4 .125 -68734
Interra IT 58
DATA DIVISION
Rules for non-numeric literals
Must be enclosed in quotation marks
From 1 to 160 characters, including
space
Any character in COBOL character set
except quotation mark

Valid Nonnumeric Literals

'123 Main St.' '$14.99'
'12,342' 'Enter a value from 1
to 10'
Interra IT 59
DATA DIVISION
Rules for non-numeric literals (contd.)
Only characters within quotes are
moved or displayed
May contain all numbers ('125') but
not same as numeric literal (125)
Cannot be used in arithmetic operations
Cannot be moved to field with PIC of 9s
Are not data-names
'Amount-In' not same as field defined in
DATA DIVISION called Amount-In
Interra IT 60
DATA DIVISION
Figurative constants
ZERO, ZEROS or ZEROES means all
zeros
Example: Move Zeros To Total-Out

Fills each position in Total-Out with a
zero
May be used with both numeric and
alphanumeric fields

Interra IT 61
DATA DIVISION
Program data is defined in two
sections within the DATA DIVISION
WORKING-STORAGE
LINKAGE
Interra IT 62
DATA DIVISION
WORKING-STORAGE SECTION
Follows FILE SECTION
Begins with heading on line by itself
Starts in Area A, ends with period
All items must be defined at 01 level
or in entries subordinate to 01 level
entry

Interra IT 63
DATA DIVISION
Uses of WORKING-STORAGE SECTION
To define fields used for
Keyed input and displayed output
Intermediate arithmetic results
Counters and totals
End-Of-File Indicators
Interra IT 64
DATA DIVISION
REDEFINES clause
The REDEFINES clause allows you to
use different data description entries
to describe the same computer
storage area.
01 e-date PIC X(6).
01 e-date-r REDEFINES e-date.
05 e-mm PIC 9(2).
05 e-dd PIC 9(2).
05 e-yy PIC 9(2).

Interra IT 65
COBOL DIVISIONS
4. PROCEDURE DIVISION: CODING
COMPLETE COBOL PROGRAMS
Interra IT 66
PROCEDURE DIVISION
Interactive processing instructions
Accept input from keyboard
Display output on screen
Batch processing instructions
Access files and read them
Write output to files

Interra IT 67
PPROCEDURE DIVISION
The PROCEDURE DIVISION begins with the
division header and a procedure-name
header. The division header for a program
can simply be:

PROCEDURE DIVISION.

Or, you can code your division header to
receive parameters with the USING
phrase or to return a value with the
RETURNING Phrase.

Interra IT 68
PROCEDURE DIVISION
To receive an argument that was passed
by reference (the default) or by
content, code the division header for
a program like this:

PROCEDURE DIVISION USING
dataname

Or this:

PROCEDURE DIVISION USING BY
REFERENCE dataname
Interra IT 69
PROCEDURE DIVISION
The PROCEDURE DIVISION of a
program is divided into:
Sections
Paragraphs
Sentences
Statements
Interra IT 70
PROCEDURE DIVISION
Arithmetic expressions
Arithmetic expressions are used as operands of certain conditional and
arithmetic statements.

An arithmetic expression can consist of any of the following:
1. An identifier described as a numeric elementary item (including
numeric functions)
2. A numeric literal
3. The figurative constant ZERO
4. Identifiers and literals, as defined in items 1, 2, and 3, separated by
arithmetic operators
5. Two arithmetic expressions, as defined in items 1, 2, 3, and/or 4,
separated by an arithmetic operator
6. An arithmetic expression, as defined in items 1, 2, 3, 4, and/or 5,
enclosed in parentheses.
Interra IT 71
PROCEDURE DIVISION
Conditional expressions
A conditional expression causes the
object program to select alternative
paths of control, depending on the
truth value of a test. Conditional
expressions are specified in
EVALUATE, IF, PERFORM, and
SEARCH statements.

Interra IT 72
PROCEDURE DIVISION
Procedure division statements
ACCEPT EXIT PROGRAM RETURN
ADD GOBACK REWRITE
ALTER GO TO SEARCH
CALL IF SET
CANCEL INITIALIZE SORT
CLOSE INSPECT STOP
COMPUTE INVOKE STRING
CONTINUE MERGE SUBTRACT
DELETE MOVE UNSTRING
DISPLAY MULTIPLY WRITE
DIVIDE OPEN
EVALUATE PERFORM
ENTRY READ
EXIT RELEASE

Interra IT 73
COBOL VERBS & COMMANDS
5. MOVING DATA PRINTING AND
DISPLAYING
Interra IT 74
MOVING DATA
Format-1:
MOVE IDENTIFIER-1 TO IDENTIFIER-2
Copies contents of identifier-1 To identifier-2
identifier-1 is sending field
identifier-2 is receiving field
Example:
MOVE Qty-In TO Qty-Out
Contents of Qty-Out replaced by contents of Qty-In
If Qty-In = 253, contents of Qty-Out = 253 after
MOVE executed
Qty-In remains unchanged
Interra IT 75
MOVING DATA
Format-2:
MOVE literal-1 TO identifier-2

Value of literal-1 copied to identifier-2
Data type of literal and identifier
should match
Move numeric literals to numeric fields
Move nonnumeric literals to
alphanumeric fields

Interra IT 76
MOVING DATA
Examples
05 Qty-Out PIC 999.
05 Color-Out PIC X(4).

Move 100 To Qty-Out
Move 'Blue' To Color-Out
Contents of Qty-Out replaced with
100
Contents of Color-Out replaced with
'Blue'

Interra IT 77
MOVING DATA
Multiple Moves:
MOVE 0 TO Total-1, Total-2, Total-3

Move may have multiple receiving
fields
Contents of all three total fields set to
0

Interra IT 78
MOVING DATA
Moving Figurative Constants:
ZEROS may be moved to numeric or
alphanumeric field
Moves 0 to every position of receiving
field
SPACES moved only to alphanumeric
field
Moves space or blank to every position of
receiving field

Interra IT 79
MOVING DATA
Numeric MOVE:
Numeric field or literal is moved to
numeric receiving field
When PIC clauses of both fields
identical, sending and receiving fields
same after MOVE
Previous contents of receiving field
are replaced by MOVE
Interra IT 80
MOVING DATA
Numeric MOVE Rules:
Decimal alignment always maintained
If 86.52 is moved to a field
86 always treated as integer part of
number
.52 always treated as decimal part of
number
Digits in integer part moved right to
left starting at decimal point
Digits in decimal part moved left to
right starting at decimal point

Interra IT 81
MOVING DATA
Numeric MOVE Example:
Operation: MOVE Amt-1 TO Amt-2
Amt-1 Amt-2
Picture 99V99 Picture 99V99
Contents 12
^
34 Contents
67
^
89
Digits in integer part moved so that
2 replaces 7, 1 replaces 6
Digits in decimal part moved so that
3 replaces 8, 4 replaces 9
Interra IT 82
MOVING DATA
Numeric MOVE Rules:
If receiving field has more integer
positions than sending field
Unfilled high-order (leftmost) integer
positions filled with zeros
If receiving field has more decimal
positions than sending field
Unfilled low-order (rightmost) decimal
positions filled with zeros

Interra IT 83
MOVING DATA
Numeric MOVE Rules:
Operation: MOVE Amt-3 TO Amt-4
Amt-3 Amt-4
Picture 9V9 Picture 99V99
Contents 3
^
4 Contents 56
^
78
Digits in integer part moved so that
3 replaces 6, 0 replaces 5
Digits in decimal part moved so that
4 replaces 7, 0 replaces 8
Interra IT 84
MOVING DATA
Numeric MOVE Rules:
If receiving field has fewer integer
positions than sending field
High-order (leftmost) digits truncated
If receiving field has fewer decimal
positions than sending field
Low-order (rightmost) digits truncated

Interra IT 85
MOVING DATA
Numeric MOVE Rules:
If receiving field has more integer
positions than sending field
Unfilled high-order (leftmost) integer
positions filled with zeros
If receiving field has more decimal
positions than sending field
Unfilled low-order (rightmost) decimal
positions filled with zeros

Interra IT 86
MOVING DATA
Numeric MOVE Rules:
Operation: MOVE Amt-5 TO Amt-6
Amt-5 Amt-6
Picture 99V99 Picture 9V9
Contents 12
^
34 Contents
5
^
6
Digits in integer part moved so that
2 replaces 5, 1 not moved
Digits in decimal part moved so that
3 replaces 6, 4 not moved
Interra IT 87
MOVING DATA
Nonnumeric MOVE:
Sending field is alphanumeric field or
nonnumeric literal
Receiving field is alphanumeric field
Interra IT 88
MOVING DATA
Rules for Nonnumeric MOVE:
Characters moved from left to right
If receiving field longer, low-order
(rightmost) positions replaced with
spaces
If receiving field shorter, low-order
characters in sending field truncated

Interra IT 89
MOVING DATA
Nonnumeric MOVE example:
Operation: MOVE Code-1 TO Code-2
Code-1 Code-2
Picture X(3) Picture X(6)
Contents abc Contents
mnopqr

Characters abc replace mno
Remaining three positions in Code-2
replaced with blanks
Interra IT 90
MOVING DATA
Nonnumeric MOVE example:
Operation: MOVE Code-3 TO Code-4
Code-3 Code-4
Picture X(5) Picture X(3)
Contents vwxyz Contents efg

Characters vwx replace efg
y and z are not moved since all
positions in Code-4 are filled
Interra IT 91
MOVING DATA
When receiving field is group item,
alphanumeric MOVE rules followed.
If sub-fields are numeric, invalid data
may be stored in sub-fields.
Interra IT 92
MOVING DATA
Group MOVE example:
Operation: MOVE "ABCD" TO WS-
Code
01 WS-Code.
05 WS-Part-1 PIC XX.
05 WS-Part-2 PIC 99.
After MOVE, value of WS-Part-1 is AB,
WS-Part-2 is CD
Causes error if WS-Part-2 then used
in arithmetic operation
Interra IT 93
MOVING DATA
MOVE Operations
Avoid using sending field with
different data type than receiving
field
Move numeric fields, numeric literals
or ZEROS to numeric fields
Move alphanumeric fields,
nonnumeric literals, ZEROS or
SPACES to alphanumeric fields
Interra IT 94
MOVING DATA
MOVE CORRESPONDING:
01 GR-1.
05 Item-1 PIC X(5).
05 Item-2 PIC 99.
01 GR-2.
05 Item-1 PIC X(5).
05 Item-2 PIC 99.
05 Item-3 99V99.

MOVE CORRESPONDING GR-1 TO GR-2.

Only Items with same name are moved.
Interra IT 95
PRINTING AND DISPLAYING
DATA
Disk Files vs. Output for Users
Conciseness and efficiency important
for data stored in disk files
Clarity and readability important for
output read by people
Displayed on screen
Printed in reports
Interra IT 96
PRINTING AND DISPLAYING
DATA
Output for Users:
Edit symbols used to make data fields
more readable
Display 001495 as $14.95
Use spacing between lines and page
margins for readability
Space fields across page or screen
Heading and footing lines added to
improve clarity of output
Interra IT 97
PRINTING AND DISPLAYING
DATA
Editing Functions:
Report-item: elementary item that
contains edit symbols in its PIC clause
Editing occurs when elementary item
moved to report-item
PIC clause of report-item determines
editing performed
Interra IT 98
PRINTING AND DISPLAYING
DATA
Decimal points
Report-item - elementary item that
contains edit symbols in its PIC clause
Editing occurs when elementary item
moved to report-item
PIC clause of report-item determines
editing performed
Interra IT 99
PRINTING AND DISPLAYING
DATA
Decimal points
Operation: Move In-Amt To Out-Amt

Field Picture Contents
Positions
In-Amt 99V99 12
^
34 4
Out-Amt 99.99 12.34 5

Actual decimal point
Replaces implied one
Uses a storage position
Interra IT 100
PRINTING AND DISPLAYING
DATA
Suppressing Leading Zeros
Zeros in leftmost position of number
usually suppressed
Value of number not affected
00025 and 25 have same value
Improves readability
Edit symbol Z in PIC clause
suppresses leading zeros, replaces
with blanks
Interra IT 101
PRINTING AND DISPLAYING
DATA
Asterisks
Example:
WS-Chk-Amt Out-Chk-Amt
PIC 9(4)V99 PIC $*,***.99
2345
^
15 $2,345.15
0072
^
08 $***72.08
0000
^
06 $*****.06

Interra IT 102
PRINTING AND DISPLAYING
DATA
Plus or Minus Signs
PIC clause with 9s is unsigned field
Value assumed to be positive
Use S with 9s in PIC clause of
sending field to define signed field
Use PIC of S9(3) to store -425
Report-item field must include + or -
editing symbol to print or display a
sign
Interra IT 103
PRINTING AND DISPLAYING
DATA
Debit and Credit Symbols
For accounting applications replace -
(minus) sign with
DB to debit an account when negative
CR to credit an account when negative
Always specified to right of report-
item
Print only when value moved to
report item is negative
Interra IT 104
PRINTING AND DISPLAYING
DATA
Spaces, Zeroes or Slashes
B (space or blank), 0 (zero) or /
(slash) may be inserted in report-
item PIC as separator
Used to edit either nonnumeric or
numeric fields

Interra IT 105
PRINTING AND DISPLAYING
DATA
Spaces, Zeroes or Slashes
Examples:
Assume
PIC 9(3) for WS-Amt
PIC X(3) for WS-Name

Report-Item
Contents PICTURE Contents
WS-Amt 528 99BB9 52bb8
WS-Amt 218 999,000
218,000
WS-Name RAY XBXBX RbAbY
WS-Name JAN X/X/X J/A/N
Interra IT 106
PRINTING AND DISPLAYING
DATA
Editing and Arithmetic Operations
Editing performed when
Sending field moved to report-item
Result of arithmetic operations stored in
report-item
PICTURE of report-item determines
type of editing

Interra IT 107
PRINTING AND DISPLAYING
DATA
Editing and Arithmetic Operations
All items used in arithmetic operation
must be numeric
Error if report-item used in calculation
of result
This statement invalid if Total-Out is
report-item
ADD WS-Total TO Total-Out
Report-item may be used after
GIVING
Interra IT 108
PRINTING AND DISPLAYING
DATA
Editing with Floating Strings
Used to place $, + or - directly
preceding first significant digit
For example, 000516 becomes $5.16
instead of $ 5.16
In edit string, replace all Zs with
floating character ($, + or -)
Suppresses leading zeros, commas
Interra IT 109
PRINTING AND DISPLAYING
DATA
Editing with Floating Strings:
Example
Assume a PICTURE of S9(4)V99 for WS-Amt

Out-Amt
WS-Amt PICTURE Contents
0002
^
29
-
$$,$$$.99
bbbb$2.29-
0036
^
62
+
++,+++.99
bbb+36.62
0007
^
05
-
---99.99 bb-07.05
Interra IT 110
PRINTING AND DISPLAYING
DATA
WRITE . FROM Statement
To transfer data from storage to print
area and then print
Replaces MOVE and WRITE

Write Print-Rec From Heading-1

instead of

Move Heading-1 to Print-Rec
Write Print-Rec

Interra IT 111
PRINTING AND DISPLAYING
DATA
ADVANCING Option
Single spacing for WRITE is default
Use AFTER or BEFORE ADVANCING to
obtain any number of blank lines
between each print line
Interra IT 112
PRINTING AND DISPLAYING
DATA
Word PAGE after ADVANCING causes
paper to advance to next page
To advance paper to top of new page
and print a heading, code

Write Print-Rec From Heading-
Line-1
After Advancing Page

Interra IT 113
PRINTING AND DISPLAYING
DATA
End-of-Page Control
When page is full, need to advance to
next page and print headings again
Define WORKING-STORAGE field for
line counter
Initialize line counter to zero and
increment it each time a line is
printed
When line counter equals or exceeds
line limit for page, advance to next
page
Interra IT 114
PRINTING AND DISPLAYING
DATA
Printing Page Numbers
Define WORKING-STORAGE field for
page number
Initialize and then increment page
number each time new page begins
Move page number to report-item in
heading line before printing it at top
of a new page
Interra IT 115
PRINTING AND DISPLAYING
DATA
Accessing date of run:
Example
ACCEPT identifier-1 FROM DATE

For older compilers identifier must be
defined as numeric field to hold 6
digits
Interra IT 116
STRING HANDLING
COBOL provides language constructs for
performing these operations
associated with string data items:
Join data items - STRING
Split data items - UNSTRING
Sub-string Reference Modifiers
Tally replace data-items - INSPECT


Interra IT 117
STRING HANDLING
Joining Data Items:
01 RCD-01.
05 CUST-INFO.
10 CUST-NAME PIC X(15).
10 CUST-ADDR PIC X(35).
05 BILL-INFO.
10 INV-NO PIC X(6).
10 INV-AMT PIC $$,$$$.99.
10 AMT-PAID PIC $$,$$$.99.
10 DATE-PAID PIC X(8).
10 BAL-DUE PIC $$,$$$.99.
10 DATE-DUE PIC X(8).
========================================================
STRING
LINE-NO SPACE CUST-INFO INV-NO SPACE DATE-DUE SPACE
DELIMITED BY SIZE
BAL-DUE
DELIMITED BY DEC-POINT
INTO RPT-LINE
WITH POINTER LINE-POS.
Interra IT 118
STRING HANDLING
The UNSTRING statement causes
contiguous data in a sending field to
be separated and placed into multiple
receiving fields.
UNSTRING identifier-1 DELIMITED BY ALL
literal-1
INTO identifier-2 COUNT IN count-1
identifier-3 COUNT in count-2
ON OVERFLOW GO TO UNSTRING-COMPLETE
Interra IT 119
STRING HANDLING
Reference a sub-string of character-
string data item items (including
EBCDIC data items) with Reference
Modifiers.

MOVE FIRST NAME LAST NAME596ADDRESS TO
Customer-Record
MOVE Customer-Record(1:20) TO Orig-Customer-Name

Contents of Orig-Customer-Name will be :
FIRST NAME LAST NAME

Interra IT 120
STRING HANDLING
INSPECT
01 N PIC X(20).
01 N-Length PIC 99 value zero.

* Display null-terminated string
Inspect N tallying N-length
for characters before initial x'00'
Display 'N: ' N(1:N-length) ' Length: '
N-length
Interra IT 121
COBOL VERBS & COMMANDS
6. COMPUTING IN COBOL: THE
ARITHMETIC VERBS AND INTRINSIC
FUNCTIONS
Interra IT 122
ARITHMETIC VERBS
ADD TO Statement:
Format-1

identifier-1
ADD TO identifier-2 ...
literal-1

identifier-1 or literal-1 added to
identifier-2
Result stored in identifier-2

Interra IT 123
ARITHMETIC VERBS
ADD GIVING Statement
Format-2

identifier-1
ADD GIVING identifier-2 ...
literal-1

Identifiers and literals preceding
GIVING added together
Result stored in identifier-2

Interra IT 124
ARITHMETIC VERBS
Producing more than one sum
Several ADD operations can be done in
single statement
Assume X, Y and Z are numeric fields
X = 5, Y = 3 and Z = 7

ADD Statement Result
Add X To Y, Z Y = 8, Z = 12
Add X, 6 Giving Y, Z Y = 11, Z = 11
Interra IT 125
ARITHMETIC VERBS

SUBTRACT Statement:

identifier-1
SUBTRACT FROM identifier-2 ...
literal-1

identifier-1 or literal-1 subtracted
from identifier-2
Result stored in identifier-2

Interra IT 126
ARITHMETIC VERBS
MULTIPLY BY.
MULTIPLY BY GIVING
DIVIDE INTO
DIVIDE . BY . GIVING.
REMAINDER

Interra IT 127
ARITHMETIC VERBS
ROUNDED Option:
Arithmetic result truncated if room to
store all decimal positions not
available
Result of 3.89 stored in field with PIC
9V9 as 3
^
8
Include ROUNDED to round result to
PICTURE specification
Result of 3.89 stored as 3.9 if ROUNDED
option used

Interra IT 128
ARITHMETIC VERBS
OVERFLOW or SIZE ERROR
Occurs when result value too large to
be stored in result field
Result of this ADD statement is 1,075

Add 350 To 725 Giving Num
If Num has PICTURE of 999, only 3
digits can be stored
High-order digits truncated so 075
stored in Num
Interra IT 129
ARITHMETIC VERBS
Checking for Overflow
Any arithmetic statement may include
one or both size error clauses
ON SIZE ERROR statement(s)
Specifies one or more statements to be
executed if overflow (size error) occurs
NOT ON SIZE ERROR statement(s)
Specifies one or more statements to be
executed if overflow (size error) does not
occur
Interra IT 130
ARITHMETIC VERBS
SIZE ERROR Clause Example
ADD X TO Y GIVING Z
ON SIZE ERROR DISPLAY ' Result too
large'
NOT ON SIZE ERROR PERFORM Calc-Para
END-ADD
If sum of X and Y too large to store in Z,
DISPLAY statement executed
If Z large enough for result, Calc-Para is
performed

Interra IT 131
ARITHMETIC VERBS
COMPUTE statement
General arithmetic statement using
symbols in place of arithmetic verbs
Symbol Verb
+ ADD
- SUBTRACT
* MULTIPLY
/ DIVIDE
** exponentiation
Interra IT 132
ARITHMETIC VERBS
Format
arithmetic-exp-1
COMPUTE identifier-1 = literal-1
identifier-2


Identifier to left of equal sign set to
value of arithmetic-expression, literal
or identifier on right of equal sign

Interra IT 133
ARITHMETIC VERBS
COMPUTE statement
COMPUTE can include same optional
clauses used with other arithmetic
verbs
ROUNDED follows result field
(identifier preceding equal sign)
If ON SIZE ERROR or NOT ON SIZE
ERROR clauses used, include scope
terminator END-COMPUTE

Interra IT 134
ARITHMETIC VERBS
Order of Evaluation
Arithmetic expression may include
any combination of symbols +, -, *, /
or **
Order of operations
1. ** all exponentiation performed first
2. * or / in order or appearance left
to right
3. + or - in order or appearance left
to right
4. ( ) override rules 1-3, all operations
in ( ) performed first


Interra IT 135
INTRINSIC FUNCTIONS
Intrinsic Functions
Built-in procedures to perform
particular task like
Find square root of number
Convert letters to uppercase
Get current date
Approved as extensions to COBOL
standard in 1989
Now included in many compilers
Interra IT 136
INTRINSIC FUNCTIONS
Example
Find square root of X and place result in
Y

COMPUTE Y = FUNCTION SQRT(X)

Value of X passed to function called
Sqrt
Code in function finds square root of
X
Result returned by SQRT assigned to
Y

Interra IT 137
INTRINSIC FUNCTIONS
More examples:
Convert More-Data to uppercase

MOVE FUNCTION UPPER-CASE(More-
Data) TO Up-More-Data

If More-Data = "Yes", function Upper-
Case returns value "YES"
Value "YES" moved to Up-More-Data
Interra IT 138
INTRINSIC FUNCTIONS
ACOS MEAN TAN
ANNUITY MEDIAN UNDATE
ASIN MIDRANGE UPPER-
CASE
ATAN MIN VARIANCE
CHAR MOD
COS NUMVAL
CURRENT-DATE NUMVAL-C
DATE-OF-INTEGER ORD
FACTORIAL PRESENT-VALUE
INTEGER RANDOM
LENGTH RANGE
LOG SQRT
LOWER-CASE STANDARD-DEVIATION
MAX SUM
Interra IT 139
COBOL VERBS & COMMANDS
7. DECISION MAKING: USING THE IF
AND EVALUATE STATEMENTS
Interra IT 140
IF STATEMENT
Format:
IF condition-1 THEN statement-1
ELSE statement-2
END-IF


Interra IT 141
EVALUATE SATEMENT
Format:
identifier-1
EVALUATE expression-1
TRUE
FALSE

(WHEN phrase-1 statement-1)
.
.
WHEN OTHER statement-3
END-EVALUATE

Interra IT 142
GO TO
Format-1
GO TO paragraph-1
paragraph-2
paragraph-3
DEPENDING ON identifier1
Interra IT 143
CALL
The CALL statement transfers control
from one object program to another
within the run unit
Format

CALL identifier-1 USING identifier-2
Interra IT 144
ENTRY STATEMENT
The ENTRY statement establishes an
alternate entry point into a COBOL
called subprogram.
Format
ENTRY literal-1

Interra IT 145
CONTINUE
The CONTINUE statement allows you to
specify a no operation statement.
CONTINUE indicates that no
executable instruction is present.
Format

CONTINUE.
Interra IT 146
EXIT PROGRAM
The EXIT PROGRAM statement
specifies the end of a called program
and returns control to the calling
program.
If control reaches an EXIT PROGRAM
statement, and no CALL statement is
active, control passes through the
exit point to the next executable
statement.


Interra IT 147
STOP RUN

When STOP RUN is specified, execution of the
object program is terminated, and control
is returned to the system.
The STOP RUN statement does not have to
be the last statement in a sequence, but
the statements following the STOP RUN will
not be executed.
The STOP RUN statement closes all files
defined in any of the programs comprising
the run unit.
Interra IT 148
GOBACK
The GOBACK statement functions like
the EXIT PROGRAM statement when it
is coded as part of a called program
(or the EXIT METHOD statement
when it is coded as part of an invoked
method) and like the STOP RUN
statement when coded in a main
program.
The GOBACK statement specifies the
logical end of a called program or
invoked method.
Interra IT 149
EXIT STATEMENT
The EXIT statement provides a
common end point for a series of
procedures
Format

Paragraph-name. EXIT.
Interra IT 150
PERFORM
Format
PERFORM procedure-1
Procedure-1 can be a paragraph or
section.
The procedure(s) referenced in the
basic PERFORM statement are
executed once, and control then
passes to the next executable
statement following the PERFORM
statement.

Interra IT 151
PERFORM
PARA-A.
PERFORM PARA-B THRU PARA-C.


PARA-B.
PARA-1.
PARA-2.
PERFORM PARA-4 THRU PARA-6.
PARA-3.
PARA-4.
PARA-5
PARA-6.
PARA-C.

Interra IT 152
COBOL VERBS & COMMANDS
8. ITERATION: BEYOND THE BASIC
PERFORM
Interra IT 153
IN-LINE PERFORM
Format
PERFORM
Statement-1
Statement-2
END-PERFORM
Interra IT 154
PERFORM with TIMES
Format
PERFORM identifier-1 TIMES
Statement-1
Statement-2
END-PERFORM
OR
PERFORM procedure-1 identifier-1 TIMES
Interra IT 155
PERFORM with UNTIL
Format

PERFORM procedure-1 THRU procedure-2 UNTIL condition-1.

OR

PERFORM UNTIL condition-1
Statement-1
Statement-2.
END-PERFORM

Interra IT 156
PERFORM with VARYING
Varying two identifiers
PERFORM procedure-name-1 THRU
procedure-name-2
VARYING identifier-2 FROM identifier-3
BY identifier-4 UNTIL condition-1
AFTER identifier-5 FROM identifier-6 BY
identifier-7 UNTIL condition-2

Interra IT 157
PERFORM with VARYING
Format example:
PERFORM procedure-1 THRU procedure-
2 VARYING identifier-1 FROM
identifier-2 BY identifier-3 UNTIL
condition-1.
Interra IT 158
COBOL VERBS & COMMANDS
9. CONTROL BREAK PROCESSING
Interra IT 159
CONTROL BREAK PROCESSING
Well designed programs are structured
programs
Use instructions executed in
standardized order
Divide program into modules, each
performing a specific function
Control returns to place module called
from
Simple PERFORM used in COBOL to
execute modules (paragraphs)
Interra IT 160
CONTROL BREAK PROCESSING
Well designed programs use top-down
approach
Code modules in hierarchical order
Main modules first, then secondary
modules with detailed code
Step-wise refinement
Interra IT 161
CONTOL BREAK PROCESSING
Well designed programs are modular
Group related statements together
into modules
Execute each module or paragraph in
COBOL with simple PERFORM
For example, statements to calculate
students tuition in one module,
statements to calculate room and
board in another module
Interra IT 162
CONTROL BREAK PROCESSING
Hierarchy Charts
To illustrate top-down relationships
among modules
Graphic method to divide program
into modules
Modules shown as rectangular boxes
Relationships among modules
represented by connected lines
Interra IT 163
CONTROL BREAK PROCESSING
Example:
D E
B
F G H
C
A
Interra IT 164
CONTROL BREAK PROCESSING
Name up to 30 characters - letters,
digits, hyphen
Choose meaningful name that
describes type of instructions in
module
Use numeric prefixes to indicate
relative location of module in program
Examples
100-Main-Module 200-Process-
Data
Interra IT 165
CONTROL BREAK PROCESSING
Four logical control structures:
Used by structured programs to
specify order in which instructions are
executed

1. Sequence
2. Selection
3. Iteration
4. Case Structure

Interra IT 166
CONTROL BREAK PROCESSING
SEQUENCE
Instructions executed in order they
appear
Three instructions below executed
one after the other

START
Read Amt1, Amt2
Compute Total = Amt1 + Amt2
Write Total
STOP
Interra IT 167
CONTROL BREAK PROCESSING
ITERATION
To specify repeated execution of
series of steps
Use in-line or standard PERFORM
UNTIL for iteration in COBOL
Both execute group of instructions
repeatedly until a condition is met

Interra IT 168
CONTROL BREAK PROCESSING
SELECTION
Instructions executed depending on
existence of a condition
Called IF-THEN-ELSE logical control
structure

Interra IT 169
CONTROL BREAK PROCESSING
CASE STRUCTURE
To choose from one of several sets of
instructions depending on a condition
use EVALUATE.
For example, assume
Different instructions should be executed
when field Code-In has values of 1, 2 or
3
Any other value of Code-In is considered
an error

Interra IT 170
COBOL VERBS & COMMANDS
10. DATA VALIDATION
Interra IT 171
DATA VALIDATION
Conditional Expressions
A conditional expression causes the
object program to select alternative
paths of control, depending on the
truth value of a test. Conditional
expressions are specified in
EVALUATE, IF, PERFORM, and
SEARCH statements.

Interra IT 172
DATA VALIDATION
Simple Conditions:
There are five simple conditions:
Class condition
Condition-name condition
Relation condition
Sign condition
Switch-status condition
A simple condition has a truth value of
either true or false.
Interra IT 173
DATA VALIDATION
CLASS CONDITION (Example)
Identifier-1 IS class-name
Instead of class name following can be
used too.
ALPHABETIC
ALPHABETIC LOWER
NUMERIC
Etc
Interra IT 174
DATA VALIDATION
CONDITION NAME (Example)
01 AGE-GROUP PIC 99.
88 INFANT VALUE 0.
88 BABY VALUE 1, 2.
88 CHILD VALUE 3 THRU 12.
88 TEEN-AGER VALUE 13 THRU 19.

IF INFANT... (Tests for value 0)
IF BABY... (Tests for values 1, 2)
IF CHILD... (Tests for values 3 through 12)
IF TEEN-AGER... (Tests for values 13 through 19)


Interra IT 175
DATA VALIDATION
A relation condition compares two
operands, either of which can be an
identifier, literal, arithmetic
expression, or index-name. A
nonnumeric literal can be enclosed in
parentheses within a relation
condition.
Example:
Operand-1 GREATER THAN Operand-2
Interra IT 176
DATA VALIDATION
Pointer Data Items
Example:
ADDRESS OF identifier-1 IS NOT
NULL
ADDRESS OF identifier-1 EQUAL
ADDRESS OF identifier-2
Interra IT 177
DATA VALIDATION
Comparing Numeric Operands
The algebraic values of numeric operands are
compared.
The length (number of digits) of the
operands is not significant.
Unsigned numeric operands are considered
positive.
Zero is considered to be a unique value,
regardless of sign.
Comparison of numeric operands is
permitted, regardless of the type of USAGE
specified for each.
Interra IT 178
DATA VALIDATION
Comparing Numeric and Nonnumeric
Operands
If the nonnumeric operand is a literal or an
elementary data item, the numeric operand is treated
as though it were moved to an alphanumeric
elementary data item of the same size, and the
contents of this alphanumeric data item were then
compared with the nonnumeric operand.
If the nonnumeric operand is a group item, the
numeric operand is treated as though it were moved
to a group item of the same size, and the contents of
this group item were compared then with the
nonnumeric operand.

Interra IT 179
DATA VALIDATION
Complex Conditions:
A complex condition is formed by
combining simple conditions,
combined conditions, and/or complex
conditions with logical operators, or
negating these conditions with logical
negation.
AND
OR
NOT
Interra IT 180
DATA VALIDATION
Order of evaluation:

NOT A IS GREATER THAN B OR A + B IS
EQUAL TO C AND D IS POSITIVE
is evaluated as if parenthesized as
follows:
(NOT (A IS GREATER THAN B)) OR
(((A + B) IS EQUAL TO C) AND (D IS
POSITIVE))

Interra IT 181
DATA VALIDATION
Comparing Nonnumeric Operands
Comparisons of nonnumeric operands
are made with respect to the collating
sequence of the character set in use.
For the EBCDIC character set, the
EBCDIC collating sequence is used.

Interra IT 182
COBOL VERBS & COMMANDS
11. ARRAY PROCESSING AND TABLE
HANDLING
Interra IT 183
ARRAYS

The Data Division clauses used for
table handling are the OCCURS clause
and USAGE IS INDEX clause.
The OCCURS clause specifies tables
whose elements can be referred to by
indexing or subscripting. It also
eliminates the need for separate
entries for repeated data items.

Interra IT 184
ARRAYS
Formats for the OCCURS clause include fixed-
length tables or variable-length tables.
Example:
05 ITEM-1 OCCURS 6.
10 ITEM-A PIC S9(3).
10 ITEM-B PIC +99.9.
10 ITEM-C PIC X(4).
10 ITEM-D REDEFINES ITEM-C PIC 9(4).
10 ITEM-E USAGE COMP-1.
10 ITEM-F USAGE INDEX.
Interra IT 185
ARRAYS
Variable-length tables are specified
using the OCCURS DEPENDING ON
clause.

OCCURS integer-1 TO integer-2 DEPENDING ON data-
name-1

The object of the OCCURS DEPENDING ON
clause must describe an integer data item.
The OCCURS DEPENDING ON clause cannot
be specified as subordinate to another
OCCURS clause.
Interra IT 186
ARRAYS
Subscripting:
For example, if TABLE-THREE is defined as:

01 TABLE-THREE.
05 ELEMENT-ONE OCCURS 3 TIMES.
10 ELEMENT-TWO OCCURS 3 TIMES.
15 ELEMENT-THREE OCCURS 2
TIMES PIC X(8).

a valid subscripted reference to TABLE-THREE
is:
ELEMENT-THREE (2 2 1)
Interra IT 187
ARRAYS
INDEXED BY phrase:
Format
OCCURS integer-1 TIMES INDEXED by
index-name-1

Interra IT 188
ARRAYS
ASCENDING/DESCENDING KEY Phrase

Format
OCCURS integer-1 TIMES ASCENDING
KEY IS data-name-1

Data-name-2 Must be the name of the
subject entry, or the name of an
entry subordinate to the subject
entry.
Interra IT 189
ARRAYS
The following example illustrates the
specification of ASCENDING KEY data item:
WORKING-STORAGE SECTION.
01 TABLE-RECORD.
05 EMPLOYEE-TABLE OCCURS 100 TIMES
ASCENDING KEY IS WAGE-RATE EMPLOYEE-NO
INDEXED BY A, B.
10 EMPLOYEE-NAME PIC X(20).
10 EMPLOYEE-NO PIC 9(6).
10 WAGE-RATE PIC 9999V99.
10 WEEK-RECORD OCCURS 52 TIMES
ASCENDING KEY IS WEEK-NO INDEXED BY C.
15 WEEK-NO PIC 99.
15 AUTHORIZED-ABSENCES PIC 9.
15 UNAUTHORIZED-ABSENCES PIC 9.
15 LATE-ARRIVALS PIC 9.
Interra IT 190
ARRAYS
SEARCH (Sequential)
Format-1
SEARCH identifier-1
AT END statement-1
WHEN condition-1 statement-2
END-SEARCH
Search begins at current index setting.
Interra IT 191
ARRAYS
SEARCH (Binary)
SEARCH ALL identifier-1
WHEN condition-1 statement-1
END SEARCH


Interra IT 192
COBOL FILE PROCESSING
12. SEQUENTIAL FILE PROCESSING
Interra IT 193
COBOL FILE PROCESSING
Opening Files
OPEN INPUT file-name-1.
OUTPUT
EXTEND
I-O
Interra IT 194
COBOL FILE PROCESSING
Reading Files
READ file-name-1
INTO identifier-1
AT END statement-1
NOT AT END statement-2
END-READ
Interra IT 195
COBOL FILE PROCESSING
Writing to Files
WRITE record-name-1 FROM identifier-1
AFTER ADVANCING integer-1 LINES.

Interra IT 196
COBOL FILE PROCESSING
The FILE STATUS clause

The FILE STATUS clause monitors the
execution of each input-output
operation for the file.
It is declared along with the SELECT
statement in INPUT-OUTPUT
SECTION.
Interra IT 197
COBOL FILE PROCESSING
Closing Files
CLOSE file-name-1


Interra IT 198
COBOL FILE PROCESSING
13. SORTING AND MERGING
Interra IT 199
Example of SORT
IDENTIFICATION DIVISION.
PROGRAM-ID. InputSort.
AUTHOR. Interra.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION. FILE-
CONTROL.
SELECT StudentFile ASSIGN TO INFILE".
SELECT WorkFile ASSIGN TO
SORTFILE".
DATA DIVISION.
FILE SECTION.
FD StudentFile.
01 StudentDetails PIC X(30).
SD WorkFile.
01 WorkRec.
02 WStudentId PIC 9(7).
02 FILLER PIC X(23).
PROCEDURE DIVISION.
Begin.
SORT WorkFile ON ASCENDING KEY
WStudentId
INPUT PROCEDURE IS
GetStudentDetails
GIVING StudentFile.
STOP RUN.
GetStudentDetails.
ACCEPT WorkRec.
PERFORM UNTIL WorkRec =
SPACES RELEASE WorkRec
ACCEPT WorkRec
END-PERFORM.
Interra IT 200
MERGE
Example of MERGE
MERGE work-file ON ASCENDING KEY ws-
studentId USING insertionsfile, studentfile
GIVING newstudentfile.
Workfile needs to be defined this way:
SD workfile.
01 WorkRec.
02 WStudentId PIC 9(7).
02 FILLER PIC X(23).
Interra IT 201
COBOL FILE PROCESSING
14. INDEXED AND RELATIVE FILE
PROCESSING (VASM)
Interra IT 202
COBOL FILE PROCESSING
ENVIRONMENT DIVISION Entries for
VSAM Files
Example 1: VSAM Sequential File
(ESDS)
SELECT S-FILE
ASSIGN TO SEQUENTIAL-AS-FILE
ORGANIZATION IS SEQUENTIAL
ACCESS IS SEQUENTIAL
FILE STATUS KEY IS FSTAT-CODE
VSAM-CODE.
Interra IT 203
COBOL FILE PROCESSING
ENVIRONMENT DIVISION Entries for VSAM
Files
Example 2: VSAM Indexed File (KSDS)
SELECT I-FILE
ASSIGN TO INDEXED-FILE
ORGANIZATION IS INDEXED
ACCESS IS DYNAMIC
RECORD KEY IS IFILE-RECORD-KEY
ALTERNATE RECORD KEY IS IFILE-
ALTREC-KEY
FILE STATUS KEY IS FSTAT-CODE VSAM-
CODE.
Interra IT 204
COBOL FILE PROCESSING
ENVIRONMENT DIVISION Entries for VSAM
Files
Example 3: VSAM Relative File (RRDS)
SELECT R-FILE
ASSIGN TO RELATIVE-FILE
ORGANIZATION IS RELATIVE
ACCESS IS RANDOM
RELATIVE KEY IS RFILE-RELATIVE-KEY
FILE STATUS KEY IS FSTAT-CODE VSAM-
CODE.

Interra IT 205
COBOL FILE PROCESSING
To initially load a VSAM file:

Open the file.
Use sequential processing because it
is faster (ACCESS IS SEQUENTIAL).
Use WRITE to add a record to the
file.

Interra IT 206
COBOL FILE PROCESSING
VSAM file processing involves these
COBOL statements:
OPEN
WRITE
START
READ AND READ NEXT
REWRITE
DELETE
CLOSE

Interra IT 207
COBOL FILE PROCESSING

Access
Mode
COBOL
Stmt.
OPEN
INPUT
OPEN
OUTPUT
OPEN I-O OPEN
EXTEND
Sequential OPEN
X X X X
WRITE
X X
START
READ
X X
REWRITE
X
DELETE
CLOSE
X X X X
Interra IT 208
COBOL FILE PROCESSING

Access
Mode
COBOL
Stmt.
OPEN
INPUT
OPEN
OUTPUT
OPEN I-O OPEN
EXTEND
Sequential OPEN
X X X X
WRITE
X X
START
X X
READ
X X
REWRITE
X
DELETE
X
CLOSE
X X X X
Interra IT 209
COBOL FILE PROCESSING

Access
Mode
COBOL
Stmt.
OPEN
INPUT
OPEN
OUTPUT
OPEN I-O OPEN
EXTEND
Random OPEN
X X X
WRITE
X X
START
READ
X X
REWRITE
X
DELETE
X
CLOSE
X X X
Interra IT 210
COBOL FILE PROCESSING

Access
Mode
COBOL
Stmt.
OPEN
INPUT
OPEN
OUTPUT
OPEN I-O OPEN
EXTEND
Dynamic OPEN
X X X
WRITE
X X
START
X X
READ
X X
REWRITE
X
DELETE
X
CLOSE
X X X
Interra IT 211
COBOL FILE PROCESSING
File Position Indicator
The file position indicator marks the next record to be
accessed for sequential COBOL requests. You do not
set the file position indicator anywhere in your
program; it is set by successful OPEN, START, READ,
and READ NEXT statements. Subsequent READ or
READ NEXT requests use the established file position
indicator location and update it.
The file position indicator is not used or affected by
the output statements WRITE, REWRITE, or DELETE.
The file position indicator has no meaning for random
processing.

Interra IT 212
COBOL FILE PROCESSING
Position file indicator
Example:
START file-name-1 KEY IS data-name-1

Sequential READ:
READ filename-1 NEXT RECORD INTO
identifier-1
AT END statement-1
NOT AT END statement-2
END-READ
Interra IT 213
COBOL FILE PROCESSING
Reading RRDS and KSDS files

READ filename-1 RECORD INTO
identifier-1
KEY IS data-name-1
INVALID KEY statement-1
NOT INVALID KEY statement-2
END-READ
Interra IT 214
COBOL FILE PROCESSING
The COBOL WRITE statement adds a record to a file,
without replacing any existing records. The record to
be added must not be larger than the maximum
record size set when the file was defined. Check the
file status key after each WRITE statement.

Interra IT 215
COBOL FILE PROCESSING
Updating RRDS and KSDS records

Access Method ESDS KSDS RRDS
ACCESS IS SEQUENTIAL

OPEN I-O
READ
REWRITE
CLOSE
OPEN I-O
READ
REWRITE
DELETE
CLOSE
OPEN I-O
READ
REWRITE
DELETE
CLOSE
ACCESS IS RANDOM N/A
OPEN I-O
READ
REWRITE
CLOSE
OPEN I-O
READ
REWRITE
CLOSE
ACCESS IS DYNAMIC
Sequential Processing
N/A
OPEN I-O
READ NEXT
REWRITE
CLOSE
OPEN I-O
READ NEXT
REWRITE
CLOSE
ACCESS IS DYNAMIC
Random Process
N/A
OPEN I-O
READ
REWRITE
CLOSE
OPEN I-O
READ
REWRITE
CLOSE
Interra IT 216
COBOL FILE PROCESSING
Deleting Records from a VSAM File
Open the file I-O and use the DELETE statement to remove
an existing record from an indexed or relative file. You
cannot use DELETE on a sequential file.
When ACCESS IS SEQUENTIAL, or if the file contains
spanned records, the record to be deleted must first be
read by the COBOL program. The DELETE then removes
the record that was read. If the DELETE is not preceded by
a successful READ, the deletion is not done and the status
key value is set to 92.
When ACCESS IS RANDOM or ACCESS IS DYNAMIC, the
record to be deleted need not be read by the COBOL
program. To delete a record, the key of the record to be
deleted is moved to the RECORD KEY data item and the
DELETE is issued. Check the file status key after each
DELETE statement.

Interra IT 217
COBOL FILE PROCESSING
Closing VSAM Files

Use the CLOSE statement to
disconnect your program from the
VSAM file. If you try to close a file
that is already closed, you will get a
logic error. Check the file status key
after each CLOSE statement.

Interra IT 218
COBOL PROGRAM
15. DESIGNING AND DEBUGGING
Interra IT 219
COBOL DEBUGGING
Debugging tools:
Debugging program provided with
compiler
Use DISPLAY statement to display
contents of fields at key locations in
program
The DISPLAY statements can be
turned off using the DEBUGGING
MODE.

Interra IT 220
COBOL DEBUGGING
Other third party tools:
XPEDITER is very popular
COBTEST
Interra IT 221
COBOL PROGRAM DESIGN
Program Development Process:
Determine Program Specifications
Design Program Using Program
Planning Tools
Code and Enter Program
Compile Program
Test Program
Document Program

Interra IT 222
CODING GUIDELINES
16. DOS AND DONTS
Interra IT 223
CODING GUIDELINES
Structured Programming
Eliminates use of GO TO statements
Allowed skipping to different sections of
program without returning to starting
point
Program logic easier to follow with
"GO-TO-less" programming
Interra IT 224
CODING GUIDELINES
Program divided into paragraphs
Main paragraph or module controls
logic flow using PERFORM statements
Main module "performs" other
modules when instructions in that
module required
Each module can be written and
tested independently of others

Interra IT 225
CODING GUIDELINES
Top-Down Programming
Code main modules or routines first
Code intermediate modules next
Details deferred to minor modules
and coded last

Interra IT 226
CODING GUIDELINES
1. Separate divisions by blank comment
line, page eject symbol or blank line
2. Code a single statement per line
3. Code paragraph-names on line by
themselves
4. Be liberal in use of comments. Box
lengthy comments using asterisks.
Interra IT 227
CODING GUIDELINES
5. Code SELECT statements in logical
order (input files first, then output
files) although order not required
6. Use separate lines for SELECT,
ASSIGN, ORGANIZATION clauses for
readability
7. Avoid use of device-specific file-
names

Interra IT 228
REFERENCES
VS COBOL II V1R4.0 Application Programming Language Reference
- http://publibz.boulder.ibm.com/cgi-
bin/bookmgr_OS390/BOOKS/IGYL1101/CCONTENTS?SHELF=IGYSH007&D
N=GC26-4047-07&DT=19930312093006
VS COBOL II V1R4.0 Application Programming Guide for MVS and CMS -
http://publibz.boulder.ibm.com/cgi-
bin/bookmgr_OS390/BOOKS/IGYA1101/CCONTENTS?SHELF=IGYSH007&
DN=SC26-4045-05&DT=19930312141355
Information Systems Through COBOL by Andreas S. Philippakis, Leonard
J. Kazmier from McGraw Hill Int. Ed.
Roy, M.K. and Dastidar Ghosh, D: COBOL Programming, Tata McGraw Hill
Pub. Comp. Ltd.
A Stern & Stern: Structured COBOL Programming - Addison Wesley

You might also like