Beruflich Dokumente
Kultur Dokumente
Version: COBOL/Handout/0408/1.0
Date: 30-04-08
Cognizant
500 Glen Pointe Center West
Teaneck, NJ 07666
Ph: 201-801-0233
www.cognizant.com
Handout - COBOL
TABLE OF CONTENTS
Introduction ...................................................................................................................................8
About this Module .........................................................................................................................8
Target Audience ...........................................................................................................................8
Module Objectives ........................................................................................................................8
Pre-requisite .................................................................................................................................8
Page 2
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Session 06: Introduction to Program Layout, Constants, Literals and Variables .................28
Learning Objectives ....................................................................................................................28
Program Layout ..........................................................................................................................28
Picture Clause ............................................................................................................................29
SIGN Clause ...............................................................................................................................31
VALUE Clause ............................................................................................................................32
Introduction to User defined variables ........................................................................................32
Constants and Literals ................................................................................................................32
Data Items - Level Numbers .......................................................................................................34
Introduction to MOVE Statement ................................................................................................36
Use of CORRESPONDING in MOVE Statement .......................................................................37
Introduction to PERFORM Statement ........................................................................................39
Try It Out .....................................................................................................................................45
Summary ....................................................................................................................................46
Test Your Understanding............................................................................................................46
Page 3
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Page 4
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Page 5
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Page 6
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Appendix 1 ..................................................................................................................................173
File Status Codes and Meaning ...............................................................................................173
Glossary ......................................................................................................................................175
References ..................................................................................................................................207
Websites ...................................................................................................................................207
Books ........................................................................................................................................207
Page 7
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Introduction
Target Audience
This module is designed for the entry level trainees.
Module Objectives
After completing this module, you will be able to:
Explain the concepts involved in COBOL programming
Identify how to code effectively in COBOL
Describe the problem solving concepts in COBOL
Pre-requisite
To take-up the course in COBOL, the trainee should have a fair idea on the following
topics:
JCL
VSAM
File creation using option 3.2
IBM Utilities like IEBGENER
Page 8
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Learning Objectives
After completing this session, you will be able to:
Explain the basic terminology used in programming
Describe the significance of COBOL and its usage
Explain the evolution of COBOL and the versions involved
Page 9
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Page 10
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
o High Level design: To provide a snap shot of the requirements in the form of box
diagrams, Hierarchy Charts. The idea here is to provide the overall business
objective but does not focus on how on the code changes involved, modules
impacted etc.
Coding: To write programs / scripts to achieve the objective as per the analysis and
design findings.
Compiling: This process converts the source code to object code and performing
initial validation such that there are no rule violations.
Testing and Debugging:
o Testing is to ensure that the code is executed as expected. Logical errors can be
found out only by testing.
o In order to correct the bugs found in testing, the code needs to be verified using
one of the debugging techniques.
Documentation: For future reference documentation is required
Debugging Techniques
The following are the debugging techniques:
o Manual verification of code after completing the program. This is done as part of
the self-review where the developer validates the code.
o Use Display or Print messages to ensure that a specific part of code is executed.
This technique is adopted to identify the location of the bug.
o Testing the code with specific test data for which the output is expected is already
known. This technique is adopted if the scenario is known in which the program is
not executing as expected.
o Using debugging tools or utilities
About COBOL
There was a growing need in the early days to have a high level language that will be best suited
for Business Applications. Hence In 1959, a new language COBOL – Common Business Oriented
Language emerged.
COBOL is a High Level Structured Language. This is English like language, which is used to
develop major business applications. Why most of business applications are developed using
Mainframe COBOL?
COBOL was the first programming language whose use was mandated by the Department of
Defense (DoD)
Cobol is an English like language and hence is easy to learn
Can be used with any database like VSAM or DB2, IDMS
Can handle huge volumes of Data
COBOL applications can be easily maintained
Page 11
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
History of COBOL
The following points highlight some salient facts about COBOL:
Conceived in 1959
Preliminary Version introduced in December 1959
First Standard COBOL introduced in 1961
ANSI Approved Versions introduced in 1968 and 1974
Latest COBOL Version introduced in 1985
Current version being used is COBOL II / COBOL 85
Page 12
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Versions of COBOL
The following are the versions of COBOL:
OS/VS COBOL:
o No longer supported
o The original COBOL on MVS systems
o Limited focus on structured programming constructs
VS Cobol II:
o Very popular version of COBOL
o Structured constructs such as scope terminators were introduced (END-IF, and so
on)
o Helped improved readability of programs
COBOL for z/OS:
o Also known as COBOL/370 and COBOL for OS/390
o Provided more support for Language Environment and Object Oriented features
Enterprise COBOL:
o Current version on mainframe systems
o Provide features like to support Web processing and Operating systems
Summary
The basic terminologies applied in programming are Program, Software, and
Applications Programs.
The development process includes Analysis, Design, Coding, Compiling, Testing and
Debugging, and Documentation.
The debugging techniques consist of Manual Check, Print Statements, Using Test
Data, and Tools.
Page 13
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Learning Objectives
After completing this session, you will be able to:
Describe the COBOL program layout
Explain the structure of COBOL program
Structural Hierarchy
COBOL programs are made up of familiar constructs such as paragraphs, sentences,
statements, and clauses.
These constructs, in turn contain elements such as words, names, verbs, and
symbols.
The hierarchy of a COBOL program is shown in the following diagram
Page 14
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
The IDENTIFICATION DIVISION and ENVIRONMENT DIVISION are the first 2 divisions that need
to be defined in the COBOL program. As their names indicate, these divisions contain entries that
give the name of the program, author of the program, Source computer in which the program is
written and the object computer in which the program may be run.
The meaning of this statement is quite apparent. The principal and interest are added to get
amount. The words PRINCIPAL, INTEREST, AMOUNT are called Data names. It is essential that
all the data names which are used in PROCEDURE DIVISION needs to be defined at the outset.
Hence all the data definitions take place in DATA DIVISION. Hence DATA DIVISION appears
before the PROCEDURE DIVISION and it is the third division in the COBOL program. The data
definition includes the size of the data item; the type and any initial value, which needs to be set,
are defined in DATA DIVISION entries.
The data that belongs to the input or output record is defined in FILE SECTION and the data
names that holds the intermediate results are defined in the WORKING STORAGE SECTION.
Now that we have defined all the necessary data names and files to be used by the COBOL
program, next comes the algorithm. The last division in the COBOL program is the PROCEDURE
DIVISION where the actual algorithm of the program is written. The PROCEDURE DIVISION
contains statements, which specify operations to be performed by the computer.
Thus these 4 divisions form the core structure of COBOL program. These divisions will be
explained in detail in the following Sections.
Page 15
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Statements:
Written in Procedure Division: Specify an action to be taken by the object program. A series of
statements, ending with a period, is defined as a sentence.
Identification division
IDENTIFICATION DIVISION is the first division in the COBOL program. There may be several
paragraphs in this division of which PROGRAM-ID is essential paragraph.
Each program has a Program id – Name of the program. Author – Person who is writing the
program and other information like date written, date compiled. Since the information identifies a
particular program, these are defined in IDENTIFICATION DIVISION, which is the First line of the
COBOL program. Except PROGRAM-ID all the other paragraphs are optional and are mainly for
documentation purposes.
The Program name is a user-defined word that identifies your program. The system uses the first
8 characters of program-name of the outermost program as the identifying name of the program.
The first 8 characters of program-name of the outermost program should be unique
within the system. The first character must be alphabetic.
If the first character is not alphabetic, it is converted as follows:
o 1 through 9 are changed to A through I
o Anything else is changed to J.
If a hyphen is used in characters 2 through 8 of the program-name of the outermost
program, it is changed to zero (0).
Page 16
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Apart from these statements, there can be comment statements describing the functionality of the
program, and a change log block giving the details about programmers who changed the program
as a part of enhancement to the program.
AUTHOR: This optional paragraph was removed from the standard in 1985, but most COBOL
compilers still support its use. Code the programmer's name following the paragraph name. There
are no formatting rules for the programmer's name. For example: AUTHOR. JANE DOE.
INSTALLATION: This optional paragraph was removed from the standard in 1985, but most
COBOL compilers still support its use. Code the programmer's employer's name following the
paragraph name. There are no formatting rules for the programmer's employer's name. For
example INSTALLATION. MAJOR CORPORATION.
DATE-WRITTEN: This optional paragraph was removed from the standard in 1985, but most
COBOL compilers still support its use. Code the date the program was written following the
paragraph name. There are no formatting rules for the date. For example DATE-WRITTEN. JUNE
2001.
DATE-COMPILED: This optional paragraph was removed from the standard in 1985, but many
COBOL compilers still support its use. Code the paragraph name only. The system date will be
inserted in this area for documentation purposes. For example DATE-COMPILED.
SECURITY: This optional paragraph was removed from the standard in 1985, but most COBOL
compilers still support its use. Code the security level of the program following the paragraph
name. There are no formatting rules for the security level and this entry will have no actual effect
on access to the program. The paragraph is for documentation purposes only. For example
SECURITY. CLASSIFIED.
REMARKS: This optional paragraph was removed from the standard in 1985, but many COBOL
compilers still support its use. Code the paragraph name followed by any desired comments, such
as the primary purpose of the program. For example REMARKS. THIS IS THE MAIN SCREEN
HANDLER FOR EMPLOYEE FILE MAINTENANCE.
IDENTIFICATION DIVISION.
PROGRAM-ID. SAMPLE.
AUTHOR. COGNIZANT.
DATE-WRITTEN. NOVEMBER 22, 2007.
DATE-COMPILED. NOVEMBER 24, 2007.
*================================================================*
*====== BRIEF PROGRAM DESCRIPTION ======*
*================================================================*
* AUTHOR : CHAITANYA (107592)
* DATE-WRITTEN : NOVEMBER 22, 2007
* PROGRAM OBJECTIVE : BILL PROCESSING SYSTEM
* INPUT : FROM JOB SYSIN
* OUTPUT : TO JCL SYSOUT
Page 17
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
* INPUT-OUTPUT : NONE
* ENTRY FROM : NOT APPLICABLE - MAIN PROGRAM
* REMARKS : ELT CASE STUDY FOR PRESENTATION
*================================================================*
* PROGRAM OBJECTIVE: This Program Maintains the Employee file by updating the master file.
Environment division
The identification division gives introduction about the program. Now we need to define the
Machine dependent details for our program. These details are given in ENVIRONMENT DIVISION.
The ENVIRONMENT DIVISION must follow the IDENTIFICATION DIVISION in the COBOL
program. Among all the divisions this one is the most machine dependent division. The computer
and all the peripheral devices required by the program are described in this division.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
[SOURCE-COMPUTER. source m/c.]
[OBJECT-COMPUTER. target m/c
[PROGRAM COLLATING SEQUENCE IS alphabet-name].]
[SPECIAL NAMES.
[, CURRENCY SIGN IS literal-1]
[, DECIMAL-POINT IS COMMA]
[, alphabet-name IS {STANDARD-1
STANDARD-2
EBCIDIC
NATIVE
lit-1 [ {THRU lit-2
(ALSO lit-3)...}]...]...
[, {SYSIN SYSIPT CONSOLE
SYSPUNCH SYSPCH
SYSOUT SYSLIST SYSLST
C01 to C12 CSP S01 to S05}
IS mnemonic-name-1]...
[, CLASS class-name-1 IS (lit-5 [THRU lit-6])...]...
[, SYMBOLIC CHARACTERS
(symb-char-1 ... {IS ARE} int-1...) ...
[IN alphabet-name-1] ] ...
.]
Page 18
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
In the configuration section at least the source computer and object computer paragraph needs to
be coded.
Page 19
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Example 2:
CONFIGURATION SECTION.
SOURCE-COMPUTER. IBM 3090.
OBJECT -COMPUTER. VAX-6410
PROGRAM COLLATING SEQUENCE IS ASCII-order.
SPECIAL-NAMES.
ALPHABET ASCII-order IS STANDARD-1
DECIMAL IS COMMA
CURRENCY IS ‘#’
SYMBOLIC CHARACTERS backspc IS 23
Input-Output Section
This section is primarily used to code the FILE-CONTROL paragraph.
FILE-CONTROL: This paragraph is used to associate the files to be used in the program with
specific I/O devices. For example:
FILE-CONTROL.
SELECT PRINTER-FILE
ASSIGN TO SYS015-UR-1403-S.
In the example, PRINTER-FILE is the name of the file to be used throughout the program.
SYS015-UR-1403-S is a system name, which will be used to link the file to something in the
operating system. The method of such connection varies from system to system.
Data Division
The DATA DIVISION is where all of the data used by a program is defined. It is divided into five
sections: the FILE, WORKING-STORAGE, LINKAGE, REPORT, and COMMUNICATION
SECTIONs, although most programs only include the FILE and WORKING-STORAGE
SECTIONs. The purpose of each of the sections follows:
FILE SECTION: The FILE SECTION is used to define the files that will be used in the program.
There will be on file description (FD) for each file followed by a record description for each different
record format associated with the file. For example:
FD FILE-NAME.
01 RECORD-NAME.
05 FIELD-NAME-1 PIC X(5).
05 FIELD-NAME-2 PIC 99V99.
05 FIELD-NAME-3 PIC X(20).
In the example, the file is named FILE-NAME-1. It is the same file name that was specified in the
SELECT statement for the file. The 01 following the FD is called a record description entry.
Multiple 01 entries can be included if there is more than one applicable record format for the file.
See Data Items for further information on the record description and its subordinate items.
Page 20
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
LINKAGE SECTION: The LINKAGE SECTION is used in a subprogram to define data that will be
passed as arguments to the routine. The structure of the items is as described in the Data Items
section of this tutorial. Each 01 level item in the LINKAGE SECTION should be included in the
PROCEDURE DIVISION USING heading. For example:
PROCEDURE DIVISION USING PARAMETER-1
PARAMETER-2
PARAMETER-3.
In this example, the subprogram would have 3 passed parameters called PARAMETER-1,
PARAMETER-2, and PARAMETER-3. Each of them would be defined as an 01 level item in the
LINKAGE SECTION. The order that the items are defined in the LINKAGE SECTION is
unimportant.
REPORT SECTION: The REPORT SECTION can be used to produce standard control break
driven reports. It is not commonly used.
Procedure Division
The PROCEDURE DIVISION consists of a series of procedures called paragraphs, each designed
to perform a specific function. A paragraph consists of a paragraph name coded in Area A and a
series of procedural statements designed to perform a desired function coded in Area B.
Procedures frequently execute other procedures as indicated in the following example:
0000-MAIN-DRIVER.
PERFORM 1000-INITIALIZATION-ROUTINE.
PERFORM 2000-MAIN-PROCESSING
UNTIL END-OF-FILE.
PERFORM 3000-FINALIZE-ROUTINE.
STOP RUN.
Notice the use of punctuation in the preceding paragraph. Each statement should be a sentence,
that is, it should end with a period unless it is part of a conditional sentence. Sentences which are
continued across multiple lines should be indented on the succeeding lines. Phrases which modify
the behavior of a statement such as UNTIL in the PERFORM statement should be coded on a new
line so that they stand out.
Page 21
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Literals
Following are the main features of Literals:
Literals are Constants
Literals can be Numeric or Non-Numeric
Examples of Literals:
Numeric Non-Numeric
123.345 “COBOL PRG”
9999 “MY NAME”
-100.95
0.54E-78
Page 22
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Description: The DISPLAY statement is used to exhibit data upon the primary output device. The
field(s) listed after DISPLAY is exhibited.
Tips:
Use the DISPLAY statement to exhibit small amounts of data such as error messages.
The chief advantage of exhibiting data with the DISPLAY statement is that no file
needs to be established to use it.
The chief disadvantage of exhibiting data with the DISPLAY statement is that there is
no mechanism to supply carriage control.
DISPLAY – Example
COBOL statement
DISPLAY ‘Return code:’ i-ret-code
DISPLAY ‘Return code:’ i-ret-code
UPON SYSLIST
JCL statement
//SYOUT DD applicable parameters
//SYLIST DD applicable parameters
Default LRECL for SYSOUT is 121 and RECFM is FBA
Page 23
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Display: Rules
Identifier-1 is converted automatically to external format, if required
Negative signed values cause a low-order sign over punch
Pointers are converted to an external PIC 9(10)
INDEX names can’t be specified
Syntax - Format 2
EXIT PROGRAM
Description: The EXIT statement is used to exit routines or programs. Each of the two formats
works slightly differently and is described in the correspondingly numbered area.
If the first format is used, it must be the only entry in a paragraph. The EXIT statement
itself does nothing. The same effect can be accomplished by leaving the paragraph
empty.
The second format is used to exit a subprogram. If the statement is executed from
within a called program, control is returned to the calling program. If the statement is
executed from within a main program, it has the same effect as the EXIT statement,
that is, it does nothing.
Tips:
Do not use the EXIT statement.
Use the EXIT PROGRAM statement only in a called subprogram.
If your system supports the GOBACK statement, use it in place of the EXIT
PROGRAM statement in a called subprogram.
Page 24
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
EXIT – Examples:
EXIT – Example
PROCEDURE DIVISION.
....
PERFORM B1-PROCESS
UNTIL A > 5.
.....
B1-PROCESS.
….
ADD 1 TO A.
IF NOT-VALID-ACTION
PERFORM B1-PROCESS-EXIT
...
B1-PROCESS-EXIT
EXIT.
STOP { RUN
literal-1 }
Description: The STOP statement is used to stop programs. STOP RUN terminates the program.
STOP literal displays the literal and waits for a response before continuing with the next
executable statement.
Tips:
Use the STOP RUN statement to terminate execution of a program.
Do not use the STOP RUN statement in a called subprogram, as it will cause the
termination of the entire run unit. Instead, to terminate execution of a subprogram, use
the EXIT PROGRAM statement
Page 25
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
SOURCE-COMPUTER. IBM-PC.
OBJECT-COMPUTER. IBM-PC.
DATA DIVISION.
PROCEDURE DIVISION.
0000-MAIN.
STOP RUN.
Summary
The structural hierarchy of a COBOL program consists of Divisions, Sections,
Paragraphs, Sentence, and Statements.
The various divisions involved are:
o Identification division
o Environment division
o Data division
o Procedure division
Block of code containing one or more paragraphs are referred to as Sections
Code blocks that are formed based on the logic performed are referred to as
Paragraphs
Sentences and Statements: Sentence consists of one or more statements and is
terminated by a period.
Page 26
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Page 27
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Learning Objectives
After completing this session, you will be able to:
Identify the various data items in a COBOL program
Declare data items
Apply data items
Write COBOL statements using the declared data items
Program Layout
COBOL programs must be written in the COBOL reference format. The below diagram illustrates
the reference format for a COBOL source line.
Page 28
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Picture Clause
The Picture clause is used to specify the type and size of an elementary data item. It consists of
the word PIC or PICTURE followed by the actual picture clause, where the type and size are
specified. The type is specified using a specific character selected from the table below. Each
picture character represents one position in the data item. Different characters may be combined
within the same Picture clause. Multiple occurrences of the same type of character are indicated
by repeating the character or including a repetition factor after the character. For example, three
alphabetic characters may be represented either with the clause PIC AAA or PIC A(3). Typically,
Page 29
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
repetitions of less than four characters are done by repeating the character and repetitions of four
or more characters are done with the number enclosed in parentheses.
Page 30
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
$ Dollar sign Inserts a dollar sign into the first position in the data
item; commonly used for currency
* Asterisk Replaces leading zeros with asterisks; has no effect
on non-zero positions or zeros not in leading
positions; commonly used in check writing
CR Credit Used at the end of a PICTURE clause, the CR will
appear in the position indicated if the item is
negative; will be blank for a positive number
DB Debit Used at the end of a PICTURE clause, the DB will
appear in the position indicated if the item is
negative; will be blank for a positive number
/ Slash Inserts a slash into the data item in this position;
commonly used as a separator in date fields
0 Zero Inserts a zero into the data item in this position; not
commonly used
Floating PICTURE Characters: Certain of the characters above ($, -, +) have the ability to float.
To float a character, simply repeat it in the leading positions of the item, along with separator
commas, if desired. If the item has leading zeros, when it is filled, the leading positions will be filled
with spaces, and the floating character will essentially move up to meet the actual data area. For
example, filling an item with a picture of $$,$$$,$$$.99 with a value of 1047.53 will yield a value of
$1,047.53 with four leading spaces.
SIGN Clause
[SIGN IS {LEADING
TRAILING}]
[SEPARATE CHARACTER]
Specifies the position and mode of representation of the operational sign for a numeric
entry.
The Sign Clause can be specified for a signed numeric data description entry (that is,
one whose PICTURE STRING contains an S)
If a SIGN clause is specified in either an elementary or group entry subordinate to a
group item for which a SIGN clause is specified, the SIGN clause for the subordinate
entry takes precedence for the subordinate entry.
The SEPARATE phrase indicates that sign is stores as separately and not in the
zoned part.
The TRAILING phrase indicates that sign is to be stored in the trailing position
The LEADING phrase indicates that sign is to be stored in the leading position
Page 31
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
l-V1 K 5 0
05 l-V2 PIC S9(3) SIGN LEADING SEPARATE VALUE -250
l-V2 - 2 5 0
05 l-V2 PIC S9 (3) SIGN TRAILING VALUE -250
The value stored internally in 3 characters as
l-V2 2 5 0
VALUE Clause
The VALUE clause is used to set an initial value to the working storage variable.
This can be specified only in the working storage variable.
The VALUE Clause cannot be a part of RECORD DESCRIPTION entry in the FILE
SECTION.
01 W04-G-VAR.
03 W04-X-RUN-TIME PIC X(20) VALUE SPACES.
03 W04-X-PGM-NAME PIC X(08) VALUE 'PXXBB290'.
01 W04-TEMP-J PIC 9(02) VALUE ZEROES.
In the above example the variable W04-X-PGM-NAME is set to an initial value of PXXBB290. The
alphanumeric items can be initialized to Spaces and numeric items can be initialized to Zeros
ZERO:
Alternate Spellings: ZEROS, ZEROES
This figurative constant can be used to load a data item with as many zeros as it takes
to fill the data item. ZEROS may be used to fill data items of any type.
Page 32
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
SPACE:
Alternate Spelling: SPACES
This figurative constant can be used to load a data item with as many spaces as it
takes to fill the data item. SPACES may not be used to fill numeric data items.
LOW-VALUE:
Alternate Spelling: LOW-VALUES
A LOW-VALUE is the lowest possible character in your machine's collating sequence.
On most machines, that would mean that all of the bits in the character are set to 0's.
This figurative constant can be used to load a data item with as many of this value as
it takes to fill the data item. LOW-VALUES may not be used to fill numeric data items.
HIGH-VALUE:
Alternate Spelling: HIGH-VALUES
A HIGH-VALUE is the highest possible character in your machine's collating
sequence. On most machines, that would mean that all of the bits in the character are
set to 1's. This figurative constant can be used to load a data item with as many of this
value as it takes to fill the data item. HIGH-VALUES may not be used to fill numeric
data items.
QUOTE:
Alternate Spelling: QUOTES
A QUOTE is whatever character your compiler uses as a quote. In most COBOLs, this
is the quotation mark. In some COBOLs, this is the apostrophe. This figurative
constant can be used to load a data item with this character. QUOTES may not be
used to fill numeric data items.
ALL literal: The literal is any non-numeric literal. This figurative constant can be used to load a
data item with this character or character string. The character or character string will be repeated
as often as necessary to fill the data item. The ALL literal may not be used to fill numeric data
items.
Literals:
Numeric Literals: Numeric literals can consist of any combination of numeric
characters. No more than 18 total digits are allowed. One decimal point may be
included and a sign (either a plus or minus sign) may be included in the front of the
item. If the sign is not included, the value is assumed to be positive.
Non-Numeric Literals: Non-numeric literals must be enclosed in quotes. Any
character may be included except a quote. If it is necessary for a quote to appear in
the literal, code two quotes adjacent to each other in the literal. They will be
interpreted by the compiler as one quote and only one quote will appear in the
resultant literal. Most COBOLs use the quotation mark for the quote. Some use the
apostrophe. Some COBOLs allow either to be used; in such COBOLs, it possible to
include a quotation mark in the literal by enclosing the literal in apostrophes and to
include an apostrophe in the literal be enclosing the literal in quotation marks.
Page 33
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
10 G PIC 9(10).
In this example, there are three group level items, A, B, and E and there are four elementary items,
C, D, F, and G. The sizes of the elementary items are determined by their picture clauses. See
picture clauses below for more information on this. The sizes of the group items are determined by
the sizes of the elementary items below them. Since B consists of the elementary items C (20
characters) and D (10 characters), B is 30 characters in length. Since E consists of the elementary
items F (5 characters) and G (10 characters), E is 15 characters in length. Since A consists of the
sub-groups B (30 characters) and E (15 characters), A is 45 characters in length.
05 B.
10 C PIC X(20).
10 D PIC X(10).
05 E.
10 F PIC X(5).
10 G PIC 9(10).
Page 34
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
In this example, we could add a line after the last line, to create a new group from items D and F.
To do this we would code:
66 H RENAMES D THRU F.
Following is the last line of the 01 level item. (In this case, the following line defines G)
Level 88 (Condition Name Items): A level 88 item is used to give a name to a condition. Using a
condition name has two primary benefits:
It allows a descriptive name to be assigned to what otherwise might not be an obvious
reason for a test.
If a condition that is subject to change due to conditions beyond the control of the
programmer and that condition is tested multiple places in the PROCEDURE
DIVISION, using the condition name in the PROCEDURE DIVISION instead of the
actual condition allows the programmer maintaining the program to change the values
defining the condition in only one place in the DATA DIVISION rather than having to
hunt down all of the individual occurrences in the PROCEDURE DIVISION.
Sample
05 COMPANY PIC 9(4).
88 DOING-BUSINESS-IN-CALIFORNIA VALUES 3
15
39 THRU 42
76.
To test for a company doing business in California, without the 88-level item, you would have to
code:
IF COMPANY = 3 OR 15 OR 39 OR 40 OR 41 OR 42 OR 76
It would not be apparent to the person reading the code what condition you were testing for. With
the 88 in place, you could code the test like this:
IF DOING-BUSINESS-IN-CALIFORNIA
Anybody reading the code could tell what condition you were testing for and if the check was done
several times throughout the PROCEDURE DIVISION and the list of companies doing business in
California changes, it is only necessary to change the list of values associated with the 88-level
item.
Page 35
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
While the data name associated with an 88-level item may have any value, the 88-level item itself
can only have one of two values, true or false. The item is true if the data item immediately above
the 88 has any of the values associated with the 88-item, otherwise it is false.
88-level items may be associated with either group or elementary items.
Syntax - Format 2:
CORRESPONDING
MOVE { } identifier-1 TO {identifier-2} ...
CORR
Description: The MOVE statement is used to copy data items to other data items. Each of the two
formats works slightly differently and is described in the correspondingly numbered area.
The first format is used to copy a field or value to another field(s). The field or value
listed between MOVE and TO is copied to the value of the field(s) following the TO.
For example in MOVE A TO B, the value in A is copied to B. The value in A is
unchanged. Furthermore, in MOVE C TO E F, the sum or the values in C and D is
moved to the value in E, storing the answer in E and the sum of C and D is also
moved to F storing the value in F. The values in C and D are unchanged.
The second format is used to copy subordinate field(s) of one group to subordinate
field(s) in another. Those subordinate field(s) of the group item identifier-1 are copied
to and those with exactly the same name in the group item identifier-2. The names of
the subordinate items must be spelled exactly the same way in both groups to qualify
to participate in the move.
Tips:
If the receiving field is edited, any editing required will be done at the time of the
MOVE.
If the receiving field is unedited and the sending field is edited, the field will be de-
edited at the time of the MOVE.
If the sending field is shorter than the receiving field:
o Numeric fields are padded on the left with zeros.
o Non-numeric fields are padded on the right with spaces.
If the sending field is longer than the receiving field:
o Numeric fields are truncated on the left.
o Non-numeric fields are truncated on the right.
Page 36
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Page 37
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Quite often it is required to move some of the data item of one group to some other data item of
other group. If the names of the corresponding data items are distinct then separate MOVE
statements have to be used. But if the corresponding data items have identical names, then
instead of separate MOVE statements, MOVE CORRESPONDING can be used.
Example:
PAY-REC.
02 ID-NUMBER PIC 9(5).
02 NAME PIC X(25).
02 DEPARTMENT PIC X(20).
02 BASIC-PAY PIC 9999V99.
02 FILLER PIC X(24).
PRINT-REC.
02 FILLER PIC X(5).
02 ID-NUMBER PIC Z(5).
02 FILLER PIC X(5).
02 NAME PIC X(25).
02 FILLER PIC X(5).
02 DEPARTMENT PIC X(20).
02 FILLER PIC X(5).
02 BASIC-PAY PIC ZZZZ.99
02 FILLER PIC X(5).
02 DEDUCTIONS PIC ZZZZ.99.
02 FILLER PIC X(5).
02 ALLOWANCES PIC ZZZZ.99
02 FILLER PIC X(5).
02 NET-PAY PIC ZZZZ.99
In the earlier example the ID-NUMBER, NAME, DEPARTMENT, BASIC-PAY of PAY-REC will be
moved the same data item of PRINT-REC.
Page 38
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Syntax - Format 2:
THROUGH
PERFORM [procedure-name-1 [{ } procedure-name-2 ] ]
THRU
{ identifier-1
integer-1 } TIMES [imperative-statement-1 END-PERFORM]
Syntax - Format 3:
THROUGH
PERFORM [procedure-name-1 [{ } procedure-name-2 ] ]
THRU
BEFORE
[ WITH TEST { }] UNTIL condition-1
AFTER
[imperative-statement-1 END-PERFORM]
Syntax - Format 4:
Description: The PERFORM statement is used to execute code. There are two different modes of
operation.
Page 39
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
The first mode is used to execute code in another area of the program and is invoked by
mentioning a procedure or paragraph name. In this mode, the code in the other paragraph(s) is
executed and control is returned to the statement following the PERFORM statement.
The second mode is called an in-line PERFORM, because the code to be executed is actually
coded in place inside of the PERFORM statement. In the second mode, the code which is
executed is that which lies between the PERFORM and the END-PERFORM.
Each of the four formats works slightly differently and is described in the correspondingly
numbered area.
The first format is used to execute the referenced code one time.
The second format is used to execute the referenced code multiple times. The actual
number of times is indicated by identifier-1 or integer-1.
The third format is also used to execute the referenced multiple times. The actual
number of times is dependent upon condition-1. The code will be repeatedly executed
until condition-1 is true. The condition will be tested before the code is actually tested
unless the WITH TEST AFTER phrase is included.
The fourth format is used to execute the referenced multiple times with the actual
number of times being dependent upon a condition like the third format. The primary
difference between format 3 and format 4 is the VARYING phrase, which is used to
count in a variable during the repetitions. The VARYING variable is set to the FROM
value before the referenced code is executed. Before each subsequent pass, the
VARYING variable is incremented by the amount of the BY value. The optional
AFTER phrase may be included to vary the value of an additional variable. If this
option is used, AFTER variable will be incremented through its entire cycle for each
time the VARYING variable is cycled.
Tips:
Use the PERFORM statement to access code which needs to be executed from more
than one location.
Use the PERFORM statement to structure your code. Make a main routine that
PERFORMs other routines which in turn PERFORM other routines which themselves
PERFORM other routines until the level of complexity of the PERFORMed routines is
easily comprehended.
Use the WITH TEST AFTER option to force the code to be PERFORMed at least
once.
Use the VARYING ... AFTER option to pass through all the entries in multiple
dimensional tables.
If the number of lines in the routine is relatively small, use an in-line PERFORM
instead of PERFORMing a separate paragraph. The next programmer will appreciate
not having to look all through the program to find the one or two lines of code in the
paragraph you PERFORMed.
Page 40
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
PERFORM (TIMES):
Example
PERFORM B1-PROCESS
THRU B1-PROCESS-EXIT
10 TIMES
In this example the number of times perform statement is going to be executed is predetermined.
Hence this perform statement will be executed 10 times.
PERFORM I-CNT TIMES
WRITE OUT-REC FROM I-ERR-REC (I-CNT)
SUBTRACT 1 FROM I-CNT
END-PERFORM
In this example the number of times the perform statement is to be executed is not
predetermined. It depends on value of the variable I-CNT.
If I-CNT is 0 or negative, this perform statement is not all executed
Page 41
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Flowchart:
Enter
True
Condition
EXIT
False
Executable statements in
the perform paragraph
PERFORM (UNTIL):
Example
MOVE 10 TO I-CNT
PERFORM UNTIL I-CNT = ZERO
WRITE OUT-REC FROM I-ERR-REC (I-
CNT)
SUBTRACT 1 FROM I-CNT
END-PERFORM
In the above example, the WRITE and SUBTRACT statements will be executed until the I-CNT
becomes zero. Here perform will be executed 10 times.
Page 42
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Changing the values of identifiers and/or index-names in the VARYING, FROM, and
BY phrases during execution changes the number of times the procedures are
executed.
EXAMPLE
PERFORM PROC1 THRU PROC2
VARYING I FROM 1 BY 1 UNTIL I > 50
AFTER J FROM 1 BY 1 UNTIL J > 10
In the above example the PROC-1 to PROC-2 will be executed 500 times.
First with I as 1 and J varying from 1 to 10 in step of 1, then I as 2 and again J varying
from 1 to 10 and so on. Every time I changes value, J must vary from 1 to 10.
Each time the loop varying J is completed, J is initialized before changing the value of
I.
Thus after this perform statement is executed, value of I will 51 and that of J will 1 and
not 11.
Enter
Set Identifier-1 to
initial value
True
Cond- Exi
1 t
False
Execute the
imperative
statement in the
perform paragraph
Add increment to
indentifier-1
Page 43
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Enter
True
Cond- Exit
1
False
Cond- True
2
Execute the
imperative
statement in the
perform paragraph
Page 44
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Try It Out
Problem Statement:
Try to display “HELLO WORLD” in the SYSOUT of the program from a sub-para called from the
main para. Also the display should not contain any hard-coded string, instead use variables
Code:
WORKING-STORAGE SECTION.
* INPUT VARIABLES
01 W01-TEST-STRING PIC X(50).
PROCEDURE DIVISION.
*================================================================*
* MAIN PARA - CALLS OTHERS PARA FOR PROCESSING
*================================================================*
0000-MAIN-PARA.
PERFORM 1000-INITIALIZE-PARA
THRU 1000-INITIALIZE-PARA-EXIT.
STOP RUN.
0000-EXIT.
EXIT.
*================================================================*
* INITIALIZE PARA - DISPLAYS ‘HELLO WORLD’
*================================================================*
1000-INITIALIZE-PARA.
*----MOVES & DISPLAYS HELLO WORLD
MOVE 'HELLO WORLD' TO W01-TEST-STRING.
DISPLAY W01-TEST-STRING.
1000-INITIALIZE-PARA-EXIT.
EXIT.
Refer File Name: Handout_Example_Code.txt under heading ‘Code for Session #6’ to obtain
soft copy of the program code
How It Works:
There are no Inputs (or) Outputs to this module
The first statement calls the INITIALIZE Para
In the INITIALIZE Para, the display statement is executed for displaying the
PROGRAM SCOPE in the Job Dump (SYSOUT)
The last statement “STOP RUN” indicates the end of execution.
It is Good Practice to provide informative comments.
Page 45
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Summary
Program Layout consists of:
o Sequence Number Area (Position 01-06)
o Comments / Continuation (Position 07)
o Area A (Position 08-11)
o Area B (Position 12-72)
o Program Identification (Position 73-80)
Identifiers in Variable Declaration are:
o X for Any character
o 9 for Numeric character
o A for Alphabetic character
Variable declaration examples: String & Numeric
MOVE and PERFORM statements: Illustration with Code example and Result
Page 46
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Learning Objectives
After completing this session, you will be able to:
Perform arithmetic operations in COBOL program
Execute the arithmetic operations through statement involving clauses and
expressions
Arithmetic Expressions
Arithmetic Expressions may consist of any of the following:
An identifier described as a numeric elementary item.
A numeric literal
Identifiers and literals separated by arithmetic operators
Two arithmetic expressions separated by an arithmetic operator.
An arithmetic expression enclosed in parentheses
Arithmetic Operators
Following are the arithmetic operators:
BINARY: + - * / **
UNARY: + -
Precedence
Unary
Exponentiation
Multiplication and Division
Addition and Subtraction
Arithmetic Statements
Arithmetic statements are of five kinds:
ADD
SUBTRACT
MULTIPLY
DIVIDE
COMPUTE
Page 47
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Syntax - Format 2:
identifier- identifier-
... GIVING {identifier-3
ADD { 1 } {2 }
TO [ROUNDED]}...
literal-1 literal-2
[ON SIZE ERROR imperative-statement-1]
[NOT ON SIZE ERROR imperative-statement-2]
[END-ADD]
Syntax - Format 3:
CORRESPONDING
ADD { } identifier-1 TO identifier-2 [ROUNDED]
CORR
[ON SIZE ERROR imperative-statement-1]
[NOT ON SIZE ERROR imperative-statement-2]
[END-ADD]
Description: The ADD statement is used to add numeric items together. Each of the three formats
works slightly differently and is described in the correspondingly numbered area.
The first format is used to add field(s) or value(s) to another field. The field(s) or
value(s) listed between ADD and TO are summed and added to the value of the
field(s) following the TO, where the answer is stored.
o For example, in ADD A TO B, the value in A is added to the value in B and the
result is stored in B. The value in A is unchanged.
o Furthermore, in ADD C D TO E F, the sum of the values in C and D is added to
the value in E, storing the answer in E and the sum of C and D is also added to F
storing the value in F. The values in C and D are unchanged.
The second format is used to add field(s) or value(s) to one another, storing the
answer in a different field. The field(s) or value(s) listed between ADD and GIVING are
added and stored in the field following the field(s) following the GIVING. For example,
in ADD A TO B GIVING C, the value in A is added to the value in B and the result is
stored in C. The values in A and B are unchanged.
The third format is used to add subordinate field(s) of one group to subordinate field(s)
in another, storing the answer in those fields. Those subordinate field(s) of the group
item identifier-1 are added to and stored in those with exactly the same name in the
group item identifier-2. The names of the subordinate items must be spelled exactly
the same way in both groups to qualify to participate in the addition.
Page 48
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Tips:
The fields to be added must have numeric pictures, that is, they can only have the
characters 9, S, and V in their PIC clauses.
Receiving fields may be either numeric or numeric edited fields.
Use the SIZE ERROR clause to detect field overflow on the receiving field.
In all formats, the mathematically correct results are computed, but if the receiving
field is too short in either the integer or decimal portion, the result will be truncated, the
integer on the left and the decimal on the right. Including the ROUNDED phrase will
result the answer field being rounded instead of truncating. Rounding is always done
in the least significant portion of the answer.
ADD Corresponding:
For example, if two data hierarchies are defined as follows:
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.
05 ITEM-2.
10 ITEM-A PIC 99.
10 ITEM-B PIC +9V9.
10 ITEM-C PIC A(4).
10 ITEM-D PIC 9(4).
10 ITEM-E PIC 9(9) USAGE COMP.
10 ITEM-F USAGE INDEX.
Then, if ADD CORR ITEM-2 TO ITEM-1(X) is specified, ITEM-A and ITEM-A(X), ITEM-B and
ITEM-B(X), and ITEM-E and ITEM-E(X) are considered to be corresponding and are added
together. ITEM-C and ITEM-C(X) are not included because they are not numeric. ITEM-D and
ITEM-D(X) are not included because ITEM-D(X) includes a REDEFINES clause in its data
description. ITEM-F and ITEM-F(X) are not included because they are defined as USAGE IS
INDEX. Note that ITEM-1 is valid as either identifier-1 or identifier-2.
If any of the individual operations in the ADD CORRESPONDING statement produces a size error
condition, imperative-statement-1 in the ON SIZE ERROR phrase is not executed until all of the
individual additions are completed.
Page 49
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
the arithmetic operation, the imperative statement in the ON SIZE ERROR phrase is
executed, control is transferred to the end of the arithmetic statement, and the NOT
ON SIZE ERROR phrase, if specified, is ignored.
If the NOT ON SIZE ERROR phrase has been specified and, after execution of an
arithmetic operation, a size error condition does not exist, the NOT ON SIZE ERROR
phrase is executed.
For ADD CORRESPONDING and SUBTRACT CORRESPONDING statements, if an
individual arithmetic operation causes a size error condition, the ON SIZE ERROR
imperative statement is not executed until all the individual additions or subtractions
have been completed.
If the ROUNDED phrase is specified, rounding takes place before size error checking.
ROUNDED Phrase:
After decimal point alignment, the number of places in the fraction of the result of an
arithmetic operation is compared with the number of places provided for the fraction of
the resultant identifier.
When the size of the fractional result exceeds the number of places provided for its
storage, truncation occurs unless ROUNDED is specified. When ROUNDED is
specified, the least significant digit of the resultant identifier is increased by 1
whenever the most significant digit of the excess is greater than or equal to 5.
ADD – Examples:
ADD A BTO
ADD 1 BTO
ADD A TO
B ROUNDED
ADD A TO
B, C
ADD A TO
B ROUNDED
C ROUNDED
ADD A TO B ROUNDED, C
ON SIZE ERROR
MOVE 1 TO ERR-FLAG
ADD A, B, C, D TO X, Y, Z
ADD A , B, C, D TO E GIVING X, Y
Page 50
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Syntax - Format 2:
identifier- identifier-
... GIVING identifier-3
SUBTRACT { 1 } {2 }
FROM [ROUNDED]
literal-1 literal-2
[ON SIZE ERROR imperative-statement-1]
[NOT ON SIZE ERROR imperative-statement-2]
[END-SUBTRACT]
Syntax - Format 3:
CORRESPONDING
SUBTRACT { } identifier-1 FROM identifier-2 [ROUNDED]
CORR
ON SIZE ERROR imperative-statement-1]
[NOT ON SIZE ERROR imperative-statement-2]
[END-SUBTRACT]
Description: The SUBTRACT statement is used to subtract numeric items. Each of the three
formats works slightly differently and is described in the correspondingly numbered area.
The first format is used to subtract field(s) or value(s) from another field. The field(s) or
value(s) listed between SUBTRACT and FROM are summed and subtracted from the
value of the field(s) following the FROM. The answer is stored in the individual field.
For example in SUBTRACT A FROM B, the value in A is subtracted from the value in
B and the result is stored in B. The value in A is unchanged. Furthermore, in
SUBTRACT C D FROM E F, the sum of the values in C and D is subtracted to the
value in E, storing the answer in E and the sum of C and D is also subtracted from F,
storing the value in F. The values in C and D are unchanged.
The second format is used to subtract field(s) or value(s) from one another, storing the
answer in a different field. The field(s) or value(s) listed between SUBTRACT and
GIVING are added and stored in the field following the field(s) following the GIVING.
For example, in SUBTRACT A FROM B GIVING C, the value in A is subtracted to the
value in B and the result is stored in C. The values in A and B are unchanged.
The third format is used to subtract subordinate field(s) of one group from subordinate
field(s) in another, storing the answer in those fields. Those subordinate field(s) of the
group item identifier-1 are subtracted from and stored in those with exactly the same
name in the group item identifier-2. The names of the subordinate items must be
spelled exactly the same way in both groups to qualify to participate in the subtraction.
Tips:
Page 51
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
The fields to be subtracted must have numeric pictures, that is, they can only have the
characters 9, S, and V in their PIC clauses.
Receiving fields may be either numeric or numeric edited fields.
Use the SIZE ERROR clause to detect field overflow on the receiving field.
In all formats, the mathematically correct results are computed, but if the receiving
field is too short in either the integer or decimal portion, the result will be truncated, the
integer on the left and the decimal on the right. Including the ROUNDED phrase will
result the answer field being rounded instead of truncating. Rounding is always done
in the least significant portion of the answer.
SUBTRACT – Examples:
SUBTRACT 1 FROM A
SUBTRACT A FROM B
SUBTRACT A B FROM C D
SUBTRACT A B FROM C GIVING D
SUBTRACT A FROM B
GIVING CROUNDED
SUBTRACT A FROM B
ON SIZE ERROR
MOVE 1 TO ERROR-FLAG
MULTIPLY { identifier-1
literal-1 } ... BY {identifier-2 [ROUNDED]} ...
[ON SIZE ERROR imperative-statement-1]
[NOT ON SIZE ERROR imperative-statement-2]
[END-MULTIPLY]
Syntax - Format 2:
identifier- identifier-
...
MULTIPLY { 1
literal-1
} BY { 2
literal-2
} GIVING {identifier-3
[ROUNDED]}...
Description: The MULTIPLY statement is used to multiply numeric items together. Both formats
work slightly differently and each is described in the correspondingly numbered area.
The first format is used to multiply a field or value by another field or value. The
product of the field(s) or value(s) listed between MULTIPLY and BY is computed and
multiplied by the value of the field(s) following the BY. The answer is stored in the
individual field. For example, in MULTIPLY A BY B, the value in A is multiplied by the
value in B and the result is stored in B. The value in A is unchanged. Furthermore, in
Page 52
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Tips:
The fields to be multiplied must have numeric pictures, that is, they can only have the
characters 9, S, and V in their PIC clauses.
Receiving fields may be either numeric or numeric edited fields.
Use the SIZE ERROR clause to detect field overflow on the receiving field.
In both formats, the mathematically correct results are computed, but if the receiving
field is too short in either the integer or decimal portion, the result will be truncated, the
integer on the left and the decimal on the right. Including the ROUNDED phrase will
result the answer field being rounded instead of truncating. Rounding is always done
in the least significant portion of the answer
MULTIPLY – Examples:
MULTIPLY 5 BY A
MULTIPLY 5 BY A ROUNDED
MULTIPLY A BY B
MULTIPLY A BY B GIVING C D
MULTIPLY A BY B ON SIZE ERROR
MOVE 1 TO ERROR-FLAG
MULTIPLY A BY B GIVING C
ON SIZE ERROR
MOVE 1 TO ERROR-FLAG
Page 53
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
DIVIDE { identifier-1
literal-1 } ... INTO {identifier-2 [ROUNDED]} ...
[ON SIZE ERROR imperative-statement-1]
[NOT ON SIZE ERROR imperative-statement-2]
[END-DIVIDE]
Syntax - Format 2:
identifier- identifier-
DIVIDE { 1
literal-1
} INTO { 2
literal-2
} GIVING {identifier-3
[ROUNDED]}...
Syntax - Format 3:
identifier- identifier-
DIVIDE { 1
literal-1
} { BY 2
literal-2
} GIVING {identifier-3
[ROUNDED]}...
Syntax - Format 4:
identifier- identifier- GIVING identifier-3
DIVIDE { 1
literal-1
} INTO { 2
literal-2
} [ROUNDED] REMAINDER
identifier-4
[ON SIZE ERROR imperative-statement-1]
[NOT ON SIZE ERROR imperative-statement-2]
[END-DIVIDE]
Syntax - Format 5:
identifier- identifier-
DIVIDE { 1
literal-1
} BY { 2
literal-2
} GIVING identifier-3 [ROUNDED]
REMAINDER identifier-4
Description: The DIVIDE statement is used to divide numeric items together. Both formats work
slightly differently and each is described in the correspondingly numbered area.
Page 54
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
The first format is used to divide a field(s) or value(s) by another field or value. The
field or value listed between DIVIDE and INTO is divided into the value of the field(s)
following the INTO. The answer is stored if the individual field. For example, in DIVIDE
A INTO B, the value in A is divided into the value in B and the result is stored in B. The
value in A is unchanged. Furthermore, in DIVIDE C INTO D E, the value in C is
divided into the value in D, storing the answer in D; the value of C is also divided into
E, storing the value in E. The value in C is unchanged.
The second format is used to divide field(s) or value(s) by one another, storing the
answer in a different field. The field(s) or value(s) listed between DIVIDE and GIVING
are divided and stored in the field following the field(s) following the GIVING. For
example, in DIVIDE A INTO B GIVING C, the value in A is divided into the value in B
and the result is stored in C. The values in A and B are unchanged.
The third format is also used to divide field(s) or value(s) by one another, storing the
answer in a different field. The field(s) or value(s) listed between DIVIDE and GIVING
are divided and stored in the field following the field(s) following the GIVING. For
example, in DIVIDE A BY B GIVING C, the value in A is divided by the value in B and
the result is stored in C. The values in A and B are unchanged.
The fourth format is used to divide field(s) or value(s) by one another, storing the
answer in a different field. The field(s) or value(s) listed between DIVIDE and GIVING
are divided and stored in the field following the field(s) following the GIVING. For
example, in DIVIDE A INTO B GIVING C REMAINDER D, the value in A is divided into
the value in B and the results stored in C with the remainder being stored in D. The
values in A and B are unchanged.
The fifth format is also used by divide field(s) or value(s) by one another, storing the
answer in a different field. The field(s) or value(s) listed between DIVIDE and GIVING
are divided and stored in the field following the field(s) following the GIVING. For
example, in DIVIDE A BY B GIVING C REMAINDER D, the value in A is divided by
the value in B and the result is stored in C with the remainder being stored in D. The
values in A and B are unchanged.
Tips:
The fields to be divided must have numeric pictures, that is, they can only have the
characters 9, S, and V in their PIC clauses.
Receiving fields may be either numeric or numeric edited fields.
Use the SIZE ERROR clause to detect field overflow on the receiving field.
In all formats, the mathematically correct results are computed, but if the receiving
field is too short in either the integer or decimal portion, the result will be truncated, the
integer on the left and the decimal on the right. Including the ROUNDED phrase will
result the answer field being rounded instead of truncating. Rounding is always done
in the least significant portion of the answer
DIVIDE – Examples:
BEFORE AFTER
A B C A B C
DIVIDE A INTO B 2 10 - 2 5 -
DIVIDE A INTO B 2 9 - 2 5 -
ROUNDED
DIVIDE A INTO B C 2 10 14 2 5 7
Page 55
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
DIVIDE A INTO B 2 10 - 2 10 5
GIVING C
DIVIDE 2 INTO A 2 - - 2 1 1
GIVING B C
DIVIDE A BY B 6 2 - 6 2 3
GIVING C
DIVIDE A BY 5 8 - - 8 1 3
GIVING B REMAINDER
C
Description: The COMPUTE statement is used to evaluate arithmetic formulas. The formula is
evaluated and the result is stored in the identifier(s) between COMPUTE and =.
The format for the formula is a standard algebraic expression with addition,
subtraction, multiplication, and division represented as +, -, *, and /. The
exponentiation operator is **.
When evaluating the formula, standard rules of mathematical precedence apply, i.e.
exponentiation first, then multiplication and division at equal precedence, then addition
and subtraction at equal precedence. If some other order is preferred, operations may
be enclosed in parentheses to give them precedence.
Tips:
If only one mathematical operation is to be performed, use the statement that performs
that operation (ADD, SUBTRACT, MULTIPLY, or DIVIDE). Reserve the COMPUTE
statement for formulas or exponentiation, since it has no separate statement
associated with it.
Receiving fields may be either numeric or numeric edited fields.
Use the SIZE ERROR clause to detect field overflow on the receiving field.
In all formats, the mathematically correct results are computed, but if the receiving
field is too short in either the integer or decimal portion, the result will be truncated, the
integer on the left and the decimal on the right. Including the ROUNDED phrase will
result the answer field being rounded instead of truncating. Rounding is always done
in the least significant portion of the answer.
Page 56
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
COMPUTE – Examples:
COMPUTE PROFIT = PRICE - COST,
COMPUTE A = B + C * 2.
Description: The INITIALIZE statement is used to initialize data items. Data items are initialized
according to their type:
Alphabetic and alphanumeric items are initialized to spaces.
Numeric items are initialized to zeros.
For group items, the subordinate elementary items are initialized depending on their
individual data types. Only named items are initialized.
The REPLACING phrase can be used to initialize data items to different values other
than the default SPACES or ZEROS.
Tips:
Use the initialize statement instead of moving ZEROS or SPACES to a group. That
way, each subordinate item will be set to an appropriate value.
Notice that unnamed and FILLER items are not initialized. This allows the variable
portion of a detail line, for example, to be initialized without the constant values
inserted into the unnamed fields being affected.
INITIALIZE - Example
01 A.
02 A1 PIC 9(5).
02 A2 PIC X(4).
02 A3 PIC 9(3).
02 A4 PIC Z(3)9.99.
INITIALIZE A.
In the above statement A1 and A3 will be initialized to zeroes and A2
and A4 will be initialized to spaces.
Page 57
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
INITIALIZE Rules:
Category of Id-2 should be compatible that of CORR REPLACING
Whether identifier-1 references an elementary or group item, all operations are
performed as if a series of MOVE statements had been written, each of which had an
elementary item as a receiving field.
Same Category can’t be repeated
If the REPLACING phrase is specified:
o If identifier-1 references a group item, any elementary item within the data item
referenced by identifier-1 is initialized only if it belongs to the category specified in
the REPLACING phrase.
o If identifier-1 references an elementary item, that item is initialized only if it
belongs to the category specified in the REPLACING phrase.
All such elementary receiving fields, including all occurrences of table items within
the group, are affected, with the following exceptions:
o Index data items
o Data items defined with USAGE IS POINTER
o Elementary FILLER data items
o Items that are subordinate to identifier-1 and contain a REDEFINES clause or any
items subordinate to such an item. (However, identifier-1 can contain a
REDEFINES clause or be subordinate to a redefining item.)
The areas referenced by identifier-1 are initialized in the order (left to right) of the
appearance of identifier-1 in the statement. Within a group receiving field, affected
elementary items are initialized in the order of their definition within the group.
SPACE is implied source for Alpha, Alpha-numeric and Alpha-numeric edited
ZERO is implied source for Numeric and Numeric edited
For Group initialize the following will not participate:
o Index variables
o Pointer variables
o Filler
o Redefines
o Elementary items that are not of category mentioned in REPLACING
Syntax - Format 2:
DATE
ACCEPT identifier-1 FROM
{ DAY
DAY-OF-WEEK
TIME
}
Page 58
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Description: The ACCEPT statement is used to acquire data from the primary input device or
various system fields. Each of the two formats works slightly differently and is described in the
correspondingly numbered area.
The first format is used to accept data from the primary input or other specified device.
The field(s) listed after ACCEPT are loaded
The second format is used to accept one of various system value(s). Each of the items
to be accept has a different format. They are:
o DATE (YYMMDD): Two-digit year of century followed by two-digit month of year
followed by two-digit day of month. (Gregorian Date)
o DAY (YYDDD): Two-digit year of century followed by three-digit day of year.
(Julian Date)
o DAY-OF-WEEK (D): One-digit day of week, where Monday is 1, Tuesday is 2, etc.
o TIME (HHMMSSHH): Two-digit hour of day followed by two digit minute of an hour
followed by two-digit second of minute followed by two digit hundredths of a
second. (Twenty-four hour clock)
Tips:
Use the ACCEPT statement to acquire small amounts of data such as parameters to
be entered at runtime.
The chief advantage of acquiring data with the ACCEPT statement is that no file
needs to be established to use it.
The chief disadvantage of acquiring data with the ACCEPT statement is that there is
no mechanism to recognize end of file.
Many COBOLs have added enhancements to allow access to a four-digit year due to
the Y2K problem. Check your system manual for details.
ACCEPT – Example
COBOL statement
ACCEPT in-parm
ACCEPT in-parm FROM card
JCL statement:
//SYSIN DD applicable parameters
LRECL of DCB parameter can be up to a
max of 256.
Try It Out
Problem Statement:
Declare two numeric variables and assign values from JCL to them using ACCEPT Statement.
Perform all the arithmetic operations on the variables
Page 59
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Code:
*================================================================*
* PROCESS PARA - PROCESS INPUTS
*================================================================*
2000-PROCESS-INPUT.
ADD W01-INPUT-01 TO W01-INPUT-02 GIVING W02-ADD.
SUBTRACT W01-INPUT-01 FROM W01-INPUT-02 GIVING W02-SUB.
MULTIPLY W01-INPUT-01 BY W01-INPUT-02 GIVING W02-MUL.
DIVIDE W01-INPUT-01 BY W01-INPUT-02 GIVING W02-DIV.
DISPLAY '--ARITHMATIC OPERATIONS DEMO RESULTS--'.
DISPLAY W01-INPUT-01 ' + ' W01-INPUT-02 ' = ' W02-ADD.
DISPLAY W01-INPUT-01 ' - ' W01-INPUT-02 ' = ' W02-SUB.
DISPLAY W01-INPUT-01 ' * ' W01-INPUT-02 ' = ' W02-MUL.
DISPLAY W01-INPUT-01 ' / ' W01-INPUT-02 ' = ' W02-DIV.
2000-PROCESS-INPUT-EXIT.
EXIT.
*================================================================*
* PROCESS PARA - PROCESS INPUTS
*================================================================*
3000-COMPUTE-INPUT.
INITIALIZE W02-ADD, W02-SUB, W02-MUL, W02-DIV.
DISPLAY '------DATA AFTER INITIALIZATION--------'.
DISPLAY 'W02-ADD = ' W02-ADD.
DISPLAY 'W02-SUB = ' W02-SUB.
DISPLAY 'W02-MUL = ' W02-MUL.
DISPLAY 'W02-DIV = ' W02-DIV.
COMPUTE W02-ADD = W01-INPUT-01 + W01-INPUT-02.
COMPUTE W02-SUB = W01-INPUT-01 - W01-INPUT-02.
COMPUTE W02-MUL = W01-INPUT-01 * W01-INPUT-02.
COMPUTE W02-DIV = W01-INPUT-01 / W01-INPUT-02.
DISPLAY '--ARITHMATIC OPERATIONS DEMO RESULTS--'.
DISPLAY '------------USING COMPUTE-------------'.
DISPLAY W01-INPUT-01 ' + ' W01-INPUT-02 ' = ' W02-ADD.
DISPLAY W01-INPUT-01 ' - ' W01-INPUT-02 ' = ' W02-SUB.
DISPLAY W01-INPUT-01 ' * ' W01-INPUT-02 ' = ' W02-MUL.
DISPLAY W01-INPUT-01 ' / ' W01-INPUT-02 ' = ' W02-DIV.
3000-COMPUTE-INPUT-EXIT.
EXIT.
Refer File Name: Handout_Example_Code.txt under heading ‘Code for Session #8’ to obtain
soft copy of the program code
Page 60
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
How It Works:
The job accepts the inputs from the JCL from the SYSIN using the ACCEPT
statement.
The output of the calculations is displayed in the JCL SYSOUT using the DISPLAY
statements.
The initial para performs the operations using ADD, SUBTRACT, MULTIPLY, DIVIDE.
The subsequent para performs the same logic using COMPUTE after initializing the
display variables
The last statement “STOP RUN” indicates the end of execution.
Summary
The basic arithmetic operation statements are ADD, SUBTRACT, MULTIPLY, and
DIVIDE.
The COMPUTE statement is used to handle complicated calculations.
The INITIALIZE statement is used to initialize variables.
Page 61
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Learning Objectives
After completing this session, you will be able to:
Execute the various string operations in a COBOL program
Perform string functions to extract a part of a long string
STRING {{ identifier-1
literal-1 } ... DELIMITED BY {
identifier-2
literal-2 }} ...
INTO identifier-3
[WITH POINTER identifier-4]
[ON OVERFLOW imperative-statement-1]
[NOT ON OVERFLOW imperative-statement-2]
[END-STRING]
Description:
The STRING statement is used to concatenate non-numeric items together. Any
number of items can be concatenated. Entire or partial strings may be concatenated.
To use the entire string, delimit it by size. To use only a portion of a string, delimit it by
whatever character indicates the end of the data you want to concatenate.
The POINTER clause can be used to start in a position other than 1. For example, if
the POINTER variable has a value of 3, character 1 and 2 of the receiving item will
remain unchanged, and the stringing operation will proceed from the third character of
the receiving field. As each character is inserted into the receiving field, the value of
the POINTER variable will be incremented, so that the POINTER variable may be
used to STRING in more values where the previous STRING operation left off.
Only as much of the value in the receiving field will be changed as is necessary to hold
the newly assembled string, for example, in the statement
STRING A B DELIMITED BY SIZE INTO C.
If A is a one character string with a value of A and B is a one character string with a
value of B and C is a five character string with an original value of CCCCC, after the
STRING statement is executed, C will have a value of ABCCC.
STRING – Example:
05 FIELD-1 PIC X(04) VALUE ‘ABCD’.
05 FIELD-2 PIC X(06) VALUE ‘MA IN ‘.
05 FIELD-3 PIC X(09) VALUE ‘121,34,56’.
05 FIELD-4 PIC X(14) VALUE SPACES.
Page 62
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
In the above example, FIELD-1 does not contain any delimiters, all 4 characters are
moved to FIELD-4
First 2 characters of FIELD-2 are moved to FIELD-4 as third character is the delimiter
First 3 characters of FIELD-3 are moved to FIELD-4 as 4th character is the delimiter
STRING Rules:
Receiving fields must not be:
o Edited field
o With Justified clause
o With reference modification
Pointer variable must be:
o Elementary and Numeric
o Large enough to hold max length of receiving field
ON OVERFLOW executed when pointer Value <= 0 or exceeds max length of
receiving field
} OR
UNSTRIN identifie
DELIMITE identifie identifie } ..
G r-1 [ D BY { r-2 [ALL { r-3
. ]
[ALL] literal-1 ] literal-2 ]
[
INTO {identifier-4 [DELIMITER IN identifier-5] [COUNT IN identifier-
6]}...
[WITH POINTER identifier-7]
[TALLYING IN identifier-8]
[ON OVERFLOW imperative-statement-1]
[NOT ON OVERFLOW imperative-statement-2]
[END-UNSTRING]
Description:
The UNSTRING statement is used to parse individual items from within a single string.
Any number of items may be parsed. Entire or partial strings may be parsed. As many
items as are provided as INTO operands will be parsed.
The POINTER clause can be used to start in a position other than 1. For example, if
the POINTER variable has a value of 3, character 1 and 2 of the string will not be
included, and the unstringing operation will proceed from the third character. As each
character is inserted into a receiving field, the value of the POINTER variable will be
incremented, so that the POINTER variable may be used to UNSTRING more values
from where the previous UNSTRING operation left off.
Page 63
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
The COUNT phrase can be used to determine the length of any parsed string.
Only as much of the values in the receiving field will be changed as is necessary to
hold the newly parsed string, for example, in the statement
UNSTRING A DELIMITED BY SPACES INTO B C.
If A is a five character unstring with a value of "A A A" and B is a two character string
with an original value of BB and C is a two character string with an original value of
CC, after the UNSTRING statement is executed, B will have a value of AB and C will
have a value of AC.
Tips:
The operands should be non-numeric.
The POINTER and COUNT operands, if any, must be positive integers that are their
pictures should contain only 9's.
INITIALIZE the receiving items before the UNSTRING, to remove unwanted
characters that may be left from a prior operation.
Use the OVERFLOW clause to detect field overflow on the receiving field(s).
identifie
BEFORE INITIA
CHARACTERS [{ } { r-3 }] ...
AFTER L
literal-1
..
{ identifi identif }
.
ALL er-4 BEFORE ier-5 .. ..
{ }{{ }[{ } INITIAL { }] }
LEADING literal- AFTER literal . .
2 -3
Page 64
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Syntax - Format 2:
INSPECT identifier-6 REPLACING
identif
identifier
CHARACT BEFORE INITIA ier-8
{ -7 }[{ } { }] ...
ERS BY AFTER L literal
literal-4
-5 .
{ ALL ident } .
identifi .
LEAD identifie ifier
er-9 BEFORE INITI } .. ..
{ ING } { } BY { r-10 } [{ } { -11 }
literal- AFTER AL ] . .
FIRS literal-7 liter
6
T al-8
Syntax - Format 3:
INSPECT identifier-12 TALLYING identifier-13 FOR
identifier
CHARACTER BEFORE INITIA }
[{ } { -14 ...
S AFTER L ] ...
literal-9
{ } REPLACIN
ALL identifier identifier G
}{ }[ BEFORE } ..
{ LEADIN -15 } INITIAL { -16 } ..
{ { AFTER ] .
G literal-10 literal-11 .
identifier- identifier
CHARACTERS BEFORE INITIA }
{ 17 }[{ } { -18 ...
BY AFTER L ]
literal-12 literal-13
..
{ }
ALL .
identifier identifier BEFOR identifier
LEADIN B } .. ..
{ } { -19 } { -20 } [{ E } INITIAL { -21 }
G Y ] . .
literal-14 literal-15 AFTER literal-16
FIRST
Syntax - Format 4:
INSPECT identifier-22 CONVERTING
identifier
T
identifier [ BEFOR
INITIA
identifier } ..
{ -3 } {O
-23 } E } L { -24
.
literal-1 literal-17 { AFTER literal-18 ]
Description: The INSPECT statement is used to perform various operations on string data. Each
of the four formats works slightly differently and is described in the correspondingly numbered
area.
Page 65
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
The first format is used to count occurrences of characters or strings within another
string. The number of occurrences is stored in identifier-2. The value in identifier-1 is
unchanged.
The second format is used to replace occurrences of characters or strings within
another string. The replacement strings must be of the same length as the original
string.
The third format is used to count while replacing occurrences of characters or strings
within another string. It is basically a combination of the first two formats.
The fourth format is used to replace occurrences of characters within another string
using only one INSPECT. Any occurrence on the first character of the CONVERTING
in the inspected string will be replaced by the first character in the TO string, while
occurrences of the second character in the CONVERTING string will be replaced by
the second character in the TO string, and so on. The CONVERTING string must be of
the same length as the tostring.
Tips:
Format 2 can be used to convert leading spaces to zeros, in a numeric item, e.g.
INSPECT LEADING-SPACE-ITEM REPLACING LEADING SPACES BY ZEROS.
Format 4 can be used to convert lowercase to uppercase, e.g.
INSPECT MIXED-CASE-ITEM CONVERTING "abcde..." TO "ABCDE...".
INSPECT – Example:
77 countr PIC 9 VALUE ZERO.
01 data-1 PIC X(6).
INSPECT data-1 TALLYING countr FOR CHARACTERS AFTER INITIAL "S"
REPLACING ALL "A" BY "O"
DATA-1 COUNTR DATA-1
Before After After
ANSELM 3 ONSELM
SACKET 5 SOCKET
PASSED 3 POSSED
ANS”LM 0 000”LM
SACK”T 0 0000”T
Page 66
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Before After
a/five/?six a/FIVE/?six
r/Rexx/RRRr r/REXX/RRRR
zfour?inspe zfour?inspe
Intrinsic Functions
Date Functions: Probably the most useful intrinsic function is CURRENT-DATE which is a
replacement for ACCEPT DATE and ACCEPT TIME. CURRENT-DATE is Y2K-compliant, having
a 4-digit year. This function returns a 20-character alphanumeric field which is laid out as follows:
01 WS-CURRENT-DATE-FIELDS.
05 WS-CURRENT-DATE.
10 WS-CURRENT-YEAR PIC 9(4).
10 WS-CURRENT-MONTH PIC 9(2).
10 WS-CURRENT-DAY PIC 9(2).
05 WS-CURRENT-TIME.
10 WS-CURRENT-HOUR PIC 9(2).
10 WS-CURRENT-MINUTE PIC 9(2).
10 WS-CURRENT-SECOND PIC 9(2).
10 WS-CURRENT-MS PIC 9(2).
05 WS-DIFF-FROM-GMT PIC S9(4).
So not only can you get the time down to the millisecond, but you can get the difference between
your time and Greenwich Mean Time.
But normally reference modification is used to only grab the part you want:
* Get the current date in yyyymmdd format:
MOVE FUNCTION CURRENT-DATE (1:8) TO WS-TODAY
* Get the current time in hhmmss format:
MOVE FUNCTION CURRENT-DATE (9:6) TO WS-TIME
The other intrinsic date functions deal with converting between either Gregorian dates or Julian
dates and an internal Integer format. This Integer format is simply the number of days since some
predetermined, fixed date like 1/1/0001. These four conversion functions are:
Page 67
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
All Gregorian and Julian dates are expected to have 4-digit years.
You might be asking just what in the heck would you want with this integer date. Well, with it
calendar math is a breeze. You need to know what date is 150 days from today (and this kind of
stuff happens more often than you'd think)? Convert today to an integer date, add 150 to it and
convert it back. No more checking which months you're going through to see if it's a 30 day or 31
day month. No more leap year calculations. It's pretty automatic:
Converting between Gregorian and Julian formats used to be a pain also. Now:
COMPUTE WS-DATE = FUNCTION DATE-OF-INTEGER (FUNCTION
INTEGER-OF-DAY (WS-JULIAN))
Numeric Functions: It's doubtful that there will be much use for most of the numeric functions
available. Some of the more useful ones:
* Calculate the square root of a number
COMPUTE WS-RESULT = FUNCTION SQRT (WS-NUMBER)
* Get the remainder from dividing two integers
COMPUTE WS-RESULT = FUNCTION MOD (WS-INTEGER-1, WS-INTEGER-2)
* Get the remainder from dividing two non-integers
COMPUTE WS-RESULT = FUNCTION REM (WS-NUMBER-1, WS-NUMBER-2)
Page 68
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
There are also geometric functions (SIN, COS, TAN), log functions (LOG, LOG10), FACTORIAL
and even RANDOM for generating random numbers.
Try It Out
Problem Statement:
Accept a sentence from the JCL SYSIN using ACCEPT command and perform the string functions
to extract a part of the string from Left, from right and from anywhere in the middle.
Code:
Code for STRING Statement
STRING W01-INPUT-01
' - '
W01-INPUT-04
DELIMITED BY SIZE
INTO W02-STRING
END-STRING.
Refer File Name: Handout_Example_Code.txt Code for Session #9 to obtain soft copy of the
program code
How It Works:
The job accepts the inputs from the JCL from the SYSIN using the ACCEPT
statement.
The output is displayed in the JCL SYSOUT using the DISPLAY statements.
The process para performs the string operations like STRING, UNSTRING, INSPECT
and so on.
The last statement “STOP RUN” indicates the end of execution.
Page 69
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Summary
The STRING statement is used to concatenate items together that are not numeric.
The UNSTRING statement is used to parse individual items from within a single string.
The starting position and length as parameters are used to extract a part of a string,
for example MOVE W01-TEXT-01(4:5) TO W01-TEXT-02.
The INSPECT statement is used to count occurrences of characters or strings within
another string.
Exercises
A field name STRING-1 contains 80 chars. The char (/) or (,) is used to indicate the end of a word
within these 80 chars. Write the COBOL statement to find the number of words in STRING-1 and
the length of the individual words
Page 70
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Learning Objectives
After completing this session, you will be able to:
Describe the concept of compiling, linking, and executing
Compile options that affect performance
Identify common errors with regard to arithmetic operations and string functions
Compiling Concept
On compiling a program, the COBOL compiler translates COBOL source program to
object code and resolves calls to nested programs.
On linking a program, the link editor resolves calls to subprograms that are to be
bound at link time. The link editor uses object code to produce a program file.
On executing a program, the loader loads the program file into memory and the
operating system executes it.
The default options are set up when compiler is installed.
One can override them with other options in the compile JCL.
To find out default compiler options in effect, run a test compilation without specifying
any option. The output listing lists the default options specified by your installation.
The compile options are handled in detail in the Compile Options Section
Page 71
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Arithmetic Operations:
The results of Arithmetic operations might have a value than what the fixed-point field
can hold them. Example: Considering a 4 digit value attempted to store in a variable
which can hold maximum 3 digits
Possibility to have a division by zero
In either case, the ON SIZE ERROR clause after the ADD, SUBTRACT, MULTIPLY,
DIVIDE, or COMPUTE statements can handle the situation.
The ON SIZE ERROR clause will execute the imperative statement and the result field
will not be changed in the following five cases:
o Fixed-point overflow
o Division by zero
o Zero raised to the zero power
o Zero raised to a negative number
o A negative number raised to a fractional power
Page 72
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Summary
The basic compiling concepts include:
o Compiling
o Linking
o Executing
o Default Compiler Options
o Performance related Compile Options
Common Errors:
o String Functions: Pointers falling out of Range, Overflow situation
o Arithmetic Operations: Possibility of division by Zero and Storing value beyond
the capacity of the variable
Page 73
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Learning Objectives
After completing this session, you will be able to:
Explain the various types of Picture Clause Editing
Picture Clause
Specified for every Elementary Item
pic-string1 can contain a maximum of 30 Code Characters
Code Character repetitions can be indicated by an integer within ()
Code Sample
Meaning
Char Picture
9 Numeric Data Item 9999
X Any allowable character from the character XXXX
set
A a Letter or Space AAAA
V Assumed Decimal Point 99V99
P Position of Assumed Decimal Point when it 99PPV
lies outside PPP99
S Data Item is Signed S9(4)
B Inserts space XXBXXX
0 Inserts zero 9(5)000
/ Inserts Slash XX/XX/XX
, Inserts Comma 9,999
. Inserts Decimal Point 9,999.99
* Replaces leading zeros ****9.99
$ Inserts Currency sign $9,999.99
+ Inserts Sign +99.99
- -99.99
CR 99.99DB
DB 99.99CR
Page 74
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Simple Insertion
Done using ‘B’, ‘0’, ‘/’
Applicable only for numeric edited
PICTURE Value of Data Edited Result
X(2)BX(3)BX(4) 19Mar1995 19 Mar 1995
9(2)/9(2)/9(2) 190395 19/03/95
99,B999,B000 1234 01, 234, 000
99,999 12345 12,345
Special insertion
Period (.) is the special insertion symbol; it also represents the actual decimal point for alignment
purposes
PICTURE Value of Data Edited Result
999.99 1.234 001.23
999.99 12.34 012.34
999.99 123.45 123.45
999.99 1234.5 234.50
Fixed insertion
- $ (Currency symbol)
+ - CR DB (editing-sign control symbols)
PICTURE Value of Data Edited Result
999.99+ +6555.556 555.55+
+9999.99 -6555.555 -6555.55
9999.99 +1234.56 1234.56
-$999.99 -123.45 -$123.45
-$999.99 -123.456 -$123.45
-$999.99 +123.456 $123.45
Page 75
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Floating insertion
Done using ‘$’, ‘+’, ‘-'
Mutually exclusive
PICTURE Value of Data Edited Result
$$$$.99 .123 bbb$.12
$$$9.99 .12 bb$0.12
$,$$$,999.99 -1234.56 bbbb$1,234.56
+,+++,999.99 -123456.789 b-123,456.78
$$,$$$,$$$.99CR -1234567 $1,234,567.00CR
++,+++,+++.+++ 0000.00 Bbbbbbb
Page 76
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Try It Out
Problem Statement:
ACCEPT an input from the JCL SYSIN and DISPLAY the value in all type of PICture clause
editing.
Code:
01 W01-INPUT.
05 W01-INPUT-01 PIC 9(05).
01 W02-OUTPUT.
05 W02-POS-SIGN PIC S9(05).
05 W02-NEG-SIGN PIC S9(05).
05 W02-NO-SIGN PIC 9(05).
05 W02-POS-SIGN-DEC PIC S9(05)V9(02).
05 W02-NEG-SIGN-DEC PIC S9(05)V9(02).
05 W02-NO-SIGN-DEC PIC 9(05)V9(02).
05 W02-NO-SIGN-DEC-DOT PIC 9(05).9(02).
05 W02-ZERO-SUPRESS PIC ZZZZZ.99.
05 W02-DOLLAR PIC $$$$$.99.
05 W02-PPP PIC 999PP.
Refer File Name: Handout_Example_Code.txt under heading ‘Code for Session #14’ to
obtain soft copy of the program code.
How It Works:
The job accepts the inputs from the JCL from the SYSIN using the ACCEPT
statement.
The various parameters are calculated and moved to the display variables.
Based on the declaration type each of the variables are displayed in JOB SYSOUT.
Summary
You should remember the concepts on the following
Signed and unsigned variables,
Implied decimal point and placeholders
Other representation like Zero suppress, dollar prefix, and so on
Page 77
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Learning Objectives
After completing this session, you will be able to:
Execute the Conditional Expression statements in a COBOL program
Conditional Expressions
Types of Conditional Expressions:
o Relation
o Class
o Sign
o Condition name
Cause the processing to select between alternate paths depending on the truth value
of the expression
Relation Operators
Causes a comparison of two operands. Operands can be an Identifier, Literal or
Arithmetic Expression.
Syntax:
Operand-1 relop operand-2
Operand-1, operand-2 can be an identifier, literal, arithmetic expression, index-name
or a pointer.
Relational Operators:
IS [NOT] GREATER THAN [NOT] >
IS [NOT] LESS THAN [NOT] <
IS [NOT] EQUAL TO [NOT] =
IS GREATER THAN OR EQUAL TO > =
IS LESS THAN OR EQUAL TO < =
For numeric operands the comparison is algebraic
Example:
012
12.00
12
+12 are all-equal
Page 78
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Example:
l-A “JOES”
l-B “JOE” taken as “JOE “
l-A > l-B is TRUE
Class Condition
Numeric or alphabetic or user defined class-name check of the operand
Numeric test cannot be done for an item declared as alphabetic (PIC A)
Alphabetic test cannot be done for item declared as Numeric (PIC 9)
Packed-decimal allowed for numeric test
Syntax:
IF id-1 IS [NOT]
{NUMERIC
ALPHABETIC
ALPHABETIC-LOWER
ALPHABETIC-UPPER
class-name}
SIGN CONDITION:
Operand-1 IS [ NOT ]
{POSITIVE
NEGATIVE
ZERO}
Determines whether algebraic value is less than greater than or equal to zero
Operand-1 must be a numeric identifier, or arithmetic containing at least one reference
to a variable
Condition Name
It is a subset of relational condition
It tests a conditional variable to determine whether its value is equal to any value(s)
associated with the condition-name.
Condition-name is used in conditions as an abbreviation for the relation condition.
Page 79
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Syntax:
condition-name-1
Conditional expression:
Examples:
IF ASSOC-AGE > 80
SET SENIOR-ASSOC TO TRUE
END-IF
IF ASSOC-SAL IS POSITIVE
SET DEBIT-AMOUNT TO TRUE
END-IF
Complex Conditions
Formed by:
o Combining simple conditions
o Nested IFs
o Logical Connectives
Logical Operators:
o Used to combine simple conditions
o Abbreviating conditions
o For negation
Logical Operators
NOT: Logical Negation
OR: Logical Inclusive
AND: Logical Conjunction
Evaluation Rules
Precedence:
o Arithmetic Expression
o All Relational Operators
o NOT
o AND
o OR
o If a condition is put in parenthesis, it is evaluated and its truth value depends on
the truth value of its constituents
Page 80
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Examples:
A > B OR NOT C OR D
= (A>B) OR NOT (A>C) OR (A>D)
Introduction to IF Statement
Syntax - Format 1:
IFcondition-1 THEN
{ statement-1
NEXT SENTENCE }
[ELSE
{ statement-1
NEXT SENTENCE }]
[END-IF]
Description: The IF statement is used to test various conditions. The ELSE clause is used to
provide code to be executed for the alternative condition. When the statement is executed, the
condition after IF is evaluated. If the condition is true, the statement(s) between the condition and
the ELSE clause are executed and control is then transferred to the statement following the END-
IF. If the condition is false, the code between the ELSE and the END-IF, if any, is executed.
Tips:
The IF statement can be used to test for various kinds of conditions, relational tests,
class tests, sign tests, or condition name tests. See conditions for more detail.
The logical operators AND, OR, and NOT may be used to combine conditions into
complex conditions. If these operators are used, the order of precedence is from
highest to lowest: AND, OR, and finally NOT, unless the order is overridden with the
use of parentheses.
Page 81
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
IF Statement - Example
IF (WS-NT91-CLT NOT EQUAL ‘99999’)
AND WS-NT91-SEQ NOT NUMERIC
Statements 1
ELSE
Statement 2
END-IF
Using conditional-names:
IF C08W-ERR-OPEN-FLAG
GO TO 999-ERR-OPEN-PARA
END-IF
FALSE FALSE
ANY
condition-3
TRUE
FALSE
{{WHEN { identifier- identifier- }
3 4
THROUGH
[NOT] {{ literal-3 }[ { } { literal-4 }]}
THRU
arith-expr- arith-expr-
3 4
ANY
condition-4
TRUE
FALSE
]
[ALSO { identifier- }
...}...
identifier-5 6
THROUGH
[NOT] {{ literal-5 }[ { } { literal-6 }]}
THRU
arith-expr-5 arith-expr-
6
imperative-statement-1}...
[WHEN OTHER imperative-statement-
2]
[END-EVALUATE]
Page 82
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Description: The EVALUATE statement is used to test a variable for multiple different values. As
such, it is an implementation of the standard case construct. The ALSO clause is used to test for
values of additional variables as the same time. To execute the same code for multiple conditions,
code all the applicable conditions on multiple WHEN clauses. When the statement is executed, the
variable after EVALUATE is compared to the each of the values in the WHEN clauses in turn.
When a match is found the statement(s) following the WHEN clause and before the next WHEN
clause, are executed and control is then transferred to the statement following the END-
EVALUATE. If no matching WHEN clause is found, the code following the WHEN OTHER
statement is executed. If the ALSO clause is used, then the value following the ALSO in the
EVALUATE must match the value in the ALSO associated with the WHEN clause.
For example:
EVALUATE FILE-STATUS
WHEN "00"
PERFORM SUCCESSFUL-ROUTINE
WHEN "10"
PERFORM END-OF-FILE-ROUTINE
WHEN OTHER
PERFORM IO-ERROR-ROUTINE
END-EVALUATE.
In this example, if the file status has a value of "00", SUCCESSFUL-ROUTINE will be performed,
but if the file status has a value of "10", the END-OF-FILE-ROUTINE will be executed. If neither
value is in file status, then IO-ERROR-ROUTINE will be executed. Here is the same test using
condition names instead of relational tests:
EVALUATE TRUE
WHEN I-O-OK
PERFORM SUCCESSFUL-ROUTINE
WHEN END-OF-FILE
PERFORM END-OF-FILE-ROUTINE
WHEN OTHER
PERFORM IO-ERROR-ROUTINE
END-EVALUATE.
Tips:
Use multiple WHEN clauses to implement code that works like an OR.
Use the ALSO clause to implement code that works like an AND.
Use ANY if the value of one of the variables is not needed in one of the conditions.
EVALUATE Statement:
Example 1
EVALUATE proc-type ALSO
cust-type
WHEN 1 ALSO 1
Page 83
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
MOVE 1 TO RESULT
WHEN 3 ALSO 1 THRU 2
MOVE 2 TO RESULT
WHEN 2 ALSO 1
MOVE 3 TO RESULT
WHEN OTHER
MOVE 0 TO RESULT
END-EVALUATE
In this example subject of Evaluation is an Expression. Depending on these values the control
passes to the corresponding WHEN.
EVALUATE TRUE
WHEN l-VALUE < 100
MOVE 1 TO RESULT
WHEN l-VALUE < 1000
MOVE 2 TO RESULT
WHEN l-VALUE < 10000
WHEN OTHER
MOVE 0 TO RESULT
END-EVALUATE
In this example, the subject is TRUTH value. Depending on the values the WHEN phrase
satisfying the TRUTH value is executed.
If a WHEN does not have an associated imperative statement it is a do-nothing condition (same as
coding CONTINUE)
AND: If two conditions are combined with an AND, then both conditions must be true for the
combined expression to be true. For example,
ABC > DEF AND GHI IS NUMERIC
Will true only if the current value of the data-item ABC exceeds the current value of the data item
DEF and GHI contains only values in the range 0 - 9.
OR: If two conditions are combined with an OR, then either condition must be true for the
combined expression to be true. For example,
JKL < MNO OR PQR IS ALPHABETIC
is true if either the current value of the data-item MNO exceeds the current value of the data item
JKL or PQR contains only values in the range A - Z, a - z, or spaces or both.
Page 84
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
NOT: Any condition may be preceded with the word NOT in order to negate that condition. In
relational and class tests, the word NOT may be moved into the middle of the condition for
readability. For example,
STU NOT NUMERIC
Will true if there are any characters not in the range 0 - 9 in the data item.
Try It Out
Problem Statement:
Declare a variable and assign a value to it using MOVE Statement and validate the value and a
specific condition and display the result accordingly.
Code:
PROCEDURE DIVISION.
*================================================================*
* MAIN PARA - CALLS INPUT AND PROCESS PARA
*================================================================*
0000-MAIN-PARA.
PERFORM 1000-IF-STATEMENT
THRU 1000-IF-STATEMENT-EXIT.
0000-MAIN-PARA-EXIT.
EXIT.
*================================================================*
* CONDITIONAL EXPRESSIONS - IF STATEMENT
*================================================================*
1000-IF-STATEMENT.
MOVE 'TRUE ' TO W01-INPUT-FLAG.
DISPLAY '----CONDITIONAL EXPRESSIONS (IF)----'.
IF W01-INPUT-FLAG-TRUE THEN
DISPLAY 'FLAG = TRUE'
ELSE
DISPLAY 'FLAG = FALSE'
END-IF.
MOVE 'FALSE' TO W01-INPUT-FLAG.
IF W01-INPUT-FLAG-TRUE THEN
DISPLAY 'FLAG = TRUE'
Page 85
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
ELSE
DISPLAY 'FLAG = FALSE'
END-IF.
DISPLAY ' '.
1000-IF-STATEMENT-EXIT.
EXIT.
*================================================================*
* CONDITIONAL EXPRESSIONS - EVALUATE STATEMENT
*================================================================*
2000-EVALUATE-STATEMENT.
EVALUATE W01-INPUT-NUM
WHEN 0
DISPLAY 'VARIABLE VALUE IS = ZERO'
WHEN 1
DISPLAY 'VARIABLE VALUE IS = ONE'
WHEN OTHER
DISPLAY 'VARIABLE VALUE IS > ONE'
END-EVALUATE.
COMPUTE W01-INPUT-NUM = W01-INPUT-NUM + 1.
2000-EVALUATE-STATEMENT-EXIT.
EXIT.
Refer File Name: Handout_Example_Code.txt under heading ‘Code for Session #14’ to
obtain soft copy of the program code
How It Works:
The job accepts the inputs from the JCL from the SYSIN using the ACCEPT
statement.
The input parameters are validated based on the pre-defined value of the flag.
Based on the declaration type each of the variables is displayed in JOB SYSOUT.
Summary
You should remember the concepts on the following
Simple Conditions like IF statement
Complex Conditions like EVALUATE statement
Looping Structures like PERFORM UNTIL statement
Logical Operators
Page 86
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Page 87
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Learning Objectives
After completing this session, you will be able to:
Explain the basic concepts of file handling in COBOL
Declare files in the Environment Division and Data Division
Access sequential files
Explain the concepts of VSAM file handling in COBOL
Use copy books for defining Record formats for Sequential and VSAM Files
Handle different File Status Codes for Sequential and Indexed Sequential Files
All these three organizations can be used on DISK files; only the SEQUENTIAL organization can
be used with TAPE files.
All files must be declared in the ENVIRONMENT division by proper SELECT statements which
should contain a phrase describing to the compiler what type of organization the file should have.
A second important declaration should be placed in the FILE-SECTION where the programmer
describes the record format associated to the file in FD blocks.
Finally, the PROCEDURE division should have proper OPEN/CLOSE and READ/WRITE etc.
statements used in compliance with the logic (algorithm) of the program.
A record of a sequential file can only be accessed by reading all the previous records.
The records are discriminated from one another using the record length declared in the associated
FD statement of the FILE-SECTION. For example, if the record structure that the programmer has
declared is 52 bytes, blocks of 52 byte data (records) are assumed to place one after another in
the file. If the programmer is reading the data in a sequential file, every READ statement brings 52
bytes into the memory.
Page 88
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
If the file contains, say, 52 byte records; but the programmer tries to read this file with a program
which has declared 40 byte records (that is, the total length of the FD structure is 40 bytes), the
program will certainly read some pieces of information into the memory but the after the first READ
statement, some meaningless pieces of records will be brought into memory and the program will
start processing some physical records which contain logically meaningless data.
It is the programmer's responsibility to take care of the record sizes in files. You must be careful
when declaring record structures for files. Any mistake you make in record sizes will cause your
program to read/write erroneous information. This is especially dangerous if the file contents are
being altered (changed, updated).
Since the records are simply appended to each other when building SEQUENTIAL files, you
simply end up with a STREAM of byte. If this string does not contain any "Carriage Return/Line
Feed" control characters in it, the whole file will appear as a single LINE of character and would be
impossible to process with regular text editors. As you should know by now, text editors are good
in reading/writing/modifying text files. These programs will assume that the file consists of LINES
and expect the lines to be separated from each other by a pair of control characters called
"Carriage Return/Line Feed" (or CR/LF).
COBOL has a special type of sequential file organization, which is called the LINE SEQUENTIAL
ORGANIZATION which places a CR/LF pair at the end of each record while adding records to a
file and expects such a pair while reading. LINE SEQUENTIAL files are much easier to use while
developing programs because you can always use a simple text editor to see the contents of your
sequential file and trace/debug your program.
Please note that LINE SEQUENTIAL files have two extra characters for each record. For files,
which have millions of records, this might use up a significant amount of disk space.
SEQUENTIAL files have only one ACCESS MODE and that is "sequential access". Therefore you
need not specify an ACCESS MODE in the SELECT statement. Typical SELECT statements for
SEQUENTIAL files are:
SELECT MY-FILE ASSIGN TO MYFILE
ORGANIZATION IS SEQUENTIAL.
SELECT MY-FILE-2 ASSIGN TO MYFILE2
ORGANIZATION IS LINE SEQUENTIAL.
In the FILE-SECTION, you must provide FD blocks for each file; hence for a sequential file you
could have something like:
FD MYFILE.
01 MYFILE-REC.
02 M-NAME PIC X(16).
02 M-SURNAME PIC X(16).
02 M-BIRTHDATE.
03 M-BD-YEAR PIC 9999.
03 M-BD-MONTH PIC 99.
03 M-BD-DAY PIC 99.
Page 89
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Note: You must NOT provide record fields for the extra two CR/LF bytes in record descriptions of
LINE SEQ files. Once you declare the file to be a LINE SEQ file, these two extra bytes are
automatically taken in consideration and added for all new records that are added to a file.
Procedure Division Considerations: Like all files, sequential and line sequential files must be
OPENed before they can be processes and CLOSEd when they are not needed anymore.
Opening a sequential file for OUTPUT means that the program will only issue WRITE statements
to a NON-EXISTING and JUST CREATED file. Therefore, when you open a file for OUTPUT,
COBOL assumes that the file does not exist and try to create a new one. IF THE FILE EXISTS,
ITS CONTENTS WILL BE CLEARED WHEN OPENED AND ASSUMED TO BE A BRAND NEW
FILE INTO WHICH RECORDS WILL BE ADDED. You should be very careful when opening a file
for OUTPUT. One small mistake and all your valuable records are lost forever.
Opening a sequential file for INPUT means that the program will only issue READ statements to
an EXISTING file. Therefore, when you open a file for INPUT, COBOL assumes that the file exists
and tries to access it. IF THE FILE DOES NOT EXIST, AN ERROR MESSAGE WILL BE ISSUED
INDICATING THAT THE MENTIONED FILE COULD NOT BE FOUND.
Opening a sequential file for EXTEND means that the program will add NEW RECORDS to an
EXISTING file. Therefore, when you open a file for EXTEND, COBOL assumes that the file exists
and subsequent WRITE statements will try to ADD NEW RECORDS at the end of the existing file
(in other words; the append mode). Records can only be added to the END of a sequential file.
When you are finished with a file you must CLOSE it.
CLOSE NEW-FILE.
CLOSE OLD-FILE NEW-FILE.
You can close more than one file with a single CLOSE statement. When a COBOL program
terminates, all files mentioned in the program are automatically closed; therefore you will not get
an error message for those files you forget to close or do not close at all. Please note that relying
Page 90
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
on COBOL to close your files is not a proper programming style. Although not absolutely
necessary, you should close your files when you are done with them.
The CLOSE statement has a very important function. Sometimes, your program needs to re-start
reading a sequential file from the beginning. (Please note that every READ statement you execute
brings the next record into memory and when you skip a record, you cannot backspace the file to
previous records.) In such a situation, you will have to REWIND the file that is making the first
record the active one in memory. You can achieve this only by closing the file and re-opening it for
INPUT.
You should be careful not to open an already opened file. Closing already closed files usually do
not cause any problems but should be avoided. You should make sure that your program opens
and closes files at proper places in your logic flow so that no input-output is tried on closed files.
Simple INPUT-OUTPUT Statements for SEQ Files: Once you open a seq file, you can use
READ or WRITE statements to read or append records to this file. You cannot use a READ
statement for a file opened for OUTPUT or EXTEND and similarly you cannot use a WRITE
statement for a file you have opened for INPUT.
A good programmer must check whether the READ statement could find a record to read
successfully. That means; the programmer must check whether there were any records to READ
when the statement was executed. The situation can be checked with the following construct:
READ MY-FILE AT END PERFORM NO-RECORDS-FOUND.
The construct tells the COBOL compiler to execute the paragraph labeled NO-RECORDS-FOUND
when the READ statement cannot find any records to read.
Once your program EXECUTES a successful READ statement, the information in the data record
that was just brought into memory will be available in the corresponding variables mentioned in
your record description declaration (the FD block).
Page 91
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
When you want to put records in a seq file, you have to open it for OUTPUT or EXTEND
(depending on the requirements of the algorithm of your program). The COBOL statement that is
used to put records into a file is the WRITE statement. The important point that you should be
careful with are that,
The file should be opened
New values for the field variables of the FD record description must be moved to
proper variables of the record
The RECORD NAME is specified in the WRITE statement and NOT the FILE NAME.
You must first open it, then move new values to the fields in MYFILE-REC and finally WRITE the
record into the file.
OPEN EXTEND MY-FILE.
....
MOVE "UGUR" TO M-NAME.
MOVE "AYFER" TO M-SURNAME.
MOVE 1955 TO M-BD-YEAR.
MOVE 1 TO M-BD-MONTH.
MOVE 1 TO M-BD-DAY.
WRITE MYFILE-REC.
.....
Updating Records of a Sequential File: Sometimes you need to make some small changes in
the contents of a file. Of course it possible to create a brand new file with the new, modified
contents but this is not practical. COBOL provides you with an OPEN I-O mode with which you can
modify only the required record in a file.
In other words, there is another file opening mode; the I-O mode; and another special REWRITE
statement. Suppose that you want to change the surname field of the 20th record of a sequential
file (originally "AYFER") into "AYFEROGLU".
Page 92
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
PROCEDURE DIVISION.
....
OPEN I-O MY-FILE.
....
MOVE 20 TO N.
....
PERFORM READ-A-REC N-1 TIMES.
*
* TO MAKE SURE THAT WE ARE ON THE CORRECT RECORD
*
IF M-SURNAME NOT = "AYFER" DISPLAY "WRONG RECORD"
DISPLAY "RECORD NOT UPDATED"
CLOSE MYFILE
STOP RUN.
MOVE "AYFEROGLU" TO M-SURNAME.
REWRITE MY-FILE-REC.
.....
CLOSE MY-FILE.
....
Deleting Records of a Sequential File: I is NOT possible to delete records of a sequential file. If
you do not want a specific record to be kept in a sequential file any more, all you can do is to
modify the contents of the record so that it contains some special values that your program will
recognize as deleted (remember to open the file in I-O mode and REWRITE a new record).
Page 93
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
In contrast to SEQ files, records of a RELATIVE file can be accessed by specifying the record
sequence number in the READ statement (the KEY) and without needing to read all the previous
records.
It is the programmer's responsibility to take care of the record sizes in files. You must be careful
when declaring record structures for files. Any mistake you make in record sizes will cause your
program to read/write erroneous information. This is especially dangerous if the file contents are
being altered (changed, updated).
Please note that you must provide the record structure to have a special field allocated to contain
the KEY that is the record sequence number.
RELATIVE files can have RANDOM or SEQUENTIAL ACCESS MODEs. If the ACCESS MODE is
declared to be RANDOM in the corresponding SELECT statement, the program can read the
record with key value 2345 and then the record with key=3, then record 2344, and so on. In short,
one can access any record of a relative file, in any order, provided that the KEY value is specified
before the READ statement is executed.
If the ACCESS MODE is SEQUENTIAL, that means the records of the file will be accesses in their
physical sequential order (just like SEQUENTIAL and LINE SEQUENTIAL files) and no specific
KEY value be given for the READ statements; but instead, the NEXT clause will appear in READ
statements meaning "Go get the record with the next consecutive key value.
SELECT MY-FILE ASSIGN TO DISK MYFILE
ORGANIZATION IS RELATIVE
ACCESS MODE IS RANDOM
RECORD KEY IS M-IDNO.
Page 94
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
In the FILE-SECTION, you must provide fields for the KEY, the numerical M-IDNO in this example,
in the FD block of the RELATIVE file;
FD MY-FILE.
01 MY-FILE-REC.
02 M-IDNO PIC 9999.
02 M-NAME PIC X(16).
02 M-SURNAME PIC X(16).
02 M-BIRTHDATE.
03 M-BD-YEAR PIC 9999.
03 M-BD-MONTH PIC 99.
03 M-BD-DAY PIC 99.
Note: Since the key field will contain integer, record sequence numbers; you should declare the
field to be numerical and take care that it is wide enough to carry all possible values for the key
value. For example, if your file is expected to have 200,000 records in it, the key field should be
declared at least 6 bytes (PIC 999999) so that it can hold the values 1 through 200,000. A key field
declaration of "PIC 999" would let use a file of max 999 records in it.
Procedure Division Considerations: Like all files, relative files must be OPENed before they can
be processes and CLOSEd when they are not needed anymore.
Relative files can be opened for:
OUTPUT
INPUT
I-O (Input-Output)
Opening a relative file for OUTPUT means that the program will only issue WRITE statements to a
NON-EXISTING and JUST CREATED file. Therefore, when you open a file for OUTPUT, COBOL
assumes that the file does not exist and try to create a new one. IF THE FILE EXISTS, ITS
CONTENTS WILL BE CLEARED WHEN OPENED AND ASSUMED TO BE A BRAND NEW FILE
INTO WHICH RECORDS WILL BE ADDED. You should be very careful when opening a file for
OUTPUT. One small mistake and all your valuable records are lost forever.
Once you open a relative file in Output mode, you are expected to write records in the
INCREASING and CONSECUTIVE order of keys. That is, before writing the record with key 98
(98th record) you should first write the first 97 records.
Opening a relative file for INPUT means that the program will only issue READ statements to an
EXISTING file. Therefore, when you open a file for INPUT, COBOL assumes that the file exists
and tries to access it. IF THE FILE DOES NOT EXIST, AN ERROR MESSAGE WILL BE ISSUED
INDICATING THAT THE MENTIONED FILE COULD NOT BE FOUND.
If you have declared the ACCESS MODE to be RANDOM, before each READ statement, you are
supposed to move a valid KEY value to the record field variable that is declared as the RECORD
KEY.
Page 95
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
For instance;
OPEN INPUT MYFILE.
....
MOVE 23 TO M-IDNO.
READ MYFILE.
Good programmers should take precautions in their program to avoid error messages and
subsequent abnormal terminations are an INVALID value for the record key specified before the
READ statement.
The INVALID KEY condition rises if the value in M-IDNO is zero, negative or has a value greater
than the total number of records in the file.
If you have declared the ACCESS MODE as SEQUENTIAL, you should use the NEXT clause in
the READ statement. Like
READ MYFILE NEXT AT END PEFORM NO-MORE-RECORDS.
When you are finished with a file you must CLOSE it.
CLOSE NEW-FILE.
CLOSE OLD-FILE NEW-FILE.
You can close more than one file with a single CLOSE statement. When a COBOL program
terminates, all files mentioned in the program are automatically closed; therefore you will not get
an error message for those files you forget to close or do not close at all. Please note that relying
on COBOL to close your files is not a proper programming style. Although not absolutely
necessary, you should close your files when you are done with them.
In order to rewind a relative file with ACCESS MODE RANDOM, you do not need to rewind it when
you need to go the first record. Just move 1 to the record key and issue a READ statement.
Simple INPUT-OUTPUT Statements for RELATIVE Files: Once you open a relative file, you can
use READ or WRITE statements to read or append records to this file. You cannot use a READ
statement for a file opened for OUTPUT and similarly you cannot use a WRITE statement for a file
you have opened for INPUT.
A good programmer must check whether the READ statement could find a record to read
successfully. That means; the programmer must check whether there were any records with the
indicated key value when the statement was executed. The situation can be checked with the
following construct:
Page 96
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
The construct tells the COBOL compiler to execute the paragraph labeled NO-RECORDS-FOUND
when the READ statement cannot find any record with the key value stored in the key field
variable.
Once your program EXECUTES a successful READ statement, the information in the data record
that was just brought into memory will be available in the corresponding variables mentioned in
your record description declaration (the FD block).
When you want to put records in a relative file, you have to open it for OUTPUT. The COBOL
statement that is used to put records into a file is the WRITE statement. The important point that
you should be careful with are that,
The file should be opened
New values for the field variables of the FD record description must be moved to
proper variables of the record
The value of the KEY VARIABLE must have a valid value and this valid value should
be one greater than the key value of the record written previously,
The RECORD NAME is specified in the WRITE statement and NOT the FILE NAME.
Updating Records of a Relative File: Sometimes you need to make some small changes in the
contents of a file. Of course it possible to create a brand new file with the new, modified contents
but this is not practical. COBOL provides you with an OPEN I-O mode with which you can modify
only the required record in a file.
In other words, there is another file opening mode; the I-O mode; and another special REWRITE
statement. Suppose that you want to change the surname field of the 20th record of a relative file
(originally "AYFER") into "AYFEROGLU".
PROCEDURE DIVISION.
Page 97
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
....
OPEN I-O MY-FILE.
....
MOVE 20 TO M-IDNO.
READ MY-FILE INVALID KEY PERFORM KEY-ERROR.
*
* TO MAKE SURE THAT WE ARE ON THE CORRECT RECORD
*
IF M-SURNAME NOT = "AYFER" DISPLAY "WRONG RECORD"
DISPLAY "RECORD NOT UPDATED"
CLOSE MY-FILE
STOP RUN.
MOVE "AYFEROGLU" TO M-SURNAME.
REWRITE MY-FILE-REC.
.....
CLOSE MY-FILE.
.....
Deleting Records of a Relative File:It is NOT possible to delete records of a relative file. If you
do not want a specific record to be kept in a relative file any more, all you can do is to modify the
contents of the record so that it contains some special values that your program will recognize as
deleted (remember to open the file in I-O mode and REWRITE a new record).
Page 98
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
It is the programmer's responsibility to take care of the record sizes in files. You must be careful
when declaring record structures for files. Any mistake you make in record sizes will cause an
error and abnormal termination.
Please note that you must provide the record structure to have a special field allocated to contain
the KEY.
INDEXED files can have RANDOM or SEQUENTIAL ACCESS MODEs. If the ACCESS MODE is
declared to be RANDOM in the corresponding SELECT statement, the program can read the
record with key value "ABC" and then the record with key="A12", then record with key "D2X", and
so on. In short, one can access any record of an indexed file, in any order, provided that the KEY
value is specified before the READ statement is executed.
If the ACCESS MODE is SEQUENTIAL, that means the records of the file will be accesses in their
physical sequential order (just like SEQUENTIAL and LINE SEQUENTIAL files) and no specific
KEY value be given for the READ statements; but instead, the NEXT clause will appear in READ
statements meaning "Go get the record with the next consecutive key value.
SELECT MY-FILE ASSIGN TO DISK MYFILE
ORGANIZATION IS INDEXED
ACCESS MODE IS RANDOM
RECORD KEY IS M-IDNO.
In the FILE-SECTION, you must provide fields for the KEY, the M-IDNO in this example, in the FD
block of the INDEXED file;
FD MY-FILE.
01 MY-FILE-REC.
02 M-IDNO PIC XXXX.
02 M-NAME PIC X(16).
02 M-SURNAME PIC X(16).
02 M-BIRTHDATE.
03 M-BD-YEAR PIC 9999.
03 M-BD-MONTH PIC 99.
03 M-BD-DAY PIC 99.
Note: Since the keys are not supposed to be numerical, you can use the X picture for key fields.
Procedure Division Considerations: Lie all files, Indexed files must be OPENed before they can
be processes and CLOSEd when they are not needed anymore.
Page 99
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Opening an indexed file for OUTPUT means that the program will only issue WRITE statements to
a NON-EXISTING and JUST CREATED file. Therefore, when you open a file for OUTPUT,
COBOL assumes that the file does not exist and try to create a new one. IF THE FILE EXISTS,
ITS CONTENTS WILL BE CLEARED WHEN OPENED AND ASSUMED TO BE A BRAND NEW
FILE INTO WHICH RECORDS WILL BE ADDED. You should be very careful when opening a file
for OUTPUT. One small mistake and all your valuable records are lost forever.
Once you open an indexed file in Output mode, you are expected to write records in the
INCREASING order of keys. That is, before writing the record with key A98 you should first write
all the records with key values alphanumerically less than "A98". Please note that indexed file keys
are case sensitive; that is the key value "a89" is NOT EQUAL TO "A89"; in fact it is
alphanumerically greater than "A89" because the ASCII value of "a" (97) is greater than the ASCII
value of "A" (65).
Opening an indexed file for INPUT means that the program will only issue READ statements to an
EXISTING file. Therefore, when you open a file for INPUT, COBOL assumes that the file exists
and tries to access it. IF THE FILE DOES NOT EXIST, AN ERROR MESSAGE WILL BE ISSUED
INDICATING THAT THE MENTIONED FILE COULD NOT BE FOUND.
If you have declared the ACCESS MODE to be RANDOM, before each READ statement, you are
supposed to move a valid KEY value to the record field variable that is declared as the RECORD
KEY.
For instance;
OPEN INPUT MY-FILE.
....
MOVE "X23" TO M-IDNO.
READ MY-FILE.
Good programmers should take precautions in their program to avoid error messages and
subsequent abnormal terminations are an INVALID value for the record key specified before the
READ statement.
The INVALID KEY condition rises if there is no record in the file with key value equal to the
specified key value.
If you have declared the ACCESS MODE as SEQUENTIAL, you should use the NEXT clause in
the READ statement. Like
Page 100
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
When you are finished with a file you must CLOSE it.
CLOSE NEW-FILE.
CLOSE OLD-FILE NEW-FILE.
You can close more than one file with a single CLOSE statement. When a COBOL program
terminates, all files mentioned in the program are automatically closed; therefore you will not get
an error message for those files you forget to close or do not close at all. Please note that relying
on COBOL to close your files is not a proper programming style. Although not absolutely
necessary, you should close your files when you are done with them.
REWINDING an indexed file with ACCESS MODE RANDOM is not meaningful. If the ACCESS
MODE is SEQUENTIAL, you can CLOSE and then OPEN INPUT again to rewind a sequentially
accessed indexed file.
Simple INPUT-OUTPUT Statements for INDEXED Files: Once you open an indexed file, you
can use READ or WRITE statements to read or add records to this file. You cannot use a READ
statement for a file opened for OUTPUT and similarly you cannot use a WRITE statement for a file
you have opened for INPUT.
A good programmer must check whether the READ statement could find a record to read
successfully. That means; the programmer must check whether there were any records with the
indicated key value when the statement was executed. The situation can be checked with the
following construct:
READ MY-FILE INVALID KEY PERFORM NO-RECORDS-FOUND.
The construct tells the COBOL compiler to execute the paragraph labeled NO-RECORDS-FOUND
when the READ statement cannot find any record with the key value stored in the key field
variable.
Once your program EXECUTES a successful READ statement, the information in the data record
that was just brought into memory will be available in the corresponding variables mentioned in
your record description declaration (the FD block).
When you want to create an indexed file, you have to open it for OUTPUT. The COBOL statement
that is used to put records into a new file is the WRITE statement. The important point that you
should be careful with are that,
The file should be opened
New values for the field variables of the FD record description must be moved to
proper variables of the record
Page 101
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
The value of the KEY VARIABLE must have a valid value and this valid value should
be alphanumerically greater than the key value of the record written previously,
The RECORD NAME is specified in the WRITE statement and NOT the FILE NAME.
Updating Records in an Indexed File: Sometimes you need to make some small changes in the
contents of a file. Of course it possible to create a brand new file with the new, modified contents
but this is not practical. COBOL provides you with an OPEN I-O mode with which you can modify
only the required record in a file.
In other words, there is another file opening mode; the I-O mode; and another special REWRITE
statement. Suppose that you want to change the surname field of a record in an indexed file
(originally "AYFER") into "AYFEROGLU".
Page 102
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
CLOSE MYFILE.
.....
Important: The key field of a record in an indexed file CANNOT be updated. If the programmer
has to update the key field, the only solution is to delete the record with the old key value and a
add the same record to the file; this time with the new key value.
Adding Records to an Indexed File: When you need to add records to an indexed file, you
should open the file in I-O mode and just write new records.
Note: Keys in an indexed file must be unique. That is to say, no two records can have the same
key. There is, however, a technique to have duplicate keys in an indexed file, but this will be
covered later.
Page 103
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Multiple Keys (Primary & Alternate Keys): Sometimes the programmers need to
assign more than one key fields in their records. An example could be a database
where one wants to keep records for vehicles registered to a certain country. The
Turkish vehicle plate numbering system is NOT suitable for using relative files
because it contains alphabetic parts (06 AHT 08). As you might guess, this type of key
values is very suitable to be organized as an INDEXED file.
Having declared the "PLATE" field as the key field, now, given a plate number, a program which
has declared an indexed file with RANDOM access mode, can find the corresponding record very
quickly (if the does exist, this condition will also be detected very quickly).
Knowing that no two vehicles have the same plate number (unique), the plate number is certainly a
very good choice for the key.
However, suppose that the program you have to write is also expected to find records for vehicles
of a certain brand very quickly. Since the key is the plate number, the only way you can find
"OPEL" brand vehicles by going through all the records (declare the access mode to be sequential
and READ NEXT all records till the AT END condition raises) testing the BRAND field against the
value given by the coder ("OPEL" for instance).
With indexed files, there is a better solution: You can declare the BRAND field also to be a key; but
AN ALTERNATE key!. The PRIMARY key will still be the plate numbers. Since there are many
vehicles manufactured by OPEL in your database, you know that the ALTERNATE KEY values will
not be unique. THIS IS ALLOWED IN COBOL. ONLY THE PRIMARY KEY HAS TO BE UNIQE.
ALTERNATE KEYS CAN HAVE DUPLICATE VALUES.
You can declare as many alternate keys your program requires. More alternate keys you have,
more extra data structures will be required and slower be your program. Therefore certain attention
should be paid before assigning alternate keys. You should avoid unnecessary alternate keys.
When you have alternate keys, you declare them in the SELECT statement together with the
PRIMARY key.
SELECT VEHICLES ASSIGN TO VEHICLES
ORGANIZATION IS INDEXED
ACCESS MODE IS RANDOM
RECORD KEY IS PLATE
ALTERNATE KEY IS BRAND.
....
FD VEHICLES.
01 VEHICLE-REC.
02 PLATE PIC XXXXXXXXXX.
02 BRAND PIC X(20).
02 OWNER PIC X(32).
02 DATE-REGISTERED PIC 99999999.
02 ENGINE-NO PIC X(20).
02 CHASSIS-NO PIC X(20).
...
Page 104
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
When you need to access the file with the primary key, you just move the key value to the primary
key field of the record and issue a READ statement.
MOVE "06 AHT 08" TO PLATE.
READ VEHICLES INVALID KEY PERFORM NOT-FOUND.
When you need to access the file using an alternate key, you move an appropriate value to the
alternate key you want to use and issue a READ statement in which you specify which key you
want to use
MOVE "CHEVROLET" TO BRAND.
READ VEHICLES KEY BRAND INVALID KEY PERFORM NOT-FOUND.
The START Statement: Sometimes, it is necessary to find a set of records for which you want to
specify a criterion. For example, in our "vehicles" example, you might want to find the records of
"TOYOTA" brand vehicles. If the criterion is related to one of the keys, you will not have to go
through the whole file, testing the fields against a certain value. Instead, you can use the START
statement to find the first vehicle with "TOYOTA" recorded as the brand.
An example is:
START VEHICLES KEY BRAND IS EQUAL TO "TOYOTA"
INVALID KEY NO-SUCH-BRAND.
LOOP1.
READ VEHICLES NEXT AT END PERFORM END-OF-BRAND.
...
GO LOOP1.
...
Important: Please note that when you use the START statement, the file is accessed as a
RANDOM file; whereas the subsequent READ NEXT statements access the file in SEQUENTIAL
mode. This dilemma is solved by the ACCESS MODE IS DYNAMIC phrase in the SELECT
statement. When you declare the access mode to be DYNAMIC, you can access the file both
sequentially the NEXT option of the READ statement) and randomly by specifying a certain key
value. When you want to use the START statement you must open an index file either as INPUT
or I-O. The START statement is not allowed and in fact not meaningful when the file is opened for
OUTPUT.
Page 105
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
The records in these files are usually needed to be put in ascending or descending order for
proper and easy handling. (Remember that searching records in an ordered file (a file sorted in
respect to the field which is the search key; you can stop reading records when you find a record
which has the key field having greater value than the value you are searching for).
Sorting a set of data which will fit into arrays (therefore fitting into the memory) is quite easy.
(Remember the Internal Sort techniques you have learned in previous courses). Sorting large files
which will not fit into arrays in memory, on the other hand, is not easy. This requires special
algorithms to be implemented and generally called "EXTERNAL SORT TECHNIQUES".
Many COBOL compilers provide facilities to solve this "External Sort" problem. RM-COBOL, for
instance, has a very powerful SORT statement which will let the user SORT and MERGE
sequential files very easily.
SORTING does not need much explanation here. The MERGE process however, needs a little bit
explanation.
MERGING DATA is simply combining two or more SORTED sequential files together into a single
file so that the resulting file is also sorted. We shall not cover the MERGE facility of the COBOL
SORT statement in this course.
In order to use this SORT statement, you will have to declare 3 files;
The WORK FILE for the SORTING Process
The file to be sorted (input file)
The file which will contain the sorted records (output file)
The WORK FILE is not an actual file; it is a special declarative file structure with which you tell the
compiler that you will perform an external sort on a file and also indicate the fields on which you
shall set the sort criteria. The concept will become clearer with an example:
Suppose you have sequential file with personnel records (PERSONEL FILE) and you want to sort
this file on the persons' names and surnames. In order to use the SORT statement, you must
declare a SORT WORK file which will declare the structure of the records to be sorted and indicate
the lengths and positions of the fields which contain the names and surnames:
Page 106
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
The corresponding SORT WORK file declaration might look something like:
SD SORT-WORK-FILE.
01 PERS-REC.
02 ID-NO PIC X(8).
02 NAME PIC X(16).
02 SURNAME PIC X(16).
02 FILLER PIC X(107).
This declaration will enable the user to issue a SORT statement using the NAME and SURNAME
fields; into either ascending or descending order.
Please note that 108 byte filler is used in the SORT-WORK-FILE record description so that the
work file's record length matches the record length of the PERSONEL file. Please also note the
"SD" indicator used in place of "FD" in FILE SECTION.
You can perform sort on more than one field at time; and also you can sort into ascending order
(increasing) on one field, and into descending order (decreasing) on another. For example, while
sorting the PERSONEL file, you can declare the NAME field to be the primary sort field and the
SURNAME to be the secondary sort field; so that records with identical names will be sorted into
surnames among themselves. (Just like the entries in a telephone directory).
Referring to our PERSONEL file example, typical file declarations and a SORT statement would
look like:
Page 107
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
FD UNSORTED-PERSON.
01 FILLER PIC X(148).
FD SORTED-PERSON.
01 FILLER PIC X(148).
Notes:
The lengths of records in the work, input, and output files should match.
You do not need to declare the details of input and output file records if you do not
need these details in your program.
You should not OPEN or CLOSE the work, input and output files before, after or
during the SORT operation.
You can specify more than one sort field and the fields may have different ordering
(ascending/descending).
A complete RM-COBOL program which sorts the PERSONEL file, creating the sorted file
SPERSONL.DAT might look like:
Page 108
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Please study the SORT statement and its relevant file declarations carefully!
IDENTIFICATION DIVISION.
PROGRAM-ID. "SORT DEMO".
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
SOURCE-COMPUTER. RMCOBOL-85.
OBJECT-COMPUTER. RMCOBOL-85.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT SORT-FILE ASSIGN TO SORTWORK.
SELECT UNSORTED-PERSON ASSIGN TO PERSONEL
ORGANIZATION IS LINE SEQUENTIAL.
SELECT SORTED-PERSON ASSIGN TO SPERSONL
ORGANIZATION IS LINE SEQUENTIAL.
*
DATA DIVISION.
FILE SECTION.
SD SORT-FILE.
01 SORT-RECORD.
02 S-ID-NO PIC X(8).
02 S-NAME PIC X(16).
02 S-SURNAME PIC X(16).
02 S-GENDER PIC X.
02 S-DEPT-CODE PIC 9.
02 FILLER PIC X(89).
02 S-EMP-DATE.
03 S-EMP-DATE-DD PIC 99.
03 S-EMP-DATE-MM PIC 99.
03 S-EMP-DATE-YY PIC 9999.
02 S-LEAVE-DATE.
03 S-LEAVE-DATE-DD PIC 99.
03 S-LEAVE-DATE-MM PIC 99.
03 S-LEAVE-DATE-YY PIC 9999.
02 S-LEAVE-REASON PIC X.
FD UNSORTED-PERSON.
01 FILLER PIC X(148).
FD SORTED-PERSON.
01 FILLER PIC X(148).
*
PROCEDURE DIVISION.
Page 109
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
MAIN-PGM.
SORT SORT-FILE
ON ASCENDING KEY S-NAME S-SURNAME
ON DESCENDING S-EMP-DATE
USING UNSORTED-PERSON
GIVING SORTED-PERSON.
STOP RUN.
File operations
This section Covers File Handling, Input- output Statements for file, Sort and Merge of records.
OPEN
Page 110
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
CLOSE
READ
Format-1 - Sequential Read:
NEXT phrase is optional for SEQUENTIAL access mode & a must for DYNAMIC
When the READ NEXT statement is the first statement to be executed after the OPEN
statement on the file, the next record is the first record in the file
USAGE:
The sequential read is used when the exact key value is not known and if we want to
search the VSAM file for a particular key for processing.
This sequential read is also used when Alternate key is used as key to the indexed
file. This is because the alternate key may not be unique.
When we need to process records with part of the key matching, we use sequential
read. For E.G, The key field of the EMP-MATER file is Emp-no, Designation., date-of-
joining, if we want to process all employees belonging to designation “Associates”, we
use sequential read of the indexed file
Page 111
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
USAGE: Te random reading of indexed file is used when the key value for the file is exactly
known. The random read can be used in real time systems like Patient monitoring system in
hospitals. Here there might be necessary to retrieve a particular patient’s record. The full key value
for the Patient master file is known. Hence we use random read in this case. The random read of
indexed file is faster.
Page 112
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Example:
The FD entry is:
When the next record from the file is read into RECORD-2,
Contents of record being read in RECORD-2:
01234567890123456789
But since the record description contains two 01 levels and it’s a variable length file tents of record
area after second READ are executed:
01234567890123456789??????????
The last 10 characters of the record area are undefined. I.e. This storage area can hold any
characters depending on the sequence of reads and any process done inside the program using
RECORD-1. In the above example, assume there was no processing then the last 10 bytes would
contain “UVWXYZ1234”. But this area cannot be accessed, when we use RECORD-2 layout
because this is implicitly redefined item
Page 113
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
READ – Example:
File- Indexed, Dynamic Access
Record Description:
01 ASSOC-REC
05 ASSOC-NO-KEY PIC 9(4).
05 ASSOC-NAME PIC X(10).
Assoc # Assoc Name
0004 RAJESH
0010 RAMESH
0015 GOPAL
0016 RAGHAVAN
0100 SARITA
0401 RANI
Page 114
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
START
Enables the positioning of the pointer at a specific point in an indexed or relative file
File should be opened in Input or I-O mode
Access mode must be Sequential or Dynamic
Does not read the record
START file-name
[ KEY IS { EQUAL TO data-name]
=
GREATER THAN
>
NOT LESS THAN
NOT < THAN }
[ INVALID KEY imperative-stmt-1 ]
[ NOT INVALID KEY imperative-stmt-2 ]
[ END-START ]
START – Rules:
Invalid Key arises if the record position is empty
When KEY phrase is not specified KEY EQUAL TO primary key is implied
File position indicator points to the first record in the file whose key field satisfies the
comparison
When the KEY phrase is specified, the file position indicator is positioned at the logical
record in the file whose key field satisfies the comparison.
When the KEY phrase is not specified, KEY IS EQUAL (to the prime record key) is
implied.
When the START statement is executed, a comparison is made between the current
value in the key data-name and the corresponding key field in the file's index.
PROGRAM COLLATING SEQUENCE clause, if specified, has no effect
The file position indicator points to the first record in the file whose key field satisfies
the comparison. If the operands in the comparison are of unequal lengths, the
comparison proceeds as if the longer field were truncated on the right to the length of
the shorter field. All other numeric and nonnumeric comparison rules apply
Page 115
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
START
File- Indexed, Dynamic Access
Record Description:
01 ASSOC-REC
05 ASSOC-NO-KEY PIC 9(04).
05 ASSOC-NAME PIC X(10).
WRITE
[AT { END-OF-PAGE
EOP } imperative-statement-1]
[NOT AT { END-OF-PAGE
EOP } imperative-statement-1]
[END-WRITE]
Page 116
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Note:
Releases a record onto the output file
ADVANCING phrase is only for Printer Files
When this phrase is specified, the following rules apply:
When BEFORE ADVANCING is specified, the line is printed before the page is
advanced.
When AFTER ADVANCING is specified, the page is advanced before the line is
printed.
When identifier-2 is specified, the page is advanced the number of lines equal to the
current value in identifier-2. Identifier-2 must name an elementary integer data item.
o File Position is not affected by this statement
o When END-OF-PAGE is specified, and the logical end of the printed page is
reached during execution of the WRITE statement, the END-OF-PAGE
imperative-statement is executed
WRITE for Seq. Files: From its Record Area defined at 01 Level
WRITE ASSOC-REC
Page 117
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
REWRITE
Syntax – Format1:
Page 118
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Description: The REWRITE statement is used to replace records in a file. The record is replaced
within the file associated with record-name-1. If the FROM clause is included, the FROM item is
copied into record-name-1 before the data record is rewritten. If the record was locked during the
READ, the REWRITE will unlock the record automatically. Each of the two formats works slightly
differently, and is described below in its correspondingly numbered item.
The first format performs a sequential rewrite of the file. The last record read is
replaced by the contents of record-name-1.
The second format performs a random rewrite of the file. The last record read, will be
rewritten. If the record key has been changed, no record is replaced and the code
between INVALID KEY and NOT INVALID KEY, if any, will be executed. If the rewrite
is successful, the code between NOT INVALID KEY and END-REWRITE, if any, will
be executed.
Tips:
If there is a file status associated with the file, it will be set after the REWRITE is
executed to indicate the result of the REWRITE. A value of "00" means successful and
"23" means the record key was modified prior to the execution of the REWRITE.
Any file mentioned must be the subject of a SELECT statement and a file description
(FD). Files must be open for input/output and read prior to executing the REWRITE
statement.
When used in a program with a SORT statement, the sort file itself can never be
rewritten.
Be sure to READ the record you wish to update and change the desired fields before
executing the REWRITE statement.
REWRITE – Rules:
File should be opened in I-O
After REWRITE record is not available in the rec area
After a REWRITE statement with the FROM phrase is executed, the information is still
available in identifier-1
Page 119
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
DELETE
Syntax – Format1:
DELETE file-name-1 RECORD
[INVALID KEY imperative-statement-1]
[NOT INVALID KEY imperative-statement-2]
[END-DELETE]
Description:
Removes a record from an indexed or relative file
For indexed files, the key can then be reused for record addition.
For relative files, the space is then available for a new record with the same
RELATIVE KEY value.
If the FILE STATUS clause is specified in the File-Control entry, the associated status
key is updated when the DELETE statement is executed.
The file position indicator is not affected by execution of the DELETE statement.
For a file in sequential access mode, the last input/output statement must have been a
successfully executed READ statement. When the DELETE statement is executed,
the system removes the record retrieved by that READ statement.
For a file in sequential access mode, the INVALID KEY and NOT INVALID KEY
phrases must not be specified. However, an EXCEPTIONERROR procedure can be
specified.
When the DELETE statement is executed, the system removes the record identified
by the contents of the prime RECORD KEY data item for VSAM indexed files, or the
RELATIVE KEY data item for VSAM relative files. If the file does not contain such a
record, an INVALID KEY condition exists.
DELETE – Rules:
File should opened for I-O
In sequential access mode, the last input/output statement must have been a
successfully executed READ
o INVALID key not allowed
For Random or Dynamic access system removes record pointed by the RECORD key
(KSDS) or RELATIVE key(RRDS)
Page 120
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
SORT
While processing sequential files, it is sometimes necessary that the records should
appear in some predetermined sequence. The process of sequencing records in file in
some predetermined order on some fields is called SORTING
The fields based on which the records are sequenced are called SORT KEYS.
The sequencing can be ascending or descending order of the KEY.
Tips:
All of the files referenced must be closed when the SORT statement is executed.
The key fields must all be defined in the record description(s) for the sort file.
The sort file cannot be opened or closed.
If the USING option is used, the USING file must have the same record layout as the
sort file.
If the GIVING option is used, the GIVING file must have the same record layout as the
sort file.
Example:
Assume the following record description for the input file
Page 121
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
FD EMP-FILE.
EMP-REC.
02 ID-NUM PIC 9(6).
02 NAME PIC X(24).
02 DEPARTMENT PIC X(10).
02 BASIC-PAY PIC 9(5)V99.
02 ALLOWANCE PIC 9(4)V99.
02 DEDUCTION PIC 9(4)V99.
We want to sort this file on DEPARTMENT on ascending sequence and then within each
DEPARTMENT, arrange BASIC-PAY on descending sequence. This means that the records with
same DEPARTMENT value are to be arranged from highest to lowest value of the BASIC-PAY.
The work file and output files are SORT-FILE and OUTPUT-FILE. The FD and SD entries for these
files are as follows:
SD SORT-FILE
01 SORT-REC.
02 FILLER PIC X(30).
02 DEPARTMENT PIC X(10).
02 BASIC-PAY PIC 9(5)V99.
02 FILLER PIC X(12).
FD OUTPUT-FILE
OUT-REC PIC X(59).
For example, a file with variable length records will require some padding with some characters to
make it fixed length for the purpose of sorting.
The sort verb allows user to specify the INPUT & OUTPUT PROCEDURE in the sort statement,
which perform the necessary processing of the records.
The input and output procedures are nothing but sections placed outside the SORT statement.
INPUT PROCEDURE: The sort statement before the start of the sorting process implicitly
performs the specified input procedure. These procedures reads the records from input file,
performs the necessary processing, and then release the records to Sorting operation by
RELEASE statement which is discussed later in this chapter
Page 122
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
OUTPUT PROCEDURE: The output procedure is performed implicitly by sort statement in order to
perform editing on the sorted records. The output procedure gets the sorted records by means of
RETURN statement that is discussed later in this session.
SORT file-1 { ON
{ASCENDING
DESCENDING} KEY id-1... } ...
[WITH DUPLICATES IN ORDER]
[COLLATING SEQUENCE IS alphabet-name-1]
{USING file-2
INPUT PROCEDURE IS
proc-nm-1 [THRU proc-nm-2]}
{GIVING file-3
OUTPUT PROCEDURE IS
proc-nm-3 [THRU proc-nm-4]}
SORT sorted-emp-file
ASCENDING s-last-nm
s-first-nm
DESCENDING s-emp-nbr
USING emp-file
OUTPUT PROCEDURE
write-emp-list THRU
write-emp-list-exit
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT EMP-FILE ASSIGN TO EMPMSTR.
SELECT SORTED-EMP-FILE ASSIGN TO EMPSORT.
SELECT EMP-LIST ASSIGN TO REPORT.
DATA DIVISION.
FILE SECTION.
FD EMP-FILE
LABEL RECORDS ARE OMITTED.
01 EMP-REC.
05 EMP-NBR PIC 9(4).
05 LAST-NM PIC X(20).
05 FIRST-NM PIC X(20).
05 MID-NM PIC X(20).
SD SORTED-EMP-FILE
LABEL RECORDS ARE OMITTED.
Page 123
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
01 SORT-EMP-REC.
05 S-EMP-NBR PIC 9(4).
05 S-LAST-NM PIC X(20).
05 S-FIRST-NM PIC X(20).
05 S-MID-NM PIC X(20).
PROCEDURE DIVISION.
.....
SORT sorted-emp-file
ASCENDING s-last-nm s-first-nm
DESCENDING s-emp-nbr
USING emp-file
OUTPUT PROCEDURE write-emp-list THRU
write-emp-list-exit
...
WRITE-EMP-LIST.
...
WRITE-EMP-LIST-EXIT.
EXIT.
Collating Sequences:
COLLATING SEQUENCE option of the SORT statement that is defined in SPECIAL-
NAMES paragraph
PROGRAM COLLATING SEQUENCE if specified in the Configuration Section
Default is EBCDIC
RELEASE
Transfers records to the initial phase of sort operation
It’s like WRITE statement
Tips:
The RELEASE statement is the equivalent of a WRITE statement, except that is used
exclusively for SORT files.
An INPUT PROCEDURE must contain at least one RELEASE statement.
The RELEASE statement may only be used within the context of an INPUT
PROCEDURE.
Page 124
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
RELEASE Example:
MOVE emp-rec TO sort-emp-rec
RELEASE sort-emp-rec
RELEASE sort-emp-rec
FROM emp-rec
RETURN
Transfers records from the final phase of a sorting or merging operation to an
OUTPUT PROCEDURE.
It’s like READ statement
RETURN – Rules: If OUTPUT PROCEDURE is used, at-least one RETURN stmt must be
executed
RETURN - Examples
read-sorted-rec.
RETURN sorted-emp-file
AT END
SET c-sort-eof TO TRUE
END-RETURN
.
read-sorted-rec-exit.
EXIT.
WRITE-EMP-LIST.
SET c-not-sort-eof TO TRUE
PERFORM read-sorted-rec
THRU read-sorted-rec-exit
PERFORM UNTIL c-sort-eof
PERFORM string-emp-name
THRU string-emp-name-exit
MOVE w-emp-name TO rep-name
MOVE s-emp-nbr TO rep-emp-nbr
WRITE emp-list-rec
PERFORM read-sorted-rec
Page 125
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
THRU read-sorted-rec-exit
END-PERFORM
.
WRITE-EMP-LIST-EXIT.
EXIT.
MERGE
Sometimes it becomes necessary to create a new output file from 2 input files. These 2 files needs
to be merged and new file needs to be created
For example A Company has its marketing operations divided into 2 zones and for each zone
there is file. Each of these files contains zone name, district name, salesman name, product name
and amount of sales for a particular product. The files are sorted on product name. We need to
merge these 2 files into a single file to get a single transaction file to update the master file.
The MERGE verb is used to merge 2 or more identical files sorted on the same field
Syntax – Format:
Page 126
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
MERGE – Examples:
MERGE sorted-emp-ph-file
ASCENDING s-last-nm
s-first-nm
DESCENDING s-emp-nbr
USING emp-ph-file
emp-addon-ph-file
GIVING new-emp-ph-file
MERGE – Rules:
When USING / GIVING option is specified the input / output file(s) to merge must not
be open
The key used in the MERGE statement cannot be variably located.
When the file referenced by filename-1 is merged control passes to first stmt in the
OUTPUT PROCEDURE.
Collating Sequences:
o COLLATING SEQUENCE option of MERGE statement that is defined in
SPECIAL-NAMES paragraph
o PROGRAM COLLATING SEQUENCE specified in the Configuration Section
o Default is EBCDIC
THE END-OF-FILE PHRASE (AT END): An end-of-file condition may or may not represent an
error. In many designs, reading sequentially to the end of a file is done intentionally, and the AT
END condition is expected.
For example, suppose you are processing a file containing transactions in order to update a
master file:
PERFORM UNTIL TRANSACTION-EOF = "TRUE"
READ UPDATE-TRANSACTION-FILE INTO WS-TRANSACTION-RECORD
AT END
DISPLAY "END OF TRANSACTION UPDATE FILE REACHED"
MOVE "TRUE" TO TRANSACTION-EOF
END READ
.
.
.
END-PERFORM
Page 127
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
In some cases, however, the condition will reflect an error. You code the AT END phrase of the
READ statement to handle either case, according to your program design.
If you code an AT END phrase, upon end-of-file the phrase is executed. If you do not code an AT
END phrase, the associated ERROR declarative is executed. Following an AT END condition, the
contents of the associated record area are undefined, and attempts to move data to or from the
associated record may result in a protection exception.
EXCEPTION/ERROR Declarative: You can code one or more ERROR declarative procedures in
your program that will be given control if an input/output error occurs. You can have:
FILE STATUS key: The system updates the FILE STATUS key after each input/output statement
executed for a file placing values in the two digits of the file status key. In general, a zero in the
first digit indicates a successful operation and a zero in both digits means "nothing abnormal to
report". Establish a FILE STATUS key using the FILE STATUS clause in the FILE-CONTROL and
data definitions in the Data Division.
Page 128
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Summary
File organizations supported by COBOL:
o Sequential organization
o Relative organization (Random organization or Direct Access)
o Indexed Sequential organization
Files are to be defined in the Environment Division using SELECT clause and in the
Data Division for the Layout Records
Files can be opened in either INPUT Mode, OUTPUT Mode, Input-Output Mode (or)
EXTEND Mode
File Operations that can be done are OPEN, START, READ, WRITE, REWRITE,
CLOSE
The result of the I/O operations can be validated against the status codes generated.
The master file is the indexed file with the same fields as above.
This transaction file records needs to be inserted in the master indexed file if the emp-no is
not present and if the emp-status id NA (new active). If the records are present and if the
emp-status id is TT the emp record from the master file needs to be deleted as he is a
terminated employee. If the record is present, and the emp status is OA which is old
active, the record in the indexed file needs to be updated.
a) Write the COBOL code to do the processing of the transaction and master files.
COBOL code includes environment division, data division and procedure division
entries.
Page 129
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Learning Objectives
After completing this session, you will be able to:
Describe the various concepts table handling
Introduction
Sometimes it becomes necessary to handle group of data consisting of similar items. Such a group
is called a Table or Array. An array is used to store similar items or elements. For example, a
series of totals in the working storage with the same format.
A table is a list of stored fields that are looked up or referenced by the program. It also eliminates
the need for separate entries for repeated data items. The usage of tables can be illustrated by the
following example
For example when you need to list the months in normal way of representing it is:
MONTH-TABLE.
02 MON-1 PIC X(9) VALUE ‘JANUARYbb‘.
02 MON-2 PIC X(9) VALUE ‘FEBRUARYb ‘.
02 MON-3 PIC X(9) VALUE ‘MARCHbbbb‘.
02 MON-4 PIC X(9) VALUE ‘APRILbbbb‘.
02 MON-5 PIC X(9) VALUE ‘MAY bbbbbb‘.
02 MON-6 PIC X(9) VALUE ‘JUNEbbbbbb‘.
02 MON-7 PIC X(9) VALUE ‘JULYbbbbbb‘.
02 MON-8 PIC X(9) VALUE ‘AUGUSTbbb‘.
02 MON-9 PIC X(9) VALUE ‘SEPTEMBER‘.
02 MON-10 PIC X(9) VALUE ‘OCTOBERbb‘.
02 MON-11 PIC X(9) VALUE ‘NOVEMBERb‘.
02 MON-12 PIC X(9) VALUE ‘DECEMBERb‘.
In the above example, the same data month name is being repeated 12 times. Instead of defining
the elements like this we can define it as a table with 12 elements. Each element of the table can
be referred using a Subscript or an index. Now lets us look at how the table can be defined in
COBOL
01 MONTH-TABLE.
02 MON-NAME PIC X (9) OCCURS 12 TIMES.
This table can be fixed length tables and Variable length tables. The tables or Arrays are define
using OCCURS in COBOL. Now let us look at Occurs clause in detail.
Page 130
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Occurs
Used for defining Tables (Arrays)
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.
Occurs clause can be specified for elementary or group item.
VALUE clause cannot be specified for associated data name defined with OCCURS
clause or any sub item to the occurs clause
REDEFINES and OCCURS clause cannot appear for the same data item. However
REDEFINES clause can appear for a group item whose sub item contains occurs
clause
The ‘occurs’ clause is used to define single dimension and multi-dimensional tables.
Tables can be Fixed Length or Variable Length
Can’t be defined for a data item which:
o Has a level number of 01, 66, 77, or 88.
o Describes a redefined data item
[ {ASCENDING KEY IS
DESCENDING }
dataname-2 [ ... ] ]
Page 131
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Example
03 YEAR PIC 9(4) OCCURS 10 TIMES INDEXED BY I1.
In the above example the displacement of first element is zero, 2nd is 4, 3rd is 8 and so on. That is
the index I1 assumes these values for occurrence numbers 1, 2, 3, and so on.
The value of Index item is set by the occurrence number and not the internal value
The value of index is set using SET clause. The statements like Move or Add cannot
be used on index
Index name is implicitly defined
Index name cannot be associated with any other data hierarchy
Must be initialized before it can be used using SET and PERFORM VARYING
Example:
77 A1 PIC 99
REC-1.
P1 PIC XX.
02 P2 PIC 99 OCCURS 1 TO 90 TIMES DEPENDING ON A1.
In this example depending on the value of A1, the size of the table may vary from 1 to 90.
[{ASCENDING KEY IS
DESCENDING }
dataname-2 [ ... ] ]
[ INDEXED BY index-name-1 [ ... ] ]
Object of the OCCURS DEPENDING ON (ODO) clause cannot be variably located;
If subject of OCCURS is defined as EXTERNAL then ODO ought to be defined as
EXTERNAL
The int-1 and int-2 defined must be positive integers.
The data name-1 can be defined at the same level as ODO but it cannot be defined as
sub item to ODO.
Page 132
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Example:
01 REC-1.
02 A1 PIC 99.
02 P1 PIC XX.
02 P2 PIC 99 OCCURS 1 TO 90 DEPENDING ON A1.
The above example is valid.
01 REC-1.
02 P1 PIC XX.
02 P2 PIC 99 OCCURS 1 TO 90 DEPENDING ON A1.
02 A1 PIC 99.
SET
Syntax – Format1:
index-name-2
SET { index-name-1
identifier-1 } ... TO { identifier-2
integer-1
}
Syntax – Format2:
Syntax – Format4:
SET {condition-name-1} ... TO TRUE...
Page 133
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Description: The SET statement is used to set values for indices and conditions. Each of the four
formats works differently and is described below in the correspondingly numbered item.
The first format of the SET statement is used to assign values to indices or assign the
value of an index to another variable. The variable(s) between SET and TO is set to
the value of the data item or literal following TO.
The second format of the SET statement is used to increase or decrease the value of
an index. The variable(s) between SET and UP or DOWN is INCREASED (for UP) or
DECREASED (for DOWN) by the value of the data item or literal following BY.
The third format of the SET statement is used to set the value of an external switch.
The mnemonic(s) between SET and TO is set to ON or OFF according to the ON or
OFF option supplied.
The fourth format of the SET statement is used to set the condition-name conditions to
true. The condition(s) between SET and TO is set to TRUE.
Tips:
Regular MOVE and mathematical statements do not work on indices. Use the SET
statement to manipulate an index.
For format 4, if more than one value is associated with the condition-name being true,
the first value listed is the one that will be used.
SET – Examples:
05 TABLE-ITEM OCCURS 10
INDEXED BY INX-A PIC X (8).
Receiving Fields
Sending fields Index Name Index Data Item Integer Data Item
Index Name V V* V
Index data item V* V* -
Integer data item V - -
Numeric literal V - -
Note: * - No Conversion
Page 134
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Complex Tables
Data item with Occurs Depending On is followed by:
o Non-subordinate item
o Non-subordinate item with Occurs Depending On
Data item with Occurs Depending On is nested
5
15 REC-2 OCCURS 1 TO 3 DEPENDING ON CTR2.
20 DATA-NUM PIC S99.
1 -A group item of variable length
2 - An elementary data item following, and not subordinate to, a variable length table
(variably located item)
3 - A group item following, and not subordinate to, a variable-length table
4 - An index name for a table that has variable length elements
5 - An element of a table that has variable-length elements
Watch out:
The location of non-subordinate items following the item with OCCURS clause is
affected by new value of the ODO object. f you want to preserve the contents of these
items, prior to the change in the ODO object, save all non-subordinate items following
the variable item and after the change in the ODO object, restore all the items back.
Careful when using complex-ODO index names. In the example if the value of the
ODO object CTR2 is changed then the offset in index INDX is no longer valid for the
table TABLE-2.
To avoid making this error save the value of index as an occurrence number before
changing ODO object.
Page 135
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
After changing ODO object, restore the value of index name from the integer data item
77 INT-DATA-1 PIC 99.
77 NEW-VALUE PIC S99.
SET INT-DATA-1 TO INDX
MOVE NEW-VALUE TO CTR2
SET INDX TO INT-DATA-1
OCCURS – Example:
WORKING STORAGE SECTION.
01 TABLE-RECORD.
05 EMP-TABLE OCCURS 100 ASCENDING KEY IS
WAGE-RATE EMP-NO INDEXED BY A, B.
10 EMP-NAME PIC X (20).
10 EMP-NO PIC 9(6).
10 WAGE-RATE PIC 9999V99.
10 WEEK-RECORD OCCURS 52 ASCENDING
KEY IS WEEK-NO INDEXED BY C.
15 WEEK-NO PIC 99.
15 ABSENCES PIC 99.
Table Processing
Now we have seen how to define tables of various sizes and dimension, we now see how to
process these tables using PERFORM verb.
Example:
Consider the following example:
77 A1 PIC 99.
01 PRICE-1 PIC S9 (7) V99.
DATA-REC.
05 PRODUCT-CODE PIC X (6)
05 PRICE-REC OCCURS 36 TIMES.
10 PERIOD PIC X (10).
10 PROD-PRICE PIC S9 (7) V99.
Now we want to find the average price of the product for a period.
MOVE ZERO TO TOTAL.
MOVE 1 TO A1.
PERFORM ADD-PRICE-PARA 36 TIMES.
COMPUTE AVERAGE = TOTAL / 36
ADD-PRICE-PARA.
COMPUTE TOTAL = PROD-PRICE (A1) + TOTAL
ADD 1 TO A1.
Page 136
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
This is one form of PERFORM statement used for FIXED length tables.
Now you want to find the price of a product for period 011999 (mmyyyy)
MOVE 1 TO A1
PERFORM FIND-PRICE-PARA UNTIL
(PERIOD = ‘011999’ OR
A1 > 36)
FIND-PRICE-PARA
IF PERIOD = ‘011999’
MOVE PROD-PRICE (A1) TO PRICE-1
END-IF
ADD 1 TO A1
In this form, the paragraph is executed repetitively until the period id 011999 or until the subscript
of the table is greater than the maximum table limits.
The same fixed length table can be defined as variable length table.
In this case again you want to find the price of a product for period 011999(mmyyyy)
77 PRICE-1 PIC S9 (7) V99.
01 DATA-REC.
05 PRODUCT PIC X(10).
05 TAB-CNT PIC S9(04) COMP.
05 DATA-TABLE OCCURS 1 TO 37 TIMES
DEPENDING ON TAB-CNT
INDEXED BY INX-1.
07 PERIOD PIC X(6).
07 PROD-PRICE PIC S9(7)V9(02).
PROCEDURE DIVISION.
SET INX-1 TO 1.
PERFORM FIND-PRICE-PARA VARYING INX-1 BY 1 UNTIL
INX-1 > TAB-CNT OR
PERIOD = ‘011999’
FIND-PRICE-PARA
IF PERIOD = ‘011999’
MOVE PROD-PRICE(INX-1) TO PRICE-1
END-IF
In the earlier statement the increment of the INDEX is not given explicitly.
It is done automatically:
Either fixed length or variable length the table can be in the sorted order by defining a
key for the table.
Page 137
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
The sorted table reduces the time of search, when a search is performed on the table.
The data have to be sorted in the correct order (ascending or descending) by the
programmer.
Search
To search a table element that satisfies a specified condition
Options
SEARCH VARYING
LINEAR SEARCH
SEARCH ALL
Binary Search, valid only for sorted tables with key specified.
SEARCH - Sequential
Syntax – Format:
Page 138
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
satisfied before the index value reaches the size of the table, the statements following
the WHEN clause is executed. If these statements are not present, then execution is
transferred to next statement. The value of the index remains set at the point where
the condition has been satisfied.
When the SEARCH terminates without finding the necessary value, the index contains
unpredictable values.
Example
77 NAME PIC X(20).
05 ASSOC-TABLE OCCURS 350 TIMES
INDEXED BY I-1.
10 ASSOC-NAME PIC X (20).
10 ASSOC-NUM PIC 9(4).
SET I-1 TO 1.
SEARCH ASSOC-TABLE
AT END
DISPLAY ‘NAME NOT FOUND’
WHEN NAME = ASSOC-NAME (I-1)
DISPLAY ‘NAME FOUND’.
Page 139
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
START
If the value
of index Execute Go to next
YES
associated imperative executable
with id-1 is statement
statement-1
> size of the
table
NO
Is YES Go to next
condition-1 Execute executable
true? imperative statement
statement-2
NO
Is Go to next
condition- YES
Execute executable
2 true? imperative statement
statement-3
NO
Index associated
with id-1 is
incremented by 1
id-2/index-name-
1 is incremented
by 1
Page 140
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
SEARCH ALL
Syntax – Format:
SEARCH ALL identifier-3
IS identifier-4
identifier-
{ EQUAL
}{ literal-1
}}
WHEN
{ 3 TO
IS =
arithmetic-
expression-1
condition-name-1
IS identifier-6
identifier-
{ EQUAL
}{ literal-2
} }]
[ { AND 5 TO
IS =
arithmetic-
expression-2
condition-name-2
imperative-
{ statement-4
NEXT SENTENCE
}}
[END-SEARCH]
Page 141
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Summary
Tables in COBOL are declared using the OCCURS clause and can be of single
dimension and multiple dimensions
Indexes and subscripts are used to access the individual elements of the table
SEARCH statement is used to extract a particular element from a Table based on a
criteria
SERACH ALL is faster than SERACH but required the table to be sorted as it perform
Binary search on the table.
Page 142
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Indicate how many elements of the array A would be added to TOTAL and what will be the
final value of TOTAL when the control goes to PARA-2 in the following program segment?
MOVE ZERO TO TOTAL.
PERFORM PARA-1 VARYING I FROM 1 BY 2 UNTIL I > 9.
GO TO PARA-2
PARA-1.
ADD A (I) TO TOTAL.
PARA-2.
4. A table contains the monthly sales data for 12 months of the year and for the 4 sales
zones where each zone has 8 districts. Write the PROCEDURE DIVISION statements to
find the total sale of each district within each zone and then find the total sale of each
zone. Store these totals in 2 tables - one district total and the other containing the zone
totals. Write the data division entries to define all these tables. The following is a
PROCEDURE DIVISION statement.
PERFORM PARA-AGAIN VARYING I FROM 1 BY 1 UNTIL I > 4
AFTER J FROM 0 BY –1 UNTIL J < -2
AFTER K FROM 1 BY 2 UNTIL K > 8.
a) How many times is the procedure named PARA-AGAIN executed? Which data
name varied least rapidly and which varied most rapidly.
Page 143
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Learning Objectives
After completing this session, you will be able to:
Explain the concepts of calling a sub-program
Call
Transfers control from one object program to another within the run unit.
Called program starts executing from:
o Top of program
o ENTRY label (not good programming practice)
Transfer control methods:
o Call nested program
o Static call
o Dynamic call
Parameters to called program:
o By reference
o By content
Use RETURN-CODE special register to pass return codes
Return of control depends on the termination stmt issued by the called program:
o Stop run unit
o Return to called program
Syntax – Format1:
CALL { identifier-1
literal-1 }
identifier-2
BY
REFERENCE { ADDRESS OF
identifier-3
file-name-1
} ...
[ USING
{ BY CONTENT
{
identifier-2
ADDRESS OF
identifier-3
} ... }]
literal-2
identifier-
{ 2
literal-2
} ...
Page 144
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
[END-CALL]
Syntax – Format2:
CALL { identifier-1
literal-1 }
identifier-2
BY
REFERENCE { ADDRESS OF
identifier-3
file-name-1
} ...
[ USING
{ BY CONTENT
{
identifier-2
ADDRESS OF
identifier-3
} ... }]
literal-2
identifier-
{ 2
literal-2
} ...
Description: The CALL statement is used to call other programs. While the format of the CALL
itself is the same for both formats; the error handling for each is different, each is described in the
correspondingly numbered area. For the primary part of the call, each item after the USING
represents a parameter which is to be passed to the called subprogram. BY REFERENCE means
the actual item will be passed and the item may be modified by the subprogram. BY CONTENT
means that only the value of the item will be passed and the item may not be modified by the
subprogram. If neither option is specified, the items are passed as by reference parameters.
The first format is used to check for overflow errors. An overflow occurs when there is
not enough memory available to hold the called subprogram. If such an error occurs,
the code between ON OVERFLOW and END-CALL will be executed. If no error
occurs, control will pass to the statement following the END-CALL.
The second format is used to check for the occurrence of any error. If such an error
occurs, the code between ON EXCEPTION and NOT ON EXCEPTION or END-CALL
will be executed. If no error occurs, code between NOT ON EXCEPTION and the
END-CALL will be executed.
Tips: he CALL statement is used to execute code outside of your program. To execute code within
your program, use the PERFORM statement.
Page 145
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
CALL – Examples:
CALL ‘SUBPGM1’.
CALL l-SUBPGM-1 USING
l-PARM1 l-PARM2.
CALL l-SUBPGM1 USING
BY CONTENT l-PARM1
l-PARM2
BY REFERENCE l-PARM3.
01 l-parm1.
05 l-name pic x(30).
05 l-emp-no pic 9(4).
01 l-parm2.
05 l-salary pic s9(9)v99 comp-3.
05 l-hra pic s9(9)v99 comp-3.
05 l-leave pic s9(2)v9 comp-3.
01 l-parm3.
05 l-gross pic s9(9)v99 comp-3.
05 l-deduct pic s9(9)v99 comp-3.
PROCEDURE DIVISION.
....
CALL l-SUBPGM1 USING
BY CONTENT l-PARM1 l-PARM2
BY REFERENCE l-PARM3.
IDENTIFICATION DIVISION.
PROGRAM-ID. 1-SUBPGM1.
…
LINKAGE SECTION.
01 L-PARM3.
05 l-gross pic s9(9)v99 comp-3.
05 l-deduct pic s9(9)v99 comp-3.
01 L-PARM1.
05 l-name pic x(30).
05 l-emp-no pic 9(4).
01 L-PARM2.
05 l-salary pic s9 (9) v99 comp-3.
05 l-hra pic s9(9)v99 comp-3.
Page 146
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
CALL - Rules
The correspondence of identifiers in the using clause of called and calling programs
is positional
File-name in using is only for QSAM files
Address of option can be used only for Linkage variables with level 01 or 77
Exception or Overflow condition occurs when the called program cannot be made
available.
Called program must not execute a CALL statement that directly or indirectly calls the
calling program (Recursion not allowed)
Cancel
CANCEL {id-1 lit-1}:
Ensures that the next time the referenced subprogram is called it will be entered in its
initial state.
All programs contained in the Cancelled program are also cancelled.
Same as executing an EXIT PROGRAM or GOBACK in the called subprogram if it
possesses the INITIAL attrib.
Entry
ENTRY lit-1 [USING id-1 ...]:
Establishes an alternate entry point
Execution of the called program begins at the first executable stmt following the
ENTRY stmt whose literal corresponds to the CALL stmt literal or identifier
Not a recommended way of entering a program
Exit
EXIT PROGRAM:
Specifies the end of a called program and returns control to the calling program
When no CALL statement is active, control passes through the exit point to the next
executable stmt
Page 147
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Stop
STOP {RUN
lit-1}
Halts execution of the program:
o Permanently (RUN option)
o Temporarily (Lit-1 option)
Literal communicated to operator and execution suspended
Program execution is resumed only after operator intervention
STOP RUN statement closes all files defined in any of the programs comprising the run unit.
GOBACK
GOBACK:
Functions like:
o EXIT PROGRAM statement when coded in a called program
o STOP RUN statement when coded in a main program.
END PROGRAM
END PROGRAM program-name:
An END PROGRAM header terminates a nested program or separates one program
from another in a sequence of programs.
The program-name must be same as the program-name declared in the
corresponding PROGRAM-ID paragraph.
An END PROGRAM is optional for the last program in a sequence only if that program
does not contain any nested source programs.
Usage Clause
The data can be stored in more than one internal form in the computer. In COBOL, a programmer
is allowed to specify the internal form of the data item so as to facilitate the use of the data item
more efficiently. The USAGE clause specifies the format of a data item in computer storage. These
are forms of internal representation
Computational
Display
Pointer
Packed – decimal
Page 148
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
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.
The amount of storage occupied by a binary item depends on the number of decimal
digits defined in its PICTURE clause:
Digits in PICTURE Clause Storage Occupied
1 through 4 2 bytes (half word)
5 through 9 4 bytes (full word)
10 through 18 8 bytes (double word)
Page 149
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
The sign is stored separately as rightmost half-a-byte regardless of whether S is specified in the
PIC clause or not. The hexadecimal number C or F denotes positive sign and D denotes negative
sign.
The number of bytes = n+1/2 Where n is the number of places specified in PIC clause
For example:
77 ITEM-1 PIC S9(7) COMP-3
Will occupy 4 bytes:
COMPUTATIONAL-4 or COMP-4 (Binary)
This is the equivalent of BINARY.
DISPLAY: The data item is stored in character form, 1 character for each 8-bit byte. This
corresponds to the format used for printed output.
INDEX:
A data item defined with the INDEX phrase is an index data 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.
Direct references to an index data item can be made only in a SEARCH statement, a
SET statement, a relation condition, the USING phrase of the Procedure Division
header, or the USING phrase of the CALL statement.
An index data item can be part of a group item referred to in a MOVE statement or an
input/output statement.
Page 150
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
An index data item saves values that represent table occurrences, yet is not
necessarily defined as part of any table. Thus, when it is referred to directly in a
SEARCH or SET statement, or indirectly in a MOVE or input/output statement, there is
no conversion of values when the statement is executed.
The USAGE IS INDEX clause can be written at any level. If a group item is described
with the USAGE IS INDEX clause, the elementary items within the group are index
data items; the group itself is not an index data item, and the group name cannot be
used in SEARCH and SET statements or in relation conditions. The USAGE clause of
an elementary item cannot contradict the USAGE clause of a group to which the item
belongs.
An index data item cannot be a conditional variable.
The DATE FORMAT, JUSTIFIED, PICTURE, BLANK WHEN ZERO,
SYNCHRONIZED, or VALUE clauses cannot be used to describe group or elementary
items described with the USAGE IS INDEX clause.
SYNCHRONIZED can be used with USAGE IS INDEX to obtain efficient use of the
index data item.
POINTER:
A data item defined with USAGE IS POINTER is a pointer data item. A pointer data item is a 4-
byte elementary item.
You can use pointer data items to accomplish limited base addressing. Pointer data items can be
compared for equality or moved to other pointer items.
The USAGE IS POINTER clause can be written at any level except level 88. If a group item is
described with the USAGE IS POINTER clause, the elementary items within the group are pointer
data items; the group itself is not a pointer data item and cannot be used in the syntax where a
pointer data item is allowed. The USAGE clause of an elementary item cannot contradict the
USAGE clause of a group to which the item belongs.
Pointer data items can be part of a group that is referred to in a MOVE statement or an
input/output statement. However, if a pointer data item is part of a group, there is no conversion of
values when the statement is executed.
A pointer data item can be the subject or object of a REDEFINES clause.
SYNCHRONIZED can be used with USAGE IS POINTER to obtain efficient use of the
pointer data item.
A VALUE clause for a pointer data item can contain only NULL or NULLS.
A pointer data item cannot be a conditional variable.
A pointer data item does not belong to any class or category.
Page 151
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
The DATE FORMAT, JUSTIFIED, PICTURE, and BLANK WHEN ZERO clauses
cannot be used to describe group or elementary items defined with the USAGE IS
POINTER clause.
Pointer data items are ignored in CORRESPONDING operations.
A pointer data item can be written to a data set, but, upon subsequent reading of the
record containing the pointer, the address contained can no longer represent a valid
pointer.
USAGE IS POINTER is implicitly specified for the ADDRESS OF special register.
Tips:
Use the CONTINUE statement in conditional code when no action is required for that
particular condition.
It is not necessary to code a CONTINUE statement in an ELSE when no action is
required for that particular condition. If no action is required for an ELSE, do not code
the ELSE, simply code the END-IF.
Page 152
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Example 1:
Example 2:
Page 153
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Summary
Calling program: The program that references or calls another subprogram
Called program: The subprogram that is linked and executed within the calling
program
Use of Linkage Section:
o Data transfer from JCL to program
o Data transfer across COBOL programs
Types of calls are static and dynamic
STOP RUN and GO BACK terminate the job execution, and delete all dynamically
called programs in the run unit and all programs link-edited with them.
The REDEFINES clause allows you to define the same storage area in main memory
for different data items whose lengths are not described as variable in an OCCURS
clause.
Page 154
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Learning Objectives
After completing this session, you will be able to:
Explain the overview of programming for DB2 environment
Apply SQL include
Test the Return Code of SQL statements
Compile Cobol code involving SQL statements using DB2 coprocessor
To retrieve, update, insert, and delete DB2 data and apply other DB2 services, you must
implement SQL statements.
Application of SQL Include: A SQL INCLUDE statement is treated identically to a native COBOL
COPY statement.
Example:
EXEC SQL INCLUDE name
COPY name
DCLGEN stands for Declarations Generator. It is a facility to generate DB2 SQL data structures in
COBOL or PL/I programs.
The library search order for SQL INCLUDE statements is the same SYSLIB concatenation as the
compiler uses to resolve COBOL COPY statements that do not specify a library name.
Page 155
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
DB2 Coprocessor: When you use the DB2 coprocessor (called SQL statement coprocessor by
DB2), the compiler handles your source program containing embedded SQL statements without
your having to use a separate precompiled step. When the compiler encounters SQL statements
at significant points in the source program, it interfaces with the DB2 coprocessor. This
coprocessor takes appropriate actions on the SQL statements and indicates to the compiler what
native COBOL statements to generate for them.
Although the use of a separate precompiled step continues to be supported, use of the
coprocessor is recommended. Interactive debugging with Debug Tool is enhanced when you use
the coprocessor because you only see the SQL statements in the listing (and not the generated
COBOL source). However, you must have DB2 for OS/390 Version 7 or later. The DB2
coprocessor is not supported on VM.
Compiling with the DB2 coprocessor generates a DB2 database request module (DBRM) along
with the usual COBOL compiler outputs such as object module and listing. The DBRM writes to the
data set that you specified on the DBRMLIBB DD statement in the JCL for the COBOL compile
step. As input to the DB2 bind process, the DBRM data set contains information about the SQL
statements and host variables in the program.
The COBOL compiler listing includes the error diagnostics (such as syntax errors in the SQL
statements) that the DB2 coprocessor generates. Certain restrictions on the use of COBOL
language that apply when you use the precompiled step do not apply when you use the DB2
coprocessor:
You can use SQL statements in any nested program. (With the pre-compiler, SQL
statements are restricted to the outermost program.)
You can use SQL statements in copy books.
REPLACE statements work on SQL statements.
CICS commands are statements you include in the PROCEDURE DIVISION of your application
program. They have the following basic format:
EXEC CICS command name and command options
END-EXEC
Page 156
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Compiler options:
When coding for CICS, certain compiler options are required while others are
recommended or ignored.
To prepare COBOL program to run under CICS one must use the CICS translator to
convert the CICS commands to COBOL statement and compile and link the program
to create the executable module.
When coding for CICS, the required compiler options are:
o RENT
o NODYNAM (if the program is translated by the CICS translator)
o LIB (if the program has a COPY or BASIS statement in it)
Coding restrictions:
Do not apply EXEC, CICS, or END-EXEC for variable names.
Do not implement the FILE-CONTROL entry in the ENVIRONMENT DIVISION, unless
the FILE-CONTROL entry is being used for a SORT statement.
Do not apply the FILE SECTION of the DATA DIVISION, unless the FILE SECTION is
being used for a SORT statement.
Do not implement parameters specified by user to the main program.
Page 157
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Page 158
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Overview:
A class defines a template for a series of similar objects.
The class can be used to define and create objects that are the same except for the
value of their data.
By defining classes and objects within classes the following takes place:
o Complex applications will be easier to develop.
o Programs will become more standardized.
o Reusable code stored in libraries will reduce duplication of effort, programming
and maintenance costs, and errors.
o Improve programmer productivity
o Objects can be acted on in any program by responding to the messages provided
by the user.
Page 159
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Example-1:
A Bank-Account may be defined as a class.
It may have checking-account and savings-account as subclasses, each of which
shares data attributes (e.g., account number and balance) and procedures (e.g.,
calculating interest) defined as part of Bank-Account.
Example-2:
A Method that can be applied to these classes includes deposit and withdrawal.
All objects within bank-account can share deposit and withdrawal services.
That means that the mechanisms used for withdrawing or depositing money will be the
same for all objects within the class.
Each object can have additional methods not inherited from the class but unique to
that object.
That is, process-check-fee can be a method applied to checking-account but not to
savings-account.
Example-3:
Data such as account-number can be shared by objects within the class as well.
This may be made available to users for processing but may also be protected so that
users can enter and retrieve them, but not be able to change them.
Page 160
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Although the term "polymorphism" itself may be new to you, it has relevance to the current COBOL
language.
The READ statement, for example is polymorphic in that it results in different actions depending on
whether we are reading from a sequential, indexed, or relative file.
The Interface that links the Method to the object may be different but the service provided will be
similar.
An INTERFACE is the entire set of messages to which an object can respond along with the
parameters required by each message.
The concept of DATA ABSTRACTION in OOP encourages programmers to think of data and
methods in abstract terms, as fixed objects;
Page 161
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Common objects--data and procedures--should be factored out and located in ancestor classes,
sometimes referred to as abstract classes.
ENCAPSULATION--the ability to hide internal details of data and procedures while providing a
public interface through a user-defined message
A COBOL example:
INVOKE ASAVINGSACCOUNT ‘Withdraw’ USING CUSTOMER-ACCT TRANS-AMT
RETURNING ACCOUNT
ASAVINGSACCOUNT may be an instance of some class object such as ACCOUNT.
‘Withdraw’ is a method.
USING indicate the parameters to pass to the object.
RETURNING indicate the parameters passed back to the user program.
Often you begin establishing a new instance of an object from a class of
objects.
MYSAVINGSACCOUNT may be an instance of ASAVINGSACCOUNT.
Defining an instance of an object is called INSTANTIATION.
This may be accomplished by code such as:
INVOKE ASAVINGSACCOUNT 'New' RETURNING MYSTAVINGSACCOUNT.
PERSISTENCE is the ability for changes to be retained after the program is terminated and when
the program executes it begins just as it ended.
Compiler options
Helps to control the compilation
Specify these options in:
o PARM field of the JCL
o CBL or PROCESS statement in program
Most of the options come in pairs like XREF/NOXREF
Some options have sub-parameters like LINECOUNT (44)
Watch out that there are default options when compiler is installed
Precedence of Compiler Options:
o Level 1: (Highest precedence) Installation defaults, fixed by your installation
o Level 2: Those on PROCESS (or CBL) stmt
Page 162
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Page 163
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
o When you specify the run-time option HEAP (BELOW), the DATA (24|31) compiler
option has no effect; the storage for all dynamic data areas is allocated from below
the 16-megabyte line. However, with HEAP (ANYWHERE) as the run-time option,
storage for dynamic data areas is allocated from below the line if you compiled the
program with the DATA (24) compiler option or from unrestricted storage if you
compiled with the DATA (31) compiler option.
o Specify the DATA (24) compiler option for programs running in 31-bit addressing
mode that is passing data parameters to programs in 24-bit addressing mode.
This ensures that the data will be addressable by the called program.- With
NORENT compiler option, DATA(31) has no effect
DECK / NODECK:
o Default is: NODECK
o Abbreviations are: D / NOD
o Use DECK to produce object code in the form of 80-column card images. If you
use the DECK option, be certain that SYSPUNCH is defined in your JCL for
compilation.
o SYSPUNCH ddname must for DECK opt
DYNAM / NODYNAM:
o Default is: NODYNAM
o Abbreviations are: DYN / NODYN
o Use DYNAM to cause separately compiled programs invoked through the CALL
literal statement to be loaded dynamically at run time. DYNAM causes dynamic
loads (for CALL) and deletes (for CANCEL) of separately compiled programs at
object time. Any CALL identifier statements that cannot be resolved in your
program are also handled as dynamic calls.
o DYNAM forced RESIDENT option
FLAG (x,y) / NOFLAG:
o Default is: FLAG (I)
o Abbreviations are: F / NOF
x: I, W, E, S, or U
y: I, W, E, S, or U
o Use FLAG (x) to produce diagnostic messages for errors of a severity level x or
above at the end of the source listing. Use FLAG (x, y) to produce diagnostic
messages for errors of severity level x or above at the end of the source listing,
with error messages of severity y and above to be embedded directly in the
source listing. The severity coded for y must not be lower than the severity coded
for x. To use FLAG (x, y), you must also specify the SOURCE compiler option.
o Error messages in the source listing are set off by embedding the statement
number in an arrow that points to the message code. The message code is then
followed by the message text
o Use NOFLAG to suppress error flagging. NOFLAG will not suppress error
messages for compiler options.
o Control listing of error messages
LIB / NOLIB:
o Default is: NOLIB
o Abbreviation is: None
Page 164
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Page 165
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Page 166
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
o Simplify the compiled code for both a PERFORM statement and a CALL
statement to a contained (nested) program. Where possible, the optimizer places
the statement inline, eliminating the need for linkage code.
o This optimization, known as procedure integration, is further discussed in
"PERFORM Procedure Integration" If procedure integration cannot be done, the
optimizer uses the simplest linkage possible (perhaps as few as two instructions)
to get to and from the called program.
o Eliminate duplicate computations (such as subscript computations and repeated
statements) that have no effect on the results of the program.
o Eliminate constant computations by performing them when the program is
compiled.
o Eliminate constant conditional expressions.
o Aggregate moves of contiguous items (such as those that often occur with the use
of MOVE CORRESPONDING) into a single move. Both the source and target
must be contiguous for the moves to be aggregated.
o Delete from the program, and identify with a warning message, code that can
never be performed (unreachable code elimination).
o The FULL suboption requests that the compilers discard any unreferenced data
items from the DATA DIVISION, and suppress generation of code to initialize
these data items to their VALUE clauses.
o For unit testing your programs, you might find it easier to debug code that has not
been optimized. But when the program is ready for final test, specify OPTIMIZE,
so that the tested code and the production code are identical. You might also
want to use the option during development, if a program is used frequently without
recompilation. However, the overhead for OPTIMIZE might outweigh its benefits if
you re-compile frequently, unless you are using the assembler language
expansion (LIST option) to fine tune your program.
o OPTIMIZE & TEST - mutually exclusive
OUTDD (ddname): To get run-time DISPLAY output on a data set other than
SYSOUT
QUOTE / APOST:
o Default is: QUOTE
o Abbreviations are: Q / APOST
o Use QUOTE if you want the figurative constant [ALL] QUOTE or [ALL] QUOTES
to represent one or more quotation mark (") characters.
o Use APOST if you want the figurative constant [ALL] QUOTE or [ALL] QUOTES to
represent one or more apostrophe (') characters.
o Note: Either quotes or apostrophes can be used as literal delimiters, regardless
of whether the APOST or QUOTE option is in effect. The delimiter character used
as the opening delimiter for a literal must be used as the closing delimiter for that
literal.
RENT / NORENT:
o Object code is to be re-entrant
o Have RESIDENT option for all programs in a unit unless the run-time option
MIXRES has been specified.
SOURCE / NOSOURCE:
o Default is: SOURCE
o Abbreviations are: S / NOS
o Use SOURCE to get a listing of your source program. This listing will include any
statements embedded by PROCESS or COPY statements.
Page 167
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
o SOURCE must be specified if you want embedded messages in the source listing.
o Use NOSOURCE to suppress the source code from the compiler output listing.
SPACE (1/2/3): To select single, double, or triple spacing in your source code listing.
TEST / NOTEST:
o Default is: NOTEST
o Use TEST to produce object code that enables Debug Tool to perform batch and
interactive debugging. The amount of debugging support available depends on
which TEST suboptions you use. The TEST option also allows you to request that
symbolic variable be included in the formatted dump produced by Language
Environment.
o Use NOTEST if you do not want to generate object code with debugging
information and do not want the formatted dump to include symbolic variables.
o TEST has two sub options; you can specify both, just one of the sub options, or
neither of the sub options:
o Hook: The hook-location sub option controls where compiled-in hooks will be
generated to provide information to the debugger.
o NONE: No hooks will be generated.
o BLOCK: Hooks will be generated at all program entry and exit points.
PATH: Hooks will be generated at all program entry and exit points and at all
path points. A path point is anywhere in a program where the logic flow is not
necessarily sequential or can change. Some examples of path points are IF-THEN-
ELSE constructs, PERFORM loops, ON SIZE ERROR phrases, and CALL
statements.
STMT: Hooks will be generated at every statement and label, as well as at all program
entry and exit point. In addition, if the DATEPROC option is in effect, hooks will be
generated at all date processing statements.
ALL: Hooks will be generated at all statements, all path points, and at all program
entry and exit points. In addition, if the DATEPROC option is in effect, hooks will be
generated at all date processing statements.
Symbol: The symbol-table sub option controls whether dictionary tables will be
generated.
o SYM: Dictionary and calculation tables will be generated.
o NOSYM: Dictionary and calculation tables will not be generated.
SSRANGE / NOSSRANGE:
o Default is: NOSSRANGE
o Abbreviations are: SSR / NOSSR
o Use SSRANGE to generate code that checks if subscripts (including ALL
subscripts) or indexes try to reference an area outside the region of the table.
Each subscript or index is not individually checked for validity; rather, the effective
address is checked to ensure that it does not cause a reference outside the region
of the table. Variable-length items will also be checked to ensure that the
reference is within their maximum defined length.
o Reference modification expressions will be checked to ensure that:
The reference modification starting position is greater than or equal to 1.
The reference modification starting position is not greater than the current
length of the subject data item.
The reference modification length value (if specified) is greater than or
equal to 1.
Page 168
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
The reference modification starting position and length value (if specified)
do not reference an area beyond the end of the subject data item.
Use it while testing
TRUNC (OPT or STD or BIN):
o Default is: TRUNC (STD)
o TRUNC (STD): Use TRUNC (STD) to control the way arithmetic fields are
truncated during MOVE and arithmetic operations. TRUNC (STD) applies only to
USAGE BINARY receiving fields in MOVE statements and arithmetic expressions.
When TRUNC (STD) is in effect, the final result of an arithmetic expression, or the
sending field in the MOVE statement, is truncated to the number of digits in the
PICTURE clause of the BINARY receiving field.
TRUNC (OPT): TRUNC (OPT) is a performance option. When TRUNC (OPT) is
specified, the compiler assumes that the data conforms to PICTURE and USAGE
specifications of the USAGE BINARY receiving fields in MOVE statements and
arithmetic expressions. The results are manipulated in the most optimal way, either
truncating to the number of digits in the PICTURE clause, or to the size of the binary
field in storage (halfword, fullword, or double word).
TRUNC (BIN): The TRUNC (BIN) option applies to all COBOL language that
processes USAGE BINARY data. When TRUNC (BIN) is in effect:
o BINARY receiving fields are truncated only at half word, fullword, or doubleword
boundaries.
o BINARY sending fields are handled as halfwords, fullwords, or doublewords when
the receiver is numeric; TRUNC (BIN) has no effect when the receiver is not
numeric.
o The full binary content of the field is significant.
o DISPLAY will convert the entire content of the binary field, with no truncation.
VBREF / NOVBREF:
o Default is: NOVBREF
o Use VBREF to get a cross-reference among all verb types used in the source
program and the line numbers in which they are used. VBREF also produces a
summary of how many times each verb was used in the program.
o Use NOVBREF for more efficient compilation.
WORD (xxxx) / NOWORD:
o Default is: NOWORD
o Abbreviations are: WD / NOWD
o xxxx: Are the ending characters of the name of the reserved word table
(IGYCxxxx) to be used in your compilation. IGYC are the first 4 standard
characters of the name, and xxxx can be 1 to 4 characters in length.
o Use WORD(xxxx) to specify that an alternate reserved word table is to be used
during compilation.
o Alternate reserved word tables provide changes to the IBM-supplied default
reserved word table.
XREF(FULL or SHORT) / NOXREF:
o Default is: NOXREF
o Abbreviations are: X / NOX
o You can choose XREF, XREF (FULL), or XREF (SHORT).
Page 169
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Page 170
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Summary
Overview of Programming for DB2 Environment:
The DB2 tables can be accessing from Cobol programs by using SQL statements
The pre-defined layouts of the DB2 tables may also be plugged into the Cobol code
DB2 Bind is process that builds "access paths" to DB2 tables.
A DBRM is a DB2 component created by the DB2 pre-compiler containing the SQL
source statements extracted from the application program. DBRMs are input to the
bind process.
A bind uses the Database Request Modules(s) (DBRM(s)) from the DB2 pre-compile
step as input and produces an application plan.
Page 171
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Page 172
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Appendix 1
Page 173
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Page 174
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Glossary
A
Abbreviated combined relation condition: The combined condition that results from the explicit
omission of a common subject or a common subject and common relational operator in a
consecutive sequence of relation conditions.
Access mode: The manner in which records are to be operated upon within a file.
Actual decimal point: The physical representation, using the decimal point characters period (.)
or comma (,), of the decimal point position in a data item.
Alternate record key: A key, other than the prime record key, whose contents identify a record
within an indexed file.
Arithmetic operation: The process caused by the execution of an arithmetic statement, or the
evaluation of an arithmetic expression, that results in a mathematically correct solution to the
arguments presented.
Page 175
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Arithmetic operator: A single character, or a fixed two-character combination that belongs to the
following set:
Character Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
** Exponentiation
Array: In Language Environment, an aggregate consisting of data objects, each of which may be
uniquely referenced by subscripting. Roughly analogous to a COBOL table.
Ascending key: A key upon the values of which data is ordered, starting with the lowest value of
the key up to the highest value of the key, in accordance with the rules for comparing data items.
ASCII: American National Standard Code for Information Interchange. The standard code, using a
coded character set consisting of 7-bit coded characters (8 bits including parity check), used for
information interchange between data processing systems, data communication systems, and
associated equipment. The ASCII set consists of control characters and graphic characters.
Assignment-name: A name that identifies the organization of a COBOL file and the name by
which it is known to the system.
Assumed decimal point: A decimal point position that does not involve the existence of an actual
character in a data item. The assumed decimal point has logical meaning with no physical
representation.
B
Big-endian: Default format used by the mainframe and the AIX workstation to store binary data. In
this format, the least significant digit is on the highest address. Compare with "little-endian."
Binary item: A numeric data item represented in binary notation (on the base 2 numbering
system). Binary items have a decimal equivalent consisting of the decimal digits 0 through 9, plus
an operational sign. The leftmost bit of the item is the operational sign.
Page 176
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Binary search: A dichotomizing search in which, at each step of the search, the set of data
elements is divided by two; some appropriate action is taken in the case of an odd number.
Block: A physical unit of data that is normally composed of one or more logical records. For mass
storage files, a block may contain a portion of a logical record. The size of a block has no direct
relationship to the size of the file within which the block is contained or to the size of the logical
record(s) that are either contained within the block or that overlap the block. The term is
synonymous with physical record.
Btrieve: A key-indexed record management system that allows applications to manage records by
key value, sequential access method, or random access method. IBM COBOL supports COBOL
sequential and indexed file I-O language through Btrieve.
Byte: A string consisting of a certain number of bits, usually eight, treated as a unit, and
representing a character.
C
Callable services: In Language Environment, a set of services that can be invoked by a COBOL
program using the conventional Language Environment-defined call interface, and usable by all
programs sharing the Language Environment conventions.
Case structure: A program processing logic in which a series of conditions is tested in order to
make a choice between a numbers of resulting actions.
Cataloged procedure: A set of job control statements placed in a partitioned data set called the
procedure library (SYS1.PROCLIB). You can use cataloged procedures to save time and reduce
errors coding JCL.
Century window: A century window is a 100-year interval within which any 2-digit year is unique.
There are several types of century window available to COBOL programmers:
For windowed date fields, the YEARWINDOW compiler option
For windowing intrinsic functions DATE-TO-YYYYMMDD, DAY-TO-YYYYDDD, and YEAR-TO-
YYYY, it is specified by argument-2
For Language Environment date and time callable services, it is specified in CEESCEN
Page 177
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Character position: The amount of physical storage required to store a single standard data
format character described as USAGE IS DISPLAY.
Character set: All the valid characters for a programming language or a computer system.
Checkpoint: A point at which information about the status of a job and the system can be
recorded so that the job step can be later restarted.
Class: The entity that defines common behavior and implementation for zero, one, or more
objects. The objects that share the same implementation are considered to be objects of the same
class.
Class condition: The proposition, for which a truth value can be determined, that the content of
an item is wholly alphabetic, is wholly numeric, or consists exclusively of those characters listed in
the definition of a class-name.
CMS (Conversational Monitor System): A virtual machine operating system that provides
general interactive, time-sharing, problem solving, and program development capabilities, and that
operates only under the control of the VM/SP control program.
COBOL character set: The complete COBOL character set consists of the characters listed
below:
Character Meaning
0,1...,9 digit
A,B,...,Z uppercase letter
a,b,...,z lowercase letter
º space
+ plus sign
Page 178
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Code page: An assignment of graphic characters and control function meanings to all code points;
for example, assignment of characters and meanings to 256 code points for 8-bit code,
assignment of characters and meanings to 128 code points for 7-bit code.
Collating sequence: The sequence in which the characters that are acceptable to a computer are
ordered for purposes of sorting, merging, comparing, and for processing indexed files sequentially.
Column: A character position within a print line. The columns are numbered from 1, by 1, starting
at the leftmost character position of the print line and extending to the rightmost position of the
print line.
Combined condition: A condition that is the result of connecting two or more conditions with the
AND or the OR logical operator.
Comment line: A source program line represented by an asterisk (*) in the indicator area of the
line and any characters from the computer's character set in area A and area B of that line. The
comment line serves only for documentation in a program. A special form of comment line
represented by a slant (/) in the indicator area of the line and any characters from the computer's
character set in area A and area B of that line causes page ejection prior to printing the comment.
Common program: A program which, despite being directly contained within another program,
may be called from any program directly or indirectly contained in that other program.
Compatible date field: The meaning of the term "compatible," when applied to date fields,
depends on the COBOL division in which the usage occurs.
Page 179
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Compile: (1) To translate a program expressed in a high-level language into a program expressed
in an intermediate language, assembly language, or a computer language. (2) To prepare a
machine language program from a computer program written in another programming language by
making use of the overall logic structure of the program, or generating more than one computer
instruction for each symbolic statement, or both, as well as performing the function of an
assembler.
Compile time: The time at which a COBOL source program is translated, by a COBOL compiler,
to a COBOL object program.
Compiler: A program that translates a program written in a higher level language into a machine
language object program.
Compiler directing statement: A statement that specifies actions to be taken by the compiler
during processing of a COBOL source program. Compiler directives are contained in the COBOL
source program. Thus, you can specify different sub-options of the directive within the source
program by using multiple compiler directive statements in the program.
Complex condition: A condition in which one or more logical operators act upon one or more
conditions. (See also "negated simple condition," "combined condition," and "negated combined
condition.")
Computer-name: A system-name that identifies the computer upon which the program is to be
compiled or run.
Condition: An exception that has been enabled, or recognized, by Language Environment and
thus is eligible to activate user and language condition handlers. Any alteration to the normal
programmed flow of an application. Conditions can be detected by the hardware/operating system
and results in an interrupt. They can also be detected by language-specific generated code or
language library code.
Condition: A status of a program at run time for which a truth value can be determined. Where the
term 'condition' (condition-1, condition-2,...) appears in these language specifications in or in
reference to 'condition' (condition-1, condition-2,...) of a general format, it is a conditional
expression consisting of either a simple condition optionally parenthesized, or a combined
condition consisting of the syntactically correct combination of simple conditions, logical operators,
and parentheses, for which a truth value can be determined.
Conditional phrase: A conditional phrase specifies the action to be taken upon determination of
the truth value of a condition resulting from the execution of a conditional statement.
Page 180
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Conditional variable: A data item one or more values of which has a condition-name assigned to
it.
Condition-name: A user-defined word that assigns a name to a subset of values that a conditional
variable may assume; or a user-defined word assigned to a status of an implementor defined
switch or device. When 'condition-name' is used in the general formats, it represents a unique data
item reference consisting of a syntactically correct combination of a 'condition-name', together with
qualifiers and subscripts, as required for uniqueness of reference.
Condition-name condition: The proposition, for which a truth value can be determined, that the
value of a conditional variable is a member of the set of values attributed to a condition-name
associated with the conditional variable.
Contiguous items: Items that are described by consecutive entries in the Data Division, and that
bear a definite hierarchic relationship to each other.
Copybook: A file or library member containing a sequence of code that is included in the source
program at compile time using the COPY statement. The file can be created by the user, supplied
by COBOL, or supplied by another product.
CORBA: The Common Object Request Broker Architecture established by the Object
Management Group. IBM's Interface Definition Language used to describe the interface for SOM
classes is fully compliant with CORBA standards.
Counter: A data item used for storing numbers or number representations in a manner that
permits these numbers to be increased or decreased by the value of another number, or to be
changed or reset to zero or to an arbitrary positive or negative value.
cross-reference listing. The portion of the compiler listing that contains information on where files,
fields, and indicators are defined, referenced, and modified in a program.
Currency sign value: A character-string that identifies the monetary units stored in a numeric-
edited item. Typical examples are '$', 'USD', and 'EUR'. A currency sign value can be defined by
either the CURRENCY compiler option or the CURRENCY SIGN clause in the SPECIAL-NAMES
paragraph of the Environment Division. If the CURRENCY SIGN clause is not specified and the
NOCURRENCY compiler option is in effect, the dollar sign ($) is used as the default currency sign
value. See also "currency symbol."
Page 181
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Currency symbol: A character used in a PICTURE clause to indicate the position of a currency
sign value in a numeric-edited item. A currency symbol can be defined by either the CURRENCY
compiler option or by the CURRENCY SIGN clause in the SPECIAL-NAMES paragraph of the
Environment Division. If the CURRENCY SIGN clause is not specified and the NOCURRENCY
compiler option is in effect, the dollar sign ($) is used as the default currency sign value and
currency symbol. Multiple currency symbols and currency sign values can be defined. See also
"currency sign value."
Current record: In file processing, the record that is available in the record area associated with a
file.
Current volume pointer: A conceptual entity that points to the current volume of a sequential file.
D
Data clause: A clause, appearing in a data description entry in the DATA DIVISION of a COBOL
program that provides information describing a particular attribute of a data item.
Data description entry: An entry in the DATA DIVISION of a COBOL program that is composed
of a level-number followed by a data-name, if required, and then followed by a set of data clauses,
as required.
DATA DIVISION: One of the four main components of a COBOL program, class definition, or
method definition. The DATA DIVISION describes the data to be processed by the object program,
class, or method: files to be used and the records contained within them; internal working-storage
records that will be needed; data to be made available in more than one program in the COBOL
run unit. (Note, the Class DATA DIVISION contains only the WORKING-STORAGE SECTION.)
Data item: A unit of data (excluding literals) defined by a COBOL program or by the rules for
function evaluation.
Data-name: A user-defined word that names a data item described in a data description entry.
When used in the general formats, 'data-name' represents a word that must not be reference-
modified, subscripted or qualified unless specifically permitted by the rules for the format.
Debugging line: A debugging line is any line with a 'D' in the indicator area of the line.
Declaratives: A set of one or more special purpose sections, written at the beginning of the
Procedure Division, the first of which is preceded by the key word DECLARATIVES and the last of
which is followed by the key words END DECLARATIVES. A declarative is composed of a section
header, followed by a USE compiler directing sentence, and followed by a set of zero, one, or
more associated paragraphs.
Page 182
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
De-edit: The logical removal of all editing characters from a numeric edited data item in order to
determine that item's unedited numeric value.
Delimited scope statement: Any statement that includes its explicit scope terminator.
Delimiter: A character or a sequence of contiguous characters that identify the end of a string of
characters and separate that string of characters from the following string of characters. A delimiter
is not part of the string of characters that it delimits.
Descending key: A key upon the values of which data is ordered starting with the highest value of
key down to the lowest value of key, in accordance with the rules for comparing data items.
Digit: Any of the numerals from 0 through 9. In COBOL, the term is not used in reference to any
other symbol.
Digit position: The amount of physical storage required to store a single digit. This amount may
vary depending on the usage specified in the data description entry that defines the data item.
Direct access: The facility to obtain data from storage devices or to enter data into a storage
device in such a way that the process depends only on the location of that data and not on a
reference to data previously accessed.
Division: A collection of zero, one or more sections or paragraphs, called the division body that
are formed and combined in accordance with a specific set of rules. Each division consists of the
division header and the related division body. There are four (4) divisions in a COBOL program:
Identification, Environment, Data, and Procedure.
Division header: A combination of words followed by a separator period that indicates the
beginning of a division. The division headers are:
IDENTIFICATION DIVISION.
ENVIRONMENT DIVISION.
DATA DIVISION.
PROCEDURE DIVISION.
Do-until: In structured programming, a do-until loop will be executed at least once, and until a
given condition is true. In COBOL, a TEST AFTER phrase used with the PERFORM statement
functions in the same way.
Do-while: In structured programming, a do-while loop will be executed if, and while, a given
condition is true. In COBOL, a TEST BEFORE phrase used with the PERFORM statement
functions in the same way.
Page 183
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Double-Byte Character Set (DBCS): A set of characters in which each character is represented
by two bytes. Languages such as Japanese, Chinese, and Korean, which contain more symbols
than can be represented by 256 code points, require Double-Byte Character Sets. Because each
character requires two bytes, entering, displaying, and printing DBCS characters requires
hardware and supporting software that are DBCS-capable.
Dynamic access: An access mode in which specific logical records can be obtained from or
placed into a mass storage file in a nonsequential manner and obtained from a file in a sequential
manner during the scope of the same OPEN statement.
Dynamic link library: A file containing executable code and data bound to a program at load time
or run time, rather than during linking. The code and data in a dynamic link library can be shared
by several applications simultaneously.
Dynamic Storage Area (DSA): Dynamically acquired storage composed of a register save area
and an area available for dynamic storage allocation (such as program variables). DSAs are
generally allocated within STACK segments managed by Language Environment.
E
EBCDIC (Extended Binary-Coded Decimal Interchange Code): A coded character set
consisting of 8-bit coded characters.
EBCDIC character: Any one of the symbols included in the 8-bit EBCDIC (Extended Binary-
Coded-Decimal Interchange Code) set.
Edited data item: A data item that has been modified by suppressing zeroes and/or inserting
editing characters.
Element (text element): One logical unit of a string of text, such as the description of a single data
item or verb, preceded by a unique code identifying the element type.
Elementary item: A data item that is described as not being further logically subdivided.
Enclave: When running under the Language Environment product, an enclave is analogous to a
run unit. An enclave can create other enclaves on OS/390 and CMS by a LINK, on CMS by
CMSCALL, and the use of the system () function of C.
End class header: A combination of words, followed by a separator period, that indicates the end
of a COBOL class definition. The end class header is:
END CLASS class-name.
End method header: A combination of words, followed by a separator period that indicates the
end of a COBOL method definition. The end method header is:
END METHOD method-name.
End of Procedure Division: The physical position of a COBOL source program after which no
further procedures appear.
Page 184
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
End program header: A combination of words, followed by a separator period that indicates the
end of a COBOL source program. The end program header is:
END PROGRAM program-name.
Entry: Any descriptive set of consecutive clauses terminated by a separator period and written in
the IDENTIFICATION DIVISION, ENVIRONMENT DIVISION, or DATA DIVISION of a COBOL
program.
ENVIRONMENT DIVISION: One of the four main component parts of a COBOL program, class
definition, or method definition. The ENVIRONMENT DIVISION describes the computers upon
which the source program is compiled and those on which the object program is executed, and
provides a linkage between the logical concept of files and their records, and the physical aspects
of the devices on which files are stored.
Environment-name: A name, specified by IBM, that identifies system logical units, printer and
card punch control characters, report codes, and/or program switches. When an environment-
name is associated with a mnemonic-name in the ENVIRONMENT DIVISION, the mnemonic-
name may then be substituted in any format in which such substitution is valid.
Environment variable: Any of a number of variables that describe the way an operating system is
going to run and the devices it is going to recognize.
Expanded date field: A date field containing an expanded (4-digit) year. See also "date field" and
"expanded year."
Expanded year: Four digits representing a year, including the century (for example, 1998).
Appears in expanded date fields. Compare with "windowed year."
Explicit scope terminator: A reserved word that terminates the scope of a particular Procedure
Division statement.
Exponent: A number, indicating the power to which another number (the base) is to be raised.
Positive exponents denote multiplication, negative exponents denote division, and fractional
exponents denote a root of a quantity. In COBOL, an exponential expression is indicated with the
symbol '**' followed by the exponent.
Extend mode: The state of a file after execution of an OPEN statement, with the EXTEND phrase
specified for that file, and before the execution of a CLOSE statement, without the REEL or UNIT
phrase for that file.
Page 185
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Extensions: Certain COBOL syntax and semantics supported by IBM compilers in addition to
those described in ANSI Standard.
External data: The data described in a program as external data items and external file
connectors.
External data item: A data item which is described as part of an external record in one or more
programs of a run unit and which itself may be referenced from any program in which it is
described.
External data record: A logical record which is described in one or more programs of a run unit
and whose constituent data items may be referenced from any program in which they are
described.
External decimal item: A format for representing numbers in which the digit is contained in bits 4
through 7 and the sign is contained in bits 0 through 3 of the rightmost byte. Bits 0 through 3 of all
other bytes contain 1's (hex F). For example, the decimal value of +123 is represented as 1111
0001 1111 0010 1111 0011. (Also known as "zoned decimal item.")
External file connector: A file connector which is accessible to one or more object programs in
the run unit.
External floating-point item: A format for representing numbers in which a real number is
represented by a pair of distinct numerals. In a floating-point representation, the real number is the
product of the fixed-point part (the first numeral), and a value obtained by raising the implicit
floating-point base to a power denoted by the exponent (the second numeral).
For example, a floating-point representation of the number 0.0001234 is: 0.1234 -3, where 0.1234
is the mantissa and -3 is the exponent.
External switch: A hardware or software device defined and named by the implementor, which is
used to indicate that one of two alternate states exists.
F
Figurative constant: A compiler-generated value referenced through the use of certain reserved
words.
File attribute conflict condition: An unsuccessful attempt has been made to execute an input-
output operation on a file and the file attributes, as specified for that file in the program, do not
match the fixed attributes for that file.
File clause: A clause that appears as part of any of the following DATA DIVISION entries: file
description entry (FD entry) and sort-merge file description entry (SD entry).
Page 186
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
File connector: A storage area which contains information about a file and is used as the linkage
between a file-name and a physical file and between a file-name and its associated record area.
File-Control: The name of an ENVIRONMENT DIVISION paragraph in which the data files for a
given source program are declared.
File control entry: A SELECT clause and all its subordinate clauses which declare the relevant
physical attributes of a file.
File description entry: An entry in the File Section of the DATA DIVISION that is composed of the
level indicator FD, followed by a file-name, and then followed by a set of file clauses as required.
File-name: A user-defined word that names a file connector described in a file description entry or
a sort-merge file description entry within the File Section of the DATA DIVISION.
File organization: The permanent logical file structure established at the time that a file is created.
File position indicator: A conceptual entity that contains the value of the current key within the
key of reference for an indexed file, or the record number of the current record for a sequential file,
or the relative record number of the current record for a relative file, or indicates that no next
logical record exists, or that an optional input file is not present, or that the at end condition already
exists, or that no valid next record has been established.
File Section: The section of the DATA DIVISION that contains file description entries and sort-
merge file description entries together with their associated record descriptions.
File system: The collection of files and file management structures on a physical or logical mass
storage device, such as a diskette or minidisk.
Fixed file attributes: Information about a file which is established when a file is created and
cannot subsequently be changed during the existence of the file. These attributes include the
organization of the file (sequential, relative, or indexed), the prime record key, the alternate record
keys, the code set, the minimum and maximum record size, the record type (fixed or variable), the
collating sequence of the keys for indexed files, the blocking factor, the padding character, and the
record delimiter.
Fixed length record: A record associated with a file whose file description or sort-merge
description entry requires that all records contain the same number of character positions.
Fixed-point number: A numeric data item defined with a PICTURE clause that specifies the
location of an optional sign, the number of digits it contains, and the location of an optional decimal
point. The format may be either binary, packed decimal, or external decimal.
Floating-point number: A numeric data item containing a fraction and an exponent. Its value is
obtained by multiplying the fraction by the base of the numeric data item raised to the power
specified by the exponent.
Page 187
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Function: A temporary data item whose value is determined at the time the function is referenced
during the execution of a statement.
Function-name: A word that names the mechanism whose invocation, along with required
arguments, determines the value of a function.
G
Global name: A name which is declared in only one program but which may be referenced from
that program and from any program contained within that program. Condition-names, data-names,
file-names, record-names, report-names, and some special registers may be global names.
H
Header label: (1) A file label or data set label that precedes the data records on a unit of recording
media. (2) Synonym for beginning-of-file label.
I
IBM COBOL extension: Certain COBOL syntax and semantics supported by IBM compilers in
addition to those described in ANSI Standard.
IDENTIFICATION DIVISION: One of the four main component parts of a COBOL program, class
definition, or method definition. The IDENTIFICATION DIVISION identifies the program name,
class name, or method name. The IDENTIFICATION DIVISION may include the following
documentation: author name, installation, or date.
IGZCBSN: The COBOL/370 Release 1 bootstrap routine. It must be link-edited with any module
that contains a COBOL/370 Release 1 program.
IGZCBSO: The COBOL for MVS & VM Release 2 and IBM COBOL for OS/390 & VM bootstrap
routine. It must be link-edited with any module that contains a COBOL for MVS & VM Release 2 or
IBM COBOL for OS/390 & VM program.
Page 188
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Imperative statement: A statement that either begins with an imperative verb and specifies an
unconditional action to be taken or is a conditional statement that is delimited by its explicit scope
terminator (delimited scope statement). An imperative statement may consist of a sequence of
imperative statements.
Implicit scope terminator: A separator period which terminates the scope of any preceding
unterminated statement or a phrase of a statement which by its occurrence indicates the end of
the scope of any statement contained within the preceding phrase.
Index: A computer storage area or register, the content of which represents the identification of a
particular element in a table.
Index data item: A data item in which the values associated with an index-name can be stored in
a form specified by the implementer.
Indexed organization: The permanent logical file structure in which each record is identified by
the value of one or more keys within that record.
Index-name: A user-defined word that names an index associated with a specific table.
Inheritance (for classes): A mechanism for using the implementation of one or more classes as
the basis for another class. A sub-class inherits from one or more super-classes. By definition the
inheriting class conforms to the inherited classes.
Initial program: A program that is placed into an initial state every time the program is called in a
run unit.
Initial state: The state of a program when it is first called in a run unit.
Inline: In a program, instructions that are executed sequentially, without branching to routines,
subroutines, or other programs.
Input mode: The state of a file after execution of an OPEN statement, with the INPUT phrase
specified, for that file and before the execution of a CLOSE statement, without the REEL or UNIT
phrase for that file.
Page 189
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
INPUT-OUTPUT SECTION: The section of the ENVIRONMENT DIVISION that names the files
and the external media required by an object program or method and that provides information
required for transmission and handling of data during execution of the object program or method
definition.
Input procedure: A set of statements, to which control is given during the execution of a SORT
statement, for the purpose of controlling the release of specified records to be sorted.
Instance data: Data defining the state of an object. The instance data introduced by a class is
defined in the WORKING-STORAGE SECTION of the DATA DIVISION of the class definition. The
state of an object also includes the state of the instance variables introduced by base classes that
are inherited by the current class. A separate copy of the instance data is created for each object
instance.
Integer: (1) A numeric literal that does not include any digit positions to the right of the decimal
point. (2) A numeric data item defined in the DATA DIVISION that does not include any digit
positions to the right of the decimal point. (3) A numeric function whose definition provides that all
digits to the right of the decimal point are zero in the returned value for any possible evaluation of
the function.
Integer function: A function whose category is numeric and whose definition does not include any
digit positions to the right of the decimal point.
Interface: The information that a client must know to use a class--the names of its attributes and
the signatures of its methods. With direct-to-SOM compilers such as COBOL, the interface to a
class may be defined by native language syntax for class definitions. Classes implemented in
other languages might have their interfaces defined directly in SOM Interface Definition Language
(IDL). The COBOL compiler has a compiler option, IDLGEN, to automatically generate IDL for a
COBOL class.
Interface Definition Language (IDL): The formal language (independent of any programming
language) by which the interface for a class of objects is defined in a IDL file, which the SOM
compiler then interprets to create an implementation template file and binding files. SOM's
Interface Definition Language is fully compliant with standards established by the Object
Management Group's Common Object Request Broker Architecture (CORBA).
Page 190
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Internal data: The data described in a program excluding all external data items and external file
connectors. Items described in the LINKAGE SECTION of a program are treated as internal data.
Internal data item: A data item which is described in one program in a run unit. An internal data
item may have a global name.
Internal decimal item: A format in which each byte in a field except the rightmost byte represents
two numeric digits. The rightmost byte contains one digit and the sign. For example, the decimal
value +123 is represented as 0001 0010 0011 1111. (Also known as packed decimal.)
Internal file connector: A file connector which is accessible to only one object program in the run
unit.
Intra-record data structure: The entire collection of groups and elementary data items from a
logical record which is defined by a contiguous subset of the data description entries which
describe that record. These data description entries include all entries whose level-number is
greater than the level-number of the first data description entry describing the intra-record data
structure.
Intrinsic function: A pre-defined function, such as a commonly used arithmetic function, called by
a built-in function reference.
Invalid key condition: A condition, at object time, caused when a specific value of the key
associated with an indexed or relative file is determined to be invalid.
I-O-Mode: The state of a file after execution of an OPEN statement, with the I-O phrase specified,
for that file and before the execution of a CLOSE statement without the REEL or UNIT phase for
that file.
I-O status: A conceptual entity which contains the two-character value indicating the resulting
status of an input-output operation. This value is made available to the program through the use of
the FILE STATUS clause in the file control entry for the file.
ISPF. Interactive System Productivity Facility: An IBM software product that provides a menu-
driven interface to the TSO or VM user. Includes library utilities, a powerful editor, and dialog
management.
Iteration structure: A program processing logic in which a series of statements is repeated while
a condition is true or until a condition is true.
Page 191
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
K
K: When referring to storage capacity, two to the tenth power; 1024 in decimal notation.
Key: A data item that identifies the location of a record or a set of data items which serve to
identify the ordering of data.
Key of reference: The key, either prime or alternate, currently being used to access records within
an indexed file.
Key word: A reserved word or function-name whose presence is required when the format in
which the word appears is used in a source program.
L
Language-name: A system-name that specifies a particular programming language.
Last-used state: A program is in last-used state if its internal values remain the same as when the
program was exited (are not reset to their initial values).
Level indicator: Two alphabetic characters that identify a specific type of file or a position in a
hierarchy. The level indicators in the DATA DIVISION are: CD, FD, and SD.
Level-number: A user-defined word, expressed as a two digit number, which indicates the
hierarchical position of a data item or the special properties of a data description entry. Level-
numbers in the range from 1 through 49 indicate the position of a data item in the hierarchical
structure of a logical record. Level-numbers in the range 1 through 9 may be written either as a
single digit or as a zero followed by a significant digit. Level-numbers 66, 77 and 88 identify special
properties of a data description entry.
Library-name: A user-defined word that names a COBOL library that is to be used by the compiler
for a given source program compilation.
Library text: A sequence of text words, comment lines, the separator space, or the separator
pseudo-text delimiter in a COBOL library.
LINAGE-COUNTER: A special register whose value points to the current position within the page
body.
Page 192
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
LINKAGE SECTION: The section in the DATA DIVISION of the called program that describes
data items available from the calling program. These data items may be referred to by both the
calling and called program.
Literal: A character string whose value is specified either by the ordered set of characters
comprising the string, or by the use of a figurative constant.
Local: A set of attributes for a program execution environment indicating culturally sensitive
considerations, such as: character code page, collating sequence, date/time format, monetary
value representation, numeric value representation, or language.
LOCAL-STORAGE SECTION: The section of the DATA DIVISION that defines storage that is
allocated and freed on a per-invocation basis, depending on the value assigned in their VALUE
clauses.
Logical operator: One of the reserved words AND, OR, or NOT. In the formation of a condition,
either AND, or OR, or both can be used as logical connectives. NOT can be used for logical
negation.
Logical record: The most inclusive data item. The level-number for a record is 01. A record may
be either an elementary item or a group of items. The term is synonymous with record.
Main program: In a hierarchy of programs and subroutines, the first program to receive control
when the programs are run.
Mass storage: A storage medium in which data may be organized and maintained in both a
sequential and non-sequential manner.
Mass storage device: A device having a large storage capacity; for example, magnetic disk,
magnetic drums.
Mass storage file: A collection of records that is assigned to a mass storage medium.
Merge file: A collection of records to be merged by a MERGE statement. The merge file is
created and can be used only by the merge function.
Metaclass: A SOM class whose instances are SOM class-objects. The methods defined in
metaclasses are executed without requiring any object instances of the class to exist, and are
frequently used to create instances of the class.
Page 193
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Method: Procedural code that defines one of the operations supported by an object, and that is
executed by an INVOKE statement on that object.
Multitasking: Mode of operation that provides for the concurrent, or interleaved, execution of two
or more tasks. When running under the Language Environment product, multitasking is
synonymous with multithreading.
N
Name: A word composed of not more than 30 characters that defines a COBOL operand.
Native character set: The implementor-defined character set associated with the computer
specified in the OBJECT-COMPUTER paragraph.
Native collating sequence: The implementor-defined collating sequence associated with the
computer specified in the OBJECT-COMPUTER paragraph.
Negated simple condition: The 'NOT' logical operator immediately followed by a simple
condition.
Next executable sentence: The next sentence to which control will be transferred after execution
of the current statement is complete.
Next executable statement: The next statement to which control will be transferred after
execution of the current statement is complete.
Next record: The record that logically follows the current record of a file.
Page 194
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Non-numeric item: A data item whose description permits its content to be composed of any
combination of characters taken from the computer's character set. Certain categories of non-
numeric items may be formed from more restricted character sets.
Non-numeric literal: A literal bounded by quotation marks. The string of characters may include
any character in the computer's character set.
Null: Figurative constant used to assign the value of an invalid address to pointer data items.
NULLS can be used wherever NULL can be used.
Numeric-edited item: A numeric item that is in such a form that it may be used in printed output. It
may consist of external decimal digits from 0 through 9, the decimal point, commas, the dollar sign,
editing sign control symbols, plus other editing symbols.
Numeric function: A function whose class and category are numeric but which for some possible
evaluation does not satisfy the requirements of integer functions.
Numeric item: A data item whose description restricts its content to a value represented by
characters chosen from the digits from '0' through '9'; if signed, the item may also contain a '+', '-',
or other representation of an operational sign.
Numeric literal: A literal composed of one or more numeric characters that may contain either a
decimal point, or an algebraic sign, or both. The decimal point must not be the rightmost character.
The algebraic sign, if present, must be the leftmost character.
O
Object: An entity that has state (its data values) and operations (its methods). An object is a way
to encapsulate state and behavior.
Object code: Output from a compiler or assembler that is itself executable machine code or is
suitable for processing to produce executable machine code.
Object deck: A portion of an object program suitable as input to a linkage editor. Synonymous
with object module and text deck.
Page 195
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Object of entry: A set of operands and reserved words, within a DATA DIVISION entry of a
COBOL program that immediately follows the subject of the entry.
Object program: A set or group of executable machine language instructions and other material
designed to interact with data to provide problem solutions. In this context, an object program is
generally the machine language result of the operation of a COBOL compiler on a source program.
Where there is no danger of ambiguity, the word 'program' alone may be used in place of the
phrase 'object program.'
Object time: The time at which an object program is executed. The term is synonymous with
execution time.
Obsolete element: A COBOL language element in Standard COBOL that is to be deleted from
the next revision of Standard COBOL.
ODBC: Open Database Connectivity that provides you access to data from a variety of databases
and file systems.
Open mode: The state of a file after execution of an OPEN statement for that file and before the
execution of a CLOSE statement without the REEL or UNIT phrase for that file. The particular
open mode is specified in the OPEN statement as either INPUT, OUTPUT, I-O or EXTEND.
Operand: Whereas the general definition of operand is "that component which is operated upon,"
for the purpose of this document, any lowercase word (or words) that appears in a statement or
entry format may be considered to be an operand and, as such, is an implied reference to the data
indicated by the operand.
Operational sign: An algebraic sign, associated with a numeric data item or a numeric literal, to
indicate whether its value is positive or negative.
Optional file: A file which is declared as being not necessarily present each time the object
program is executed. The object program causes an interrogation for the presence or absence of
the file.
Optional word: A reserved word that is included in a specific format only to improve the
readability of the language and whose presence is optional to the user when the format in which
the word appears is used in a source program.
OS/2 (Operating System/2*): A multi-tasking operating system for the IBM Personal Computer
family that allows you to run both DOS mode and OS/2 mode programs.
Output file: A file that is opened in either the OUTPUT mode or EXTEND mode.
Output mode: The state of a file after execution of an OPEN statement, with the OUTPUT or
EXTEND phrase specified, for that file and before the execution of a CLOSE statement without the
REEL or UNIT phrase for that file.
Page 196
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Output procedure: A set of statements to which control is given during execution of a SORT
statement after the sort function is completed, or during execution of a MERGE statement after the
merge function reaches a point at which it can select the next record in merged order when
requested.
Overflow condition: A condition that occurs when a portion of the result of an operation exceeds
the capacity of the intended unit of storage.
P
Packed decimal item: See "internal decimal item."
Padding character: An alphanumeric character used to fill the unused character positions in a
physical record.
Page: A vertical division of output data representing a physical separation of such data, the
separation being based on internal logical requirements and/or external characteristics of the
output medium.
Page body: That part of the logical page in which lines can be written and/or spaced.
Paragraph header: A reserved word, followed by the separator period that indicates the beginning
of a paragraph in the IDENTIFICATION and ENVIRONMENT DIVISIONs.
Paragraph-name: A user-defined word that identifies and begins a paragraph in the Procedure
Division.
Parameter: Parameters are used to pass data values between calling and called programs.
Password: A unique string of characters that a program, computer operator, or user must supply
to meet security requirements before gaining access to data.
Phrase: A phrase is an ordered set of one or more consecutive COBOL character-strings that
form a portion of a COBOL procedural statement or of a COBOL clause.
Pointer data item: A data item in which address values can be stored. Data items are explicitly
defined as pointers with the USAGE IS POINTER clause. ADDRESS OF special registers are
implicitly defined as pointer data items. Pointer data items can be compared for equality or moved
to other pointer data items.
Portability: The ability to transfer an application program from one application platform to another
with relatively few changes to the source program.
Page 197
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Preloaded: In COBOL this refers to COBOL programs that remain resident in storage under IMS
instead of being loaded each time they are called.
Prime record key: A key whose contents uniquely identify a record within an indexed file.
Priority-number: A user-defined word which classifies sections in the Procedure Division for
purposes of segmentation. Segment-numbers may contain only the characters '0','1', ... , '9'. A
segment-number may be expressed either as a one- or two-digit number.
Procedure branching statement: A statement that causes the explicit transfer of control to a
statement other than the next executable statement in the sequence in which the statements are
written in the source program. The procedure branching statements are: ALTER, CALL, EXIT,
EXIT PROGRAM, GO TO, MERGE, (with the OUTPUT PROCEDURE phrase), PERFORM and
SORT (with the INPUT PROCEDURE or OUTPUT PROCEDURE phrase).
Procedure Division: One of the four main component parts of a COBOL program, class definition,
or method definition. The Procedure Division contains instructions for solving a problem. The
Program and Method Procedure Divisions may contain imperative statements, conditional
statements, and compiler directing statements, paragraphs, procedures, and sections. The Class
Procedure Division contains only method definitions.
Procedure integration: One of the functions of the COBOL optimizer is to simplify calls to
performed procedures or contained programs. PERFORM procedure integration is the process
whereby a PERFORM statement is replaced by its performed procedures. Contained program
procedure integration is the process where a CALL to a contained program is replaced by the
program code.
Procedure-pointer data item: A data item in which a pointer to an entry point can be stored. A
data item defined with the USAGE IS PROCEDURE-POINTER clause contains the address of a
procedure entry point.
Program-name: In the IDENTIFICATION DIVISION and the end program header, a user-defined
word that identifies a COBOL source program.
Pseudo-text: A sequence of text words, comment lines, or the separator space in a source
program or COBOL library bounded by, but not including, pseudo-text delimiters.
Pseudo-text delimiter: Two contiguous equal sign characters (==) used to delimit pseudo-text.
Page 198
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Q
QSAM (Queued Sequential Access Method): An extended version of the basic sequential
access method (BSAM). When this method is used, a queue is formed of input data blocks that are
waiting processing or of output data blocks that have been processed and are awaiting transfer to
auxiliary storage or to an output device.
Qualified data-name: An identifier that is composed of a data-name followed by one or more sets
of either of the connectives OF and IN followed by a data-name qualifier.
Qualifier: A data-name or a name associated with a level indicator which is used in a reference
either together with another data-name which is the name of an item that is subordinate to the
qualifier or together with a condition-name.
A section-name that is used in a reference together with a paragraph-name specified in that
section.
A library-name that is used in a reference together with a text-name associated with that library.
Random access: An access mode in which the program-specified value of a key data item
identifies the logical record that is obtained from, deleted from, or placed into a relative or indexed
file.
Record area: A storage area allocated for the purpose of processing the record described in a
record description entry in the File Section of the DATA DIVISION. In the File Section, the current
number of character positions in the record area is determined by the explicit or implicit RECORD
clause.
Record description entry: The total set of data description entries associated with a particular
record. The term is synonymous with record description.
Recording mode: The format of the logical records in a file. Recording mode can be F (fixed-
length), V (variable-length), S (spanned), or U (undefined).
Record key: A key whose contents identify a record within an indexed file.
Record-name: A user-defined word that names a record described in a record description entry in
the DATA DIVISION of a COBOL program.
Record number: The ordinal number of a record in the file whose organization is sequential.
Recursion: A program calling itself or being directly or indirectly called by a one of its called
programs.
Page 199
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Reel: A discrete portion of a storage medium, the dimensions of which are determined by each
implementor that contains part of a file, all of a file, or any number of files. The term is synonymous
with unit and volume.
Reentrant: The attribute of a program or routine that allows more than one user to share a single
copy of a load module.
Reference format: A format that provides a standard method for describing COBOL source
programs.
Reference modification: A method of defining a new alphanumeric data item by specifying the
leftmost character and length relative to the leftmost character of another alphanumeric data item.
Relation condition: The proposition, for which a truth value can be determined, that the value of
an arithmetic expression, data item, non-numeric literal, or index-name has a specific relationship
to the value of another arithmetic expression, data item, non-numeric literal, or index name. (See
also "relational operator.")
Relative key: A key whose contents identify a logical record in a relative file.
Relative organization: The permanent logical file structure in which each record is uniquely
identified by an integer value greater than zero, which specifies the record's logical ordinal position
in the file.
Relative record number: The ordinal number of a record in a file whose organization is relative.
This number is treated as a numeric literal which is an integer.
Reserved word: A COBOL word specified in the list of words that may be used in a COBOL
source program, but that must not appear in the program as user-defined words or system-names.
Page 200
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Resource: A facility or service, controlled by the operating system that can be used by an
executing program.
Resultant identifier: A user-defined data item that is to contain the result of an arithmetic
operation.
Routine: A set of statements in a COBOL program that causes the computer to perform an
operation or series of related operations. In Language Environment, refers to a procedure,
function, or subroutine.
Routine-name: A user-defined word that identifies a procedure written in a language other than
COBOL.
Run time: The time at which an object program is executed. The term is synonymous with object
time.
Run unit: A stand-alone object program, or several object programs, that interact via COBOL
CALL statements, which function at run time as an entity.
S
SBCS (Single Byte Character Set): See "Single Byte Character Set (SBCS)."
Scope terminator: A COBOL reserved word that marks the end of certain Procedure Division
statements. It may be either explicit (END-ADD, for example) or implicit (separator period).
Section: A set of zero, one or more paragraphs or entities, called a section body, the first of which
is preceded by a section header. Each section consists of the section header and the related
section body.
Section header: A combination of words followed by a separator period that indicates the
beginning of a section in the Environment, Data, and Procedure Divisions. In the ENVIRONMENT
and DATA DIVISIONs, a section header is composed of reserved words followed by a separator
period.
Selection structure: A program processing logic in which one or another series of statements is
executed, depending on whether a condition is true or false.
Sentence: A sequence of one or more statements, the last of which is terminated by a separator
period.
Page 201
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Sequential access: An access mode in which logical records are obtained from or placed into a
file in a consecutive predecessor-to-successor logical record sequence determined by the order of
records in the file.
Sequential organization: The permanent logical file structure in which a record is identified by a
predecessor-successor relationship established when the record is placed into the file.
Serial search: A search in which the members of a set are consecutively examined, beginning
with the first member and ending with the last.
* sign condition: The proposition, for which a truth value can be determined, that the algebraic
value of a data item or an arithmetic expression is either less than, greater than, or equal to zero.
Single Byte Character Set (SBCS): A set of characters in which each character is represented by
a single byte. See also "EBCDIC (Extended Binary-Coded Decimal Interchange Code)."
Slack bytes: Bytes inserted between data items or records to ensure correct alignment of some
numeric items. Slack bytes contain no meaningful data. In some cases, they are inserted by the
compiler; in others, it is the responsibility of the programmer to insert them. The SYNCHRONIZED
clause instructs the compiler to insert slack bytes when they are needed for proper alignment.
Slack bytes between records are inserted by the programmer.
Sort file: A collection of records to be sorted by a SORT statement. The sort file is created and
can be used by the sort function only.
Page 202
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Sorbetière file description entry: An entry in the File Section of the DATA DIVISION that is
composed of the level indicator SD, followed by a file-name, and then followed by a set of file
clauses as required.
Source program: Although it is recognized that a source program may be represented by other
forms and symbols, in this document it always refers to a syntactically correct set of COBOL
statements. A COBOL source program commences with the IDENTIFICATION DIVISION or a
COPY statement. A COBOL source program is terminated by the end program header, if specified,
or by the absence of additional source program lines.
Special registers: Certain compiler generated storage areas whose primary use is to store
information produced in conjunction with the use of a specific COBOL feature.
Standard data format: The concept used in describing the characteristics of data in a COBOL
DATA DIVISION under which the characteristics or properties of the data are expressed in a form
oriented to the appearance of the data on a printed page of infinite length and breadth, rather than
a form oriented to the manner in which the data is stored internally in the computer, or on a
particular external medium.
Statement: A syntactically valid combination of words, literals, and separators, beginning with a
verb, written in a COBOL source program.
STL: Standard Language file system: native workstation and PC file system for COBOL and PL/I.
Supports sequential, relative, and indexed files, including the full ANSI 85 COBOL standard I/O
language and all of the extensions described in IBM COBOL Language Reference, unless
exceptions are explicitly noted.
Structured programming: A technique for organizing and coding a computer program in which
the program comprises a hierarchy of segments, each segment having a single entry point and a
single exit point. Control is passed downward through the structure without unconditional branches
to higher levels of the hierarchy.
Page 203
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Sub-class: A class that inherits from another class. When two classes in an inheritance
relationship are considered together, the sub-class is the inheritor or inheriting class; the super-
class is the inheritee or inherited class.
Syntax: (1) The relationship among characters or groups of characters, independent of their
meanings or the manner of their interpretation and use. (2) The structure of expressions in a
language. (3) The rules governing the structure of a language. (4) The relationship among
symbols. (5) The rules for the construction of a statement.
System-name: A COBOL word that is used to communicate with the operating environment.
System Object Model (SOM): IBM's object-oriented programming technology for building,
packaging, and manipulating class libraries. SOM conforms to the Object Management Group's
(OMG) Common Object Request Broker Architecture (CORBA) standards.
T
Table: A set of logically consecutive items of data that are defined in the DATA DIVISION by
means of the OCCURS clause.
Table element: A data item that belongs to the set of repeated items comprising a table.
Trailer-label: (1) A file or data set label that follows the data records on a unit of recording
medium. (2) Synonym for end-of-file label.
Truth value: The representation of the result of the evaluation of a condition in terms of one of two
values: true or false.
U
Unary operator: A plus (+) or a minus (-) sign, that precedes a variable or a left parenthesis in an
arithmetic expression and that has the effect of multiplying the expression by +1 or -1,
respectively.
Unit: A module of direct access, the dimensions of which are determined by IBM.
Page 204
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
Universal object reference: A data-name that can refer to an object of any class.
Unsuccessful execution: The attempted execution of a statement that does not result in the
execution of all the operations specified by that statement. The unsuccessful execution of a
statement does not affect any data referenced by that statement, but may affect status indicators.
UPSI switch: A program switch that performs the functions of a hardware switch. Eight are
provided: UPSI-0 through UPSI-7.
User-defined word: A COBOL word that must be supplied by the user to satisfy the format of a
clause or statement.
V
Variable: A data item whose value may be changed by execution of the object program. A variable
used in an arithmetic expression must be a numeric elementary item.
Variable length record: A record associated with a file whose file description or sort-merge
description entry permits records to contain a varying number of character positions.
Variable occurrence data item: A variable occurrence data item is a table element which is
repeated a variable number of times. Such an item must contain an OCCURS DEPENDING ON
clause in its data description entry, or be subordinate to such an item.
Variably located group: A group item following, and not subordinate to, a variable-length table in
the same level-01 record.
Variably located item: A data item following, and not subordinate to, a variable-length table in the
same level-01 record.
Verb: A word that expresses an action to be taken by a COBOL compiler or object program.
Volume: A module of external storage. For tape devices it is a reel; for direct-access devices it is a
unit.
Volume switch procedures: System specific procedures executed automatically when the end of
a unit or reel has been reached before end-of-file has been reached.
VSAM (Virtual Storage Access Method): A high-performance mass storage access method.
Three types of data organization are available to COBOL programs: entry sequenced data sets
(ESDS), key sequenced data sets (KSDS), and relative record data sets (RRDS). Their COBOL
equivalents are, respectively: sequential, indexed, and relative organizations. A fourth type of
organization, linear data sets, is only available from Assembler.
Page 205
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
W
Windowed date field: A date field containing a windowed (2-digit) year. See also "date field" and
"windowed year."
Windowed year: Two digits representing a year within a century window (for example, 98).
Appears in windowed date fields.
Word: A character-string of not more than 30 characters which forms a user-defined word, a
system-name, a reserved word, or a function-name.
WORKING-STORAGE SECTION: The section of the DATA DIVISION that describes working
storage data items, composed either of noncontiguous items or working storage records or of both.
Y
Year 2000 problem: The Year 2000 problem refers to the limitation of 2-digit year date fields that
were used to save storage in the 1960s and 1970s. For example, it is not possible to compute the
age of someone who is older than 100 years with 2-digit year date fields, and on 1/1/2000, the
current date will not be greater than the previous day's date. Because so many applications and
data have only 2-digit year dates, they must all be changed before the year 2000 to avoid failure.
Z
Zoned decimal item: See "external decimal item."
Page 206
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
References
Websites
http://homepage.ntlworld.com/zingmatter/zingcobol/index.html
http://www.techtutorials.info/cobol.html
http://www.techiwarehouse.com/Cobol/Cobol_Tutorial.html
http://publibz.boulder.ibm.com/cgi-bin/bookmgr_OS390/library
http://www.csis.ul.ie/cobol/Course/COBOLIntro.htm
http://docs.hp.com/cgi-bin/doc3k/B3150090013.11820/10
Books
Stern and Stern Structured COBOL Programming - Nancy stern
Structured COBOL - Philippakis and Kazmier
COBOL Programming - Roy & Dastidar
How to design & develop COBOL programs - Paul N.
VS COBOL II - guide for programmers 2 ed. - Anne prince
Various COBOL IBM Manuals
Online Training Materials in Web
Page 207
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Handout - COBOL
STUDENT NOTES:
Page 208
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected