Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
SPECIAL
VALUE
UNIT 1
To meet the increasing demands for a high level language suitable for business data processing, the
United States Department of Defense Convened a Conference on 28th and 29th of May 1958.
Three committee were formed for the actual design of the language.
In September 1959 the short term committee submitted a report to the Defense Directorate thus
COBOL came into existence.
COBOL is known as a structured programming language because it allows programmers to
segregate the modules and put them into different paragraphs in a more efficient way.
Some of the features of COBOL are
It is English-like and more easily readable
Efficient file handling capabilities.
More than 70% of business applications are running on COBOL
Reduces the efforts required for documentation of the program.
IDENTIFICATION DIVISION
ENVIRONMENT DIVISION
DATA DIVISION
PROCEDURE DIVISION
Notes:
The four divisions of the COBOL source program are :
IDENTIFICATION DIVISION
ENVIRONMENT DIVISION
This division is primarily used to tell the computer about the input and output devices such
as files or printers.
DATA DIVISION
This division describes the data the program will be using and carves out sections
of memory to map the data. Here you would distinguish between data, which
will be used for a scratch pad area called WORKING-STORAGE and the
holding area for data that will be used by the files.
PROCEDURE DIVISION
The PROCEDURE DIVISION is the section of our program where the logic or
commands reside. This is the logic or rules we will use to manipulate the data
defined in the DATA DIVISION to solve a business problem.
Characters
Character String
COBOL Words
User-Defined Words
Reserved Words
Figurative Words
Special Registers
IBM Extensions
Non-numeric and numeric Literals
Divisions
Sections or Paragraphs
Statements
Sentences
DATA DIVISION
PROGRAM-ID
FILE SECTION, 100-PARA
MOVE A TO B
IF A>B MOVE A TO B ELSE
ADD C TO D
Notes:
All COBOL programs should follow the structure. Rules of coding varies, depending
on the compiler versions but the structure remains same. A period (.) is a must at the end of
each sentence and indicates the end of the sentence.
0-9
Alphabets
a-z, A-Z
Arithmetic operators
ex: **, *, +, -, /
Special characters
ex: - \ / , ;
Spaces or blanks
Notes:
The COBOL dictionary words used for coding are called COBOL reserved words and
they should not be used as user-defined words. Lower case alphabets can be used for coding
depending on the compiler version.comma (,) or space is used as separators for user-defined
words.
72 73
80
IDENTIFICATION DIVISION.
PROGRAM-ID. SAMPLE.
ENVIRONMENT DIVISION.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 A PIC 9(2) VALUE 20.
01 B PIC 9(2) VALUE 3O.
01 C PIC 9(3) VALUE ZEROS.
PROCEDURE DIVISION.
DISPLAY THE SUM IS.
ADD A ,B GIVING C.
DISPLAY C.
STOP RUN.
Notes:
1-6 -------------- Sequence numbers
7
-------------- Indicator/Comment/Continuation
8-11 -------------- Area A
12-72 -------------- Area B
73-80 -------------- Descriptor
This foil shows a sample COBOL program to ADD two numbers and DISPLAY the sum.
SAMPLE is the program name.
SAMPLE, A, B AND C are called user-defined words.
A, B,C are called variables or data-items.
Coding Format
Columns
Name
01-06
Purpose
Sequence
07
Indicator
08-11
Area A
12-72
Area B
73-80
Description
Notes:
COBOL coding should follow the standard format.
The Screen is divided into different areas for the purposes explained above.
All statements indicating action are called COBOL verbs and should begin from 12 th column or after.
-E.g
MOVE, ADD, DIVIDE, STOP RUN
User-defined Words
Valid
Invalid
TOTAL-OF-FIGURES
34B100-PARA1
GROSS-PAY
DATA
-48B
GROSS PAY
Reason
Cobol reserved word
Hyphen in beginning
space in b/w 2 words
Literals
Examples
Numeric constants
Alphanumeric constants
35, -345.67
Leo talstoy
ka01-h215
Notes:
UNIT 2
IDENTIFICATION DIVISION
IDENTIFICATION DIVISION.
PROGRAM-ID. <Pgm-name>
AUTHOR.
<Pgmr-name>
DATE WRITTEN. <Entry>
DATE-COMPILED. <Entry>
SECURITY. <Entry>
Required
Required
Optional
Optional
Optional
Optional
Notes:
The Identification Division must be the first division in every COBOL source program.
It must be coded as IDENTIFICATION DIVISION or ID DIVISION followed by a
separator period.
ENVIRONMENT DIVISION
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
SOURCE-COMPUTER. <Entry>.
OBJECT-COMPUTER. <Entry>.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
------------------------------------------------------I-O-CONTROL.
--------------------------------------------------------Notes:
The Environment Division is divided into two sections:
FILE-CONTROL paragraph
The keyword FILE-CONTROL can appear only once, at the beginning of the FILE-CONTROL
paragraph. It must begin in Area A, and be followed by a separator period.
The FILE-CONTROL paragraph is optional.
The FILE-CONTROL paragraph associates each file in the COBOL program with an
external dataset, and specifies file organization, access mode, and other information.
There are three formats for the FILE-CONTROL paragraph:
QSAM, SAM, and VSAM sequential file entries
VSAM indexed file entries VSAM relative file entries.
The FILE-CONTROL paragraph begins with the word "FILE-CONTROL", followed by a
separator period. It must contain one and only one entry for each file described in an FD or SD
entry in the Data Division. Within each entry, the SELECT clause must appear first, followed
by the ASSIGN clause. The other clauses can appear in any order.
I-O-CONTROL paragraph
Specifies information needed for efficient transmission of data between
the external data set and the COBOL program. The series of entries must
end with a separator period
The keyword I-O-CONTROL can appear only once, at the beginning of the
paragraph. The word I-O-CONTROL must begin in Area A, and must
be followed by a separator period.
Each clause within the paragraph can be separated from the next by
a separator comma or a separator semicolon. The order in which
I-O-CONTROL paragraph clauses are written is not significant
DATA DIVISION
Data division is the third and most frequently used division in all programs. Every variable
required by the program should be declared in appropriate section of the data division,
before using in procedure division
The Data Division is divided into three sections:
.
File Section
Defines the structure of data files (including sort-merge files).
Working-Storage Section
Describes records and subordinate data items that are not part of data
files but are required by the program.
. Linkage Section
Describes data made available by another program. It usually appears in the called
program and describes data items that are referred to by the calling and
the called programs.
Each section has a specific logical function within a COBOL source program, and each
can be omitted from the source program when that logical function is not needed.
If included, the sections must be written in the order shown.
DATA DIVISION.
FILE SECTION.
FD .
---------------------------------------------
WORKING-STORAGE SECTION.
01 VAR-1
01 ID-1
01 DATA-NAME
Level number
PIC
PIC
PIC
picture
Clause
LINKAGE SECTION.
record-description-entry
data-item-description-entry
DATA TYPES
A(5).
-Alphabetic
X(10)
-Alphanumeric
9(5)
-Numeric
DATA-ITEMS
Notes:
Data item is a user-defined word which is associated with Level number.
COBOL Reserved words should not be Data items .
Level Numbers
.
.
Level-number 01 and 77 must begin in Area A and must be followed either by a separator period;
or by a space, followed by its associated data-name, FILLER, or appropriate data description clause.
Level numbers 02 through 49 can begin in Areas A or B and must be followed by a space or
a separator period.
Level number 66 and 88 can begin in Areas A or B and must be followed by a space.
Single-digit level-numbers 1 through 9 can be substituted for level-numbers
01 through 09.
Successive data description entries can start in the same column as the first or they can be indented according to the levelnumber. Indentation does not affect the magnitude of a level-number.
When level-numbers are indented, each new level-number can begin any number of spaces to
the right of Area A. The extend of indentation to the right is limited only by the width of Area B.
Higher numbered level(s) represent subordinate definition(s).
Level numbers need not be consecutive(but should be in ascending order)
Picture Clause
Describes the characteristics of the data
CODE
A
B
G or N
9
X
P
V
S
Meaning
Alphabetic or space
Blanks or spaces
Graphical data
Indicates a Numeric
Indicates an Alpha Numeric
Indicates the position of the assumed
Decimal point when the point lies
Outside the data item.
Indicates the position of assumed
Decimal point of numeric field.
Indicates whether the data item signed.
Notes:
Picture clause specifies the data type of an identifier.
Identifier with PIC clause 9 implies that it is numeric data type, which can take art in arithmetic
computations. V and S clauses are allowed with numeric data types only.
X clause represents an alphanumeric data type which can hold any character including numbers also.
A clause indicates an alphabetic data type.
Group items are always considered as alphanumeric only. Therefore GROSS-PAY, DEDUCTIONS can
not be used for computations
W-S Declarations
WOKING-STORAGE SECTION.
01 PAY.
05 GROSS-PAY.Alternatively
10 BASIC PIC 9(4)V99.
10 DA
PIC 9(4)V99.9(4)V9(2)
10 HRA
PIC 9(4)V999999V99
05 DEDUCTIONS.
07 PF-DED PIC
07 IT-DED PIC
05 NET-PAY
PIC
05 NAME
PIC
05 E-CODE
PIC
9(3)V99.
9(3)V99.
9(4)V99.
A(5).AAAAA
X(6).XXXXXX
Notes:
Pay, gross-pay, deductions are called group items and they dont have PICTURE clause. Other elements with
picture clause are called elementary items, which cannot be broken further.
Pay is a Group item is divided into Gross-pay, Deductions, net-pay, name, e-code further Gross-pay sub-divided
into Basic, DA, HRA and DEDUCTIONS sub-divided into PF-DED and IT-DED.
FILLER
FILLER is a COBOL Reserved Word used to describe data fields that will not
be referenced in the PROCEDURE DIVISION.
If the data-name of FILLER clause is omitted, the data item being described is treated as
though it was FILLER
01 EMPLOYEE-RECORD.
05 EMPLOYEE-TYPE
05 EMPLOYEE-SERIAL
05 EMPLOYEE-NAME
05
05 EMPLOYEE-ADDRESS
05 FILLER
PIC X.
PIC X(6).
PIC X(30).
PIC X(2).
PIC X(60).
PIC X(34).
Notes:
FILLER is a data item that is not explicitly referred to in a program. The key word FILLER is optional.
If specified, FILLER must be the first word following the level-number.
IF data-name or FILLER clause is omitted, the data item being described is treated as though FILLER had been
specified.
The VALUE clause may be used on FILLER items, e.g. to assure BLANKS in header lines between fields.
In a MOVE CORRESPONDING statement ,or in an ADD CORRESPONDING or SUBTRACT
CORRESPONDING statement ,FILLER items are ignored.
In an INITIALIZE statement, elementary FILLER items are ignored.
USAGE Clause
<level number> data-name [PIC
X(n)] [USAGE]
COMP
COMP-1
COMP-2
COMP-3
COMP Binary Representation
Size:
Half/Full/Double word
COMP-1 Hexa Decimal Representation Size:
Full word for Float
COMP-2 COMP-3 Where n is number of digits.
Notes:
The USAGE clause can be specified for a data description entry with a level-number other than 66 or 88.
However, if it is specified at the group level, it applies to each Elementary item in the group. The usage
of an elementary item must not contradict the usage of a group to which the elementary item belongs.
The USAGE clause specifies the format in which data is represented in storage. The format can be restricted
if certain Procedure Division statements
When the USAGE clause is not specified at either the group or elementary level, it assumed
that the usage is DISPLAY
COMPUTATIONAL-2(COMP-2)Usage
This usage is same as COMP-1, except that the data is represented internally in two words.
The advantages is that this increases the precision of the data which means that more significant
digits can be available for the item. The PICTURE clause cannot be specified for COMP-2 items.
COMPUTATIONAL-3(COMP-3)Usage
In this form of internal representation the numeric data is the decimal form, but one digit
takes half-a-byte. The sign is stored separately as the right most half a-byte regardless of whether
S is specified in the PICTURE or not. The hexa decimal number C or F denotes a positive sign
and the Hexa decimal number D denotes a negative sign. Inorder that data fields can start and end
on byte boundaries, numbers with an even number of digits are stored with an extra half-byte of
zeroes on the left hand side.
PICTURE
S9(5)V9(3)
USAGE IS COMP-3
Will require 5 bytes to be stored internally. Only the characters 9,S, V and P can be used in the
PICTURE of a COMP-3 item.
Value Clause
EXAMPLES.
01 NUM-1
PIC 9(3)
VALUE 245.
01 E-CODE
PIC X(6)
VALUE E10K3.
At group level
contents
01 GROUP-ITEM
VALUE IS ER34155
05 E-ITEM-1
PIC X(2).
ER
05 E-ITEM-2
PIC XXX
341
05 E-ITEM-3
PIC X(3)
55
Notes:
Assigning values to identifiers is called initialization. If variables are not initialized, then they
may contain any value, which was stored at the time of last execution of program. It is advised to always
working-storage variables.
initialize
REDEFINES Clause
Two or more data items can share the same working storage area by
REDEFINING a storage area.
Level number data name-1 REDEFINES data-name-2
Notes:
Two or more storage areas defined in the data sometimes may not be used simultaneously, in such
cases, only one storage area can serve the purpose of two or more areas if the area is defined.
The REDEFINES clause used allows the said area to be referred to by more than one data name
with different sizes and pictures.
DISPLAY X5.
STOP RUN.
XX.
02 Name
02 Dept
01 Print-Rec.
02 Filler
02 Id-numbers
02 Filler
02 Name
02 Dept
PIC 9(5).
PIC X (25).
PIC X (20).
PIC X (5).
PIC X (5)
PIC X (5).
PIC X (25).
PIC X (920).
RENAMES Clause
Syntax:
66 data-name-1 RENAMES data-name-2 THRU data-name-3
E.g. :
01
66
66
PAY REC.
02 FIXED-PAY.
05 BASIC
PIC
9(6) V99.
05 DA
PIC
9(6) V99.
02 ADDITIONAL-PAY.
05 HRD
PIC
9(4) V99.
05 INCENT
PIC
9(3) V99.
02 DEDUCTIONS.
05 PF
PIC
9(3) V99.
05 IT
PIC
9(4) V99.
05 OTHER
PIC
9(3) V99.
PAY-OTHER-THAN-BASIC RENAMES DA THRU INCENT.
IT-AND-PF-DEDUCTIONS RENAMES PF THRU IT.
PROCEDURE DIVISION.
MAIN-PARA
MOVE-123456.78 TO E-BASIC.
MOVE 234567.89 TO E-DA.
MOVE 1234.56 TO HRA.
MOVE 123.45 TO INCENTIVE.
MOVE 123.45 TO E-PF.
MOVE 1234.56 TO E-IT.
MOVE 123.45 TO OTHERS.
DISPLAY PAY.
DISPLAY FIXED-PAY.
DISPLAY ADDL-PAY.
DISPLAY DEDUCTIONS.
DISPLAY PAY-LESS-BASIC.
DISPLAY IT-AND-PF.
STOP RUN.
Figurative Constants
Meaning
HIGH-VALUE(S)
LOW-VALUES (S)
SPACE (S)
Example
Edited Fields
Editing Codes
Z
*
$
Effect
Leading Zeros if any will be suppressed
Leading Zeros are replaced by asterisks(*)
Currency sign appears in the left most of the
field.
-
EDIT CODES
MEANING
CR or DB
-(hyphen) / (slash)
EXAMPLES
DATA
02346
PIC CLAUSE
UNEDITED
9(5)
PIC CLAUSE
EDITED
ZZ999
EDITED
VALUE
2346
0005
9(4)
ZZ99
05
03.42
99V99
Z999
003
0.007
9V999
ZV999
007
05634
9(5)
**999
*5634
00143
9(5)
$9(5)
$00143
453
9(3)
$**999
$**453
-0453
s9(4)
-ZZ9(2)
- b453
-0453
s9(4)
9999-
0453-
453
9(3)
999-
453
-453
s9(3)
999+
453-
70.46
99V99
99.99-
70.46
156758
9(6)
99/99/99
15/67/58
00
99V9
0.00
8654
9(4)
86b5b4
24
99
9900
2400
Notes:
The above table shows contents of unedited fields in the first column. Contents of edited fields
after moving the data-1 shown in last column.
Edited fields (Fields with editing codes) cannot take part in arithmetic computations. Moving of numeric
edited fields to unedited fields is illegal.
UNIT 3
PROCEDURE DIVISION
PROCEDURE DIVISION
PROCEDURE DIVISION[USING <DATA-ITEM1>, <DATA-ITEM2>.
MAIN-PARA.
DISPLAY ENTER VALUE OF A:.
ACCEPT A.
DISPLAY ENTER VALUE OF B:.
ACCEPT A.
MOVE A TO B.
ADD A TO B.
DISPLAY A VALUE : A.
DISPLAY B VALUE : B.
----------------------------------------------------------------
STOP RUN.
Notes :
COBOL VERBS
MOVE
ACCEPT
DISPLAY
PERFORM
GOTO
STOP RUN
CALL
COPY
SORT
MERGE
FILE OPERATIONS
CHARACTER
HANDLING
TABLE HANDLING
CONDITIONS
ARITHMETIC VERBS
Notes:
Arithmetic Verbs
Conditions
: IF.ELSE, EVALUATE
File handling
Character handling
Table handling
: SET, SEARCH
Paragraphs
Paragraphs are building blocks of the PROCEDURE DIVISION
PROCEDURE DIVISION.
MAIN-PARA.
STATEMENT1.
STATEMENT2.
-------------------------------------------------------------PARA-100.
-----------------------------------------------
Notes:
A paragraph-name must begin in Area A and must be followed by a separator period.
A paragraph-name need not be unique because it can qualified by a SECTION name.
Paragraph-names need NOT contain any alphabetic character (i.e. can be all numeric).
A paragraph ends at:
Terminator statements
EXIT PROGRAM.
The EXIT PROGRAM statement specifies the end of a called program and returns
control to the calling program
STOP RUN.
The STOP RUN statements halts the execution of the object program, and returns
control to the system
GOBACK.
The GOBACK statement functions like the EXIT PROGRAM statement
When it is coded as part of a called program and like the STOP RUN when coded in a
main program
Notes:
If these statements are not the last statements in a sequence, statements following them will not
be executed.
Scope Terminators
Explicit scope terminators mark the end of certain PROCEDURE DIVISION statements.
Explicit scope terminators are COBOL Reserved Words.
END-ADD
END-SEARCH
END-MULTIPLY
END-START
END-PERFORM
END-STRING
END-READ
END-DIVIDE
END-EVALUATE
END-REWRITE
END-IF
END-CALL
END-COMPUTE
END-DELETE
END-UNSTRING
END-WRITE
An explicit Scope Terminator is paired with the unpaired occurrence of the verb.
An implicit Scope Terminator is a separator period.
Notes:
Example:
PERFORM PARA-1 UNTIL A > 10
STATEMENT1
STATEMENT2
-------------------------------------------------------END-PERFORM.
Period(.) should not encounter in between PERFORM and END-PERFORM. Since it indicates end of
the PERFORM statement, then compiler error will raise.
Display verb
The function of the DISPLAY statement is to display low-volume results on the
operators console or some other hardware device.
Syntax :
>>____DISPLAY_____ __identifier-1___ __ |
_____________________________________________>
| _ literal-1______|
e.g:
PROCEDURE DIVISION.
DISP-PARA.
DISPLAY SRCH-ARG NOT IN TABLE..
---------------------------------------------------------------DISPLAY HELLO HOW ARE YOU.
Notes:
The DISPLAY statement transfers the contents of each operand to the output device. The contents are
displayed on the output device in the order, left to right, in which the operands are listed.
WITH NO ADVANCING When specified, the positioning of the output device will not be changed in
any way following the display of the last operand.
ACCEPT Verb
Format 1 transfers data from an input/output device into identifier-1.
When the FROM phrase is omitted, the system input device is assumed.
Format 1 is useful for exceptional situations in a program when
operator intervention (to supply a given message, code, or exception indicator)
is required.
Format 1 :
>>__ACCEPT______identifier-1___ __________________________________________><
| _ FROM__ _mnemonic-name-1___ _|
| _ environment-name _ |
77 SEARCH-VALUE
PIC X(10).
.
ACCEPT SEARCH-VALUE FROM SYSIN.
Notes:
The ACCEPT statement transfers data into the specified identifier. There is no editing or error checking
of the incoming data.
If the source of the ACCEPT statement is a file and identifier-1 is filled without using the full record
delimited by the record terminator, the remainder of the input record is used in the next ACCEPT
statement for the file. The record delimiter characters are removed from the input data before the input
records are moved into the ACCEPT receiving area.
If the source of the ACCEPT statement is a terminal, the data entered at the terminal, followed by the
enter key, is treated as the input data. If the input data is shorter than identifier-1, the area is padded with
spaces.
MOVE Verb
MOVE verb is used to copy the contents of an identifier into another identifier.
MOVE <identifier-1>
Or
<literal-1>
TO <identifier-2>[<identifier-3>,.].
E.g.:
MOVE A TO B,C,D
MOVE dataname-1 to dataname-2
MOVE 345 to num-1
MOVE 345 TO K
MOVE XYZ TO data-name-1
If the length of the receiving field is less than the length of sending field then truncation
occurs.
Notes:
The MOVE statement transfers data from one area of storage to one or more other areas.
An index data item cannot be specified in a MOVE statement.
If the sending field(identifier-1) is reference-modified, subscripted, or is an alphanumeric or
alphabetic function-identifier, the reference-modifier, subscript, or function is evaluated only
once, immediately before data is moved to the first of the receiving operands.
Notes:
Elementary move
-
Group Move
-
CORRESPONDING Phrase
01 STRUCT-1.
03 FIELD-A
03 FIELD-B
03 FIELD-C
03 FIELD-D
01 STRUCT-2.
10 FIELD-C
10 FILLER
10 FIELD-B
10 FILLER
10 FIELD-A
10 FILLER
PIC
PIC
PIC
PIC
PIC
PIC
PIC
PIC
PIC
PIC
Z(4).99.
XXX.
X(5).
XXX.
Z(9)
XXX.
PROCEDURE DIVISION.
PARA 1.
MOVE E-ID OF DATA-1 TO E-ID OF DATA-2
MOVE E-NAME OF DATA-1 TO E-NAME OF DATA-2.
MOVE E-DEPT OF DATA-1 TO E-BASIC OF DATA-2.
DISPLAY DATA-1
DISPLAY DATA-2
MOVE SPACES TO DATA-2.
MOVE CORRESPONDING DATA-1 TO DATA-2.
DISPLAY DATA-1
DISPLAY DATA-2.
STOP RUN.
Reference Modification
Reference Modification defines a data item by specifying its leftmost character and
optionally, a length
MOVE data-name1(begin : [length]) TO data-name2
The data name must have usage DISPLAY. It may be qualified or subscripted. When
qualified or subscripted, the reference modification is specified last.
WORKING-STORAGE SECTION.
01
01
01
01
ADD Verb
All identifiers (or literals) preceding the word TO are added together, and then this
sum is added to, and replaces, each identifier-2. The action is repeated in order left-to- right for each
identifier-2.
Identifiers must be elementary numeric items.
Format 1 :
>>___ADD_______ identifier-1_ _|__ To _____identifier-2__ _ ______ _______|____>
|_literal-1___|
|_ROUNDED _|
>___ _______________________________________ ___________________________>
|_ ____ __SIZE ERROR imperative-statement-1______|
>___ ________________________________________ ___________________________>
|_ NOT___ ______ ___SIZE ERROR__imperative statement_2_|
>___ _______ ___________________________________________________________>
|_ END-ADD_|
In Format 1, all identifiers or literals preceding the key word TO are added together, and this
sum is stored in a temporary data item. This| temporary data item is then added to each
successive occurrence of identifier-2, in the left-to-right order in which identifier-2 is specified.
Identifier must name an elementary numeric item.
Literal must be a numeric.
The ADD statement sums two or more numeric operands and stores the result.
Example :
ADD A TO B.
ADD 112 TO B.
ADD A TO B ON SIZE ERROR GO TO ERR-PARA.
ADD Verb(Continue)
The operands preceding the GIVING are added together and the sum
replaces the value of each identifier-3.
In Format 2, the values of the operands preceding the word GIVING are added together,
and the sum is stored as the new value of each data item referenced by identifier-3.
Identifier must name an elementary numeric item, except when following the word
GIVING. Each identifier following the word GIVING must name an elementary
numeric or numeric-edited item
Literal must be a numeric.
Example :
ADD A TO B GIVING C
If the value of an arithmetic evaluation exceeds the largest value that can be contained
in a result, then a size error condition exists.
The SIZE ERROR condition applies to final results, not intermediate calculations
If ON SIZE ERROR phrase is not specified, then truncation of the results will occur.
When the absolute value of the result of an arithmetic evaluation, after decimal point alignment,
exceeds the largest value that can be contained in the result field
.
.
Zero raised to a
negative power
Program is terminated
abnormally
A negative number
raised to a fractional
power
The size error condition applies only to final results, not to any intermediate results
NUMERIC Data
Types of numeric items are:
Binary
Packed decimal. (internal decimal)
Floating point representation.
The PICTURE character-string can contain only the symbols 9, P, S, and V
The number of digit positions must range from 1 through 18, inclusive
If unsigned, the contents of the item in standard data format must contain a
combination of the Arabic numerals 0-9. If signed, it may also contain a +, -, or
other representation of the operation sign
Notes:
A VALUE clause can specify a figurative constant ZERO
SUBTRACT Verb
Format 1 :
>>___SUBTRACT_______ identifier-1_ _|__ FROM____________________________>
|_literal-1___|
> ______identifier-2__ ___ _|________________________________________________>
| _ ROUNDED ____|
>___ ________________________________________ ___________________________>
|_ ____ __SIZE ERROR imperative-statement-1______|
|_ON _|
>___ ________________________________________ ___________________________>
|_ NOT___ ______ ___SIZE ERROR__imperative statement_2_|
>___ _______ _________________________________________________>
|_ END-SUBTRACT_|
All identifiers or literals preceding the key word FROM are added together and this sum
is subtracted from and stored immediately in identifier-2. This process is repeated for each
successive occurrence of identifier-2, in the left-to-right order in which identifier-2 is specified .
SUBTRACT Verb(Continue.)
Format 2 :
>>___SUBTRACT_______ identifier-1_ _|__ FROM ___ _ identifier-2__ _______________>
|_literal-1___|
|_literal-2______|
>___ GIVING ___________identifier-3__ ______________ _| _________________________ >
|_ ROUNDED__|
>___ ____________________________________________ ____________________________ >
|_
_______ ___SIZE ERROR__imperative statement_1_|
|_ ON _|
>___ ____________________________________________ ____________________________ >
|_ NOT___ ______ _SIZE ERROR__imperative statement_2_|
|_ ON_|
>___ _______ __________________________________________________________________ >
|_ END-SUBTRACT_|
All identifier or literals preceding the key word FROM are added together and this sum is
subtracted from identifier-2 or literals-2. The result of the subtraction is stored as the new value of
each data item referenced by identifier-3.
Notes:
Example:
1. SUBTRACT A FROM B.
The value of A subtttracted from the value of B and then the resultant value will be stored in B.
2. SUBTRACT 9 FROM C.
3. SUBTRACT C FROM 9. Is not valid because 9 is a Literal.
Elementary data items within identifier-1 are subtracted from, and the results are stored in, the
corresponding elementary data items within identifier-2.
MULTIPLY Verb
Format 1 :
>>___MULTIPLY_______ identifier-1___ ___BY____identifier-2___ ______________| __________>
|_ literal-1________|
MULTIPLY Verb(Continue..)
Format 2 :
>>___MULTIPLY_______ identifier-1_ _|__ BY_______ _ identifier-2__ ______________>
|_literal-1___|
|_literal-2______|
>___ GIVING ___________identifier-3__ ______________ _| _______________________ >
|_ ROUNDED__|
>___ _____________________________________________________ ________________ >
|_
_______ ___SIZE ERROR__imperative statement_1_|
|_ ON _|
>___ _____________________________________________________ ________________>
|_ NOT___ ______ _SIZE ERROR__imperative statement_2_|
|_ ON_|
>___ _______ ______________________________________________________________ >
|_ END-MULTIPLY_|
In Format 2, the value of identifier-1 or literal-1 is multiplied by the value of identifier-2
or literal-2.The product is then stored in the data item(s) referenced by identifier-3.
DIVIDE Verb
Format 1 :
>>___DIVIDE_____ _____ identifier-1_ _|__ INTO__________identifier-2____ _____
|_literal-1___|
|_ROUNDED
__ |____>
_|
DIVIDE Verb(Continue)
Format 2 :
>>___DIVIDE_______ identifier-1_ _|__ INTO_______ _ identifier-2__ ___________________________>
|_literal-1___|
|_literal-2______|
In Format 2, the value of identifier-1 or literal-1 is divided into or by the value of identifier-2 or literal-2.
The value of the result is stored in each data item referenced by identifier-3.
COMPUTE Verb
Format :
>>___COMPUTE_______ identifier-1_ ____________ _|____ _ =______ __________________________>
|_ ROUNDED _|
|_ EQUAL_|
>___ arithmetic expression________________________________________________________________ >
>___ _____________________________________________________ ____________________________ >
|_
_______ ___SIZE ERROR__imperative statement_1_|
|_ ON _|
>___ _____________________________________________________ ____________________________ >
|_ NOT___ ______ _SIZE ERROR__imperative statement_2_|
|_ ON_|
>___ _______ __________________________________________________ >
|_ END-COMPUTE_|
The arithmetic expression is calculated and replaces the value for each identifier-1 item. Valid operators
allowed in the expression are:
+ addition
- subtraction
* multiplication
/ division
** exponentiation
Notes:
The COMPUTE statement assigns the value of an arithmetic expression to one or more data items.
With the COMPUTE statement, arithmetic operations can be combined without the restrictions on receiving
data items imposed by the rules for the ADD, SUBTRACT, MULTIPLY, and DIVIDE statements.
When the COMPUTE statement is executed, the value of the arithmetic expression is calculated, and this
value is stored as the new value of each data item referenced by identifier-1.
PERFORM Statement
PERFORM Paragraph-name/Section-header
Transfer the control to the specified paragraph or section and expects the control back after
executing the paragraph.
PERFORM para-name
PERFORM para-name N TIMES
PERFORM para-name VARYING K FROM M BY N
UNTIL CONDITION K>20
VARYING.
PERFORM THROUGH
PROCEDURE DIVISION.
100-MAIN-PARA.
PERFORM 200-PARA THRU 500-PARA.
STOP RUN.
200-PARA.
* Statements.
400-PARA.
* Statements
500-PARA.
* Statements
300-PARA.
* Statement - Not executed
All the paragraphs between 200-PARA and 500-PARA are executed.
PERFORMN times
PERFORMVARYING
PERFORM PARA-NAME-1 [THRU (or) THROUGH PARA-NAME-N]
VARYING { identifier- 1 }
{identifier-2 }
{Index-name-1} FROM
{index-name-2}
{ Literal-1
}
BY
{identifier-3 }
UNTIL
Condition
{Literal-2 }
EX:
1. PERFORM PARA-2000 THRU PARA-5000 VARYING A FROM M BY N
UNTIL A > Y
2. PERFORM para-1 Varying K FROM 10 BY 5
UNTIL K>100
Notes:
Example 2 says :
Sets the value of K to 10 initially
Execute para-1
Check the condition K>100
If condition is true, transfer the control to next line
If condition is false, increment K by 5
Execute para-1 again
Check the condition K > 100
Repeat steps from 2 through 7 until Condition K > 100 becomes true
Enter
Set identifier 1
to initial value
Exit
Conditi
on
False
Execute range
{ identifier- 4 }
{Index-name-3}
BY
{identifier-6 }
{Literal-4 }
AFTER
BY
{ identifier- 7 }
{Index-name-5}
FROM
UNTIL
FROM
{identifier-5 }
{index-name-4}
{ Literal-3
}
Condition-2
{identifier-8 }
{index-name-6}
{ Literal-5
}
{identifier-9 }
UNTIL
Condition-3
{Literal-6 }
This form is used when a nested repetition of the range is required while varying more than one
identifier.
For example
PERFORM RANGE-TO-BE-EXECUTED
VARYING I FROM 1 BY 1 UNTIL I > 50
AFTER
J FROM 1 BY 1 UNTIL J > 10.
The range RANGE-TO-BE-EXECUTED will be performed 500 times,.
In-Line PERFORM
The in-line PERFORM will be coded using END-PERFORM.
Named Paragraph
PERFORM MOVEIT
VARYING X FROM 1 BY 1 UNTIL X = 5.
...
MOVEIT.
MOVE DATA-FLD (X) TO PRINT (X).
In-line PERFORM
PERFORM VARYING X FROM 1 BY 1 UNTIL X = 5.
MOVE DATA-FLD (X) TO PRINT (X).
END-PERFORM.
Notes:
An In-line PERFORM requires the END-PERFORM terminator. Conversely the
END-PERFORM phrase must not be specified when the statement is PERFORM procedure name.
Delimited by END-PERFORM.
The OPTIMIZE compile option may move the PERFORM in-line in the object code at
the compile time.
IF .. ELSE Statement
The IF statement evaluates a condition and provides for alternative actions in the object
program, depending on the evaluation.
Format :
>>_______IF_____Condition-1____ __________ _____ ___statement-1___|__ ________>
|_THEN_____|
|_NEXT SENTENCE _|
>___ ______________ ____ ________________ ______________________________>
|
<____________
|
|
(1) |
| _ ELSE__ ___statement-2_|_____ |
|___END-IF________|
Note :
(1) END-IF can be specified with NEXT SENTENCE as an IBM extension.
Notes:
The IF statement evaluates a condition and provides for different sets of statements to execute, depending
on the evaluation of the IF.
Condition can be any simple or complex condition.
NEXT SENTENCE
If the NEXT SENTENCE phrase is specified, and then the END-IF phrase must not be specified.
NEXT SENTENCE passes control to the statement after the closest following period. However, if
the NEXT SENTENCE phrase is executed, control will not pass to the statement after the closest
following period.
Compound Conditionals
Conditional expressions can be compound using the AND and OR logical operators
Conditional conditions can also use parentheses to group conditions.
IF
ITEM-1
=
DOMESTIC-ITEM-NO
AND ITEM-2
=
OVERSEAS-ITEM-NO
OR
ITEM-1
=
OVERSEAS-ITEM-NO
AND ITEM-2
=
DOMESTIC-ITEM-NO
SET MIXED-SHIPMENT-FLAG TO TRUE
END-IF
.
SEARCH TABLEPAIR VARYING NDX
WHEN ITEM-1(NDX) = FROM-CITY AND ITEM-2(NDX) = TO-CITY
MOVE
WHEN ITEM-2(NDX) = FROM-CITY AND ITEM-1(NDX) = TO-CITY
MOVE ..
END-SEARCH
Relational Expressions
IS LESS THAN
IS NOT LESS THAN
GREATER THAN
IS NOT GREATER THAN
IS EQUAL TO
IS NOT EQUAL TO
IS GREATER THAN OR EQUAL TO
IS LESS THAN OR EQUAL TO
IS <
IS NOT <
IS >
IS NOT >
IS =
IS NOT =
IS >=
IS <=
Example 2 CONTINUE
IF A=B
IF C=D
CONTINUE
ELSE
MOVE MESSAGE-1 TO RPT-MESSAGE-1
END-IF
ADD C TO TOTAL
DISPLAY TOTAL
IF E=F
MOVE MESSAGE-4 TO RPT-MESSAGE-2
END-IF
END-IF.
EVALUATE Statement
WHEN OTHER
END-EVALUATE
Perform add-trans
Perform delete-trans
Perform update-trans
Perform bad-trans
The scope of a WHEN clause is all statements UNTIL the next WHEN clause,
the END-EVALUATE, or a period
Notes:
The EVALUATE statement provides a shorthand notation for a series of nested IF statements. It
can evaluate multiple conditions. That is, the IF Statements can be made up of compound
conditions.
Examples:
Working-Storage for all Examples:
01 PLANET.
05 PLANET-NUMBER PIC 9.
05 PLANET-NAME PIC X(7).
TO
TO
TO
TO
TO
TO
TO
TO
TO
TO
PLANET-NUMBER
PLANET-NUMBER
PLANET-NUMBER
PLANET-NUMBER
PLANET-NUMBER
PLANET-NUMBER
PLANET-NUMBER
PLANET-NUMBER
PLANET-NUMBER
PLANET-NUMBER
INITIALIZE Statement
The INITIALIZE statement sets selected categories of data fields to predetermined values. It
is functionally equivalent to one or more MOVE statements.
When the REPLACING phrase is not used:
SPACE is the implied sending field for alphabetic alphanumeric, alphanumeric-edited, and
DBCS items.
ZERO is the implied sending field for numeric and numeric-edited items.
>>___INITIALIZE____identifier- 1 ________________________________________>
>___ ___________________________ _________________
_______><
|
< ____________________________________________ __________________
|_REPLACING____ _ALPHABETIC_______ __ _______ __BY____ identifier-2 _ _ | _ |
|_ALPHANUMER____| |_DATA_|
|_LITERAL-1__|
|_NUMERIC __________|
|_ALPHANUMERIC-EDITED_|
|_NUMERIC-EDITED__|
|_ DBCS _____________|
|_ EGCS _____________|
Notes:
The INITIALIZE statement sets selected categories of data fields to predetermined values. It is functionally equivalent to
one or more MOVE statements.
A subscripted item can be specified for identifier-1. A complete table can be initialized only by specifying
a group that contains the complete table.
identifier-1 as
The data description entry for identifier-1 must not contain a RENAMES clause. An index data item cannot be
an operand of INITIALIZE.
Special registers can be specified for identifier-1 and identifier-2 only if they are valid receiving fields or
fields, respectively, for the implied MOVE statement(s).
sending
When this form of the SET statement is executed, the value associated with a
condition-name is placed in its conditional variable according to the rules of the
VALUE clause.
>>__SET____condition-name-1_|_ TO TRUE_________________________><
condition-name-1: Must be associated with a conditional variable.
If more than one literal is specified in the VALUE clause of condition-name-1, its
associated conditional variable is set equal to the first literal.
01 CUST-TYPE
PIC 99.
88 INACTIVE
VALUE 9.
88 SPEC-ACCTS VALUE 20, 11, 40, 44.
Class Condition
NUMERIC
The item entirely contains characters 0 through 9 (with or without a sign determined by its
clause). It may be USAGE DISPLAY or PACKED DECIMAL.
ALPHABETIC
The entire item contains only A through Z, a through z, or spaces
ALPHABETIC-UPPER
The entire item contains only A through Z (exclusively upper-case) or spaces.
ALPHABETIC-LOWER
The entire item contains only a through z (exclusively lower-case) or spaces.
Notes:
Ex:
1. IF A IS NUMERIC
-------------------------------------------2.
IF C IS ALPHABETIC
---------------------------------------------Where A and C are Data items.
PICTURE
UNIT 4
FILES
E.g.:
Details of an employee
-Name, Adds, Phone no., Dept no etc Forms a record
Notes:
Files can be broadly categorized into Program files and Data files. In COBOL the term Files is used to
indicate data files. Data files are normally created on a tape or disk and subsequently
program can refer
them.
FILE-CONTROL Paragraph
Format:
SELECT [OPTIONAL] File-name-1 ASSIGN TO Assignment-name-1
[ RESERVE <INTEGER> AREA ]
SEQUENTIAL
[ ORGANIZATION IS
INDEXED
RELATIVE
[ACCESS MODE IS
SEQUENTIAL
RANDOM
DYNAMIC
SELECT OPTIONAL may be specified only for files opened in the input, I-O, or extended mode.
You must specify SELECT OPTIONAL for such input files that are not necessarily present each
time the program is executed.
The file-name-1 must be identified by an FD or SD entry in the DATA DIVISION.
The ASSIGN clause associates the programs name for a file with the external name for the
actual data file.
The RESERVE clause allows you to specify the number of input/output buffers to be allocated at
run time for the file.
The ORGANIZATION clause identifies the logical structure of the file.
ORGANIZATION IS SEQUENTIAL
The Records are stored in contiguous allocation. To access the record in Sequential mode only
(I.e. to read the last record, it reads all the records until last record found.)Deletion of record
is not possible.Updating is possible but record length should not changed.
ORGANIZATION IS INDEXED
Each record in the file has one or more embedded keys; each key is associated with an index.
An index provides a logical path to the data records, according to the contents of the
associated embedded record key data items. Indexed files must be direct-access storage
files.
Records can be fixed-length or variable-length.
Each record in an indexed file must have an embedded prime key data item. When records
are inserted, updated, or deleted, they are identified solely by the values of their prime keys.
Thus, the value in each prime key data item must be unique and must not be changed when the
record is updated.
In addition, each record in an indexed file can contain one or more embedded alternated key data
items. Each alternated key provides another means of identifying which record to retrieve.
The RECORD KEY clause specifies the data item within the record that is the prime
RECORD KEY for an indexed file. The values contained in the prime RECORD KEY data
item
must be unique among records in the file.
The ALTERNATRE RECORD KEY clause specifies a data item within the record that provides
an alternated path to the data in an indexed file. Used like the RECORD KEY but for an alternate
index.
ORGANIZATION IS RELATIVE
The INPUT-OUTPUT FILE-CONTROL for Relative record files is very similar to that of
indexed files except you use the RELATIVE KEY clause of the ACCESS MODE phrase and each
record identified by the Relative Record Number instead of Recoed Key.
ACCESS Mode
Modes
Meaning
SEQUENTIAL
RANDOM
DYNAMIC
Notes:
The record of a file stored on a magnetic tape can be accessed in sequential mode only. But the records of file stored
on magnetic disk can be accessed in all the modes.
Value
00
10
30
34
Status
Successful Completion
At end condition
Permanent error
Boundary violation
Notes:
Input-Output operations may not be successful thus resulting in termination of the program.
The data-name specified in the file-status clause contains the status code and can be referred by the programmer.
Depending on the code programmer can take specific actions by transferring the control to error-routine paragraphs.
The data name should be declared in working-storage section with alphanumeric data type of two characters.
I-O-CONTROL Paragraph
Specifies information needed for efficient transmission of data between the external data
set and the COBOL program.
Notes:
The I-O-CONTROL paragraph is optional.
The key word I-O-CONTROL can appear only once, at the beginning of the paragraph. The word
CONTROL must begin in Area A, and must be followed by a separator period.
Each clause within the paragraph can be separated from the next by a separator comma or a separator
semicolon. The order in which I-O-CONTROL paragraph clauses are written is not significant. The I-OCONTROL paragraph ends with a separator method.
I-O-
FILE SECTION
FILE SECTION.
FD File-Name
BLOCK CONTAINS m RECORDS
RECORD CONTAINS n CHRACTERS
LABEL RECORDS ARE STANDARD/ OMMITED
01
File-record-structure.
Notes:
Each file used in the program should have an FD entry (File Description) in
FILE SECTION.
Value clause specifies the name of the physical file and the path
File Operations
Cobol Verbs
Meaning
WRITE
REWRITE
READ
DELETE
Notes:
This foil lists the possible operations that can be performed over files.
Before doing any operation, files should be opened and they must be closed before exiting the program
OPEN and CLOSE verbs are provided by COBOL.
OPEN MODES
Mode
Meaning
INPUT
OUTPUT
I-O
EXTEND
Notes:
SYNTAX
OPEN Mode File-name1, File-name2.
CLOSE File-name1, File-name2
While opening the file the mode must be specified depending on the operation to perform.
More than one file can be opened and closed. Further, files can be opened and closed more than once in a program.
When the READ statement is executed the file must already be open in INPUT
or I-O mode
The AT END clause must be before the NOT AT END
Format 1: sequential retrieval
>>____READ__file-name-1___ _________________ __ __________ ___________________>
|_ NEXT __________| |_RECORD__|
|_
(1)|
|_ PREVIOUS______|
>_____ _______________________ ______________________________________________>
|____ INTO___identifier-1____|
>_____ ___________________________________ __________________________________>
|_ ____ __END_imperative statement-1_|
|_ AT _|
>_____ ____________________________________________ ____ __________ _______><
|_ NOT___ ______ ___END_imperative-statement-2_|
|_END-READ_|
Notes:
For sequential access, the READ statement makes the next logical record from a file available to the object program.
For random access, the READ statement makes a specified record from a direct-access file available to the object
program.
When the READ statement is executed, the associated file must be open in INPUT or I-O mode.
NEXT RECORD Reads the next record in the logical sequence of records. NEXT is optional when ACCESS MODE
IS SEQUENTIAL;
PREVIOUS RECORD Reads the previous record in the logical sequence of records.
When the AT END condition occurs during sequential processing, the READ statement
execution is unsuccessful. The contents of the record area are undefined
Indexed Files
Execution of a Format 2 READ statement causes the value of the key of reference to be compared
with the value of the
corresponding key data item in the file records, until the first record having
an equal value is found. The file position
indicator is positioned to this record, which is then made
available. If no record can be so identified, an INVALID KEY condition exists, and READ
statement execution is unsuccessful.
If the KEY phrase is not specified, the prime RECORD KEY becomes the key of reference for this request. When dynamic access is
specified, the prime RECORD KEY is also used as the key
of reference for subsequent executions of sequential READ statements,
until a different key of
reference is established.
Relative Files
Execution of a Format 2 READ statement sets the file position indicator pointer to the record
contained in the RELATIVE KEY data item, and makes that record available.
The KEY phrase must not be specified for relative files.
For dynamic access, either sequential or random access possible, depending upon
the format of the Read statement
The NEXT phrase must be specified for sequential access with dynamic mode.
In order to READ NEXT, position must have been established in the file by a
successful OPEN, START or READ statement
START Statement
Format :
>>___START___file-name-1___________________________________________________________>
>__ _____________________________________________________________________ ________>
|_KEY___ ______ ____ __EQUAL___ ___ ________________ _data-name-1____|
|__TO _|
|
|_ TO_|
|
|_ = ______________________________|
|_LESS__ _______ ________________|
|
|_THAN_|
|
|_ < ______________________________|
|_GREATER__ ____
_____________|
|
|_THAN_|
|
|_> _______________________________|
|_NOT LESS___ _______ ___________|
|
|_THAN _|
|
|_NOT < ___________________________|
|_NOT GREATER__ _______ ________|
|
|_THAN_|
|
|_NOT > ___________________________|
|_LESS_ ____ _ OR EQUAL_ __ _____|
|
|THAN|
|_TO_|
|
|_ < = _____________________________|
|_GREATER__ ____ _OR EQUAL_ __ _|
|
|_THAN_|
\ TO|
|_>+_______________________________|
>__ _______________________________________ _____________________________________>
|_INVALID___ _____ _imperative-statement-1_|
|_KEY_|
>__ _______________________________________ ___________ ____________ _____________>
|_NOT INVALID___ _____ imperative-statement-1_|
|_END-START_|
|_KEY_|
Notes: The START statement provides a means of positioning within an indexed or relative file for
subsequent sequential record retrieval.
When the START statement is executed, the associated indexed or relative file must be open
in either INPUT or I-O mode.
file-name-1
Must name a file with sequential or dynamic access. File-name-1 must be defined in an
FD entry in the Data Division, and must not name a sort file.
END-START Phrase
This explicit scope terminator delimits the scope of the START statement. END-START converts a
conditional START statement to an imperative statement so that it can be nested in another
conditional statement. END-START can also be used with an imperative START statement.
WRITE Statement
The WRITE statement releases a logical record for an output or input/output file.
WRITE.FROM
PROCEDURE DIVISION.
WRITE File-rec FROM Identifier.
File-rec is record-name declared in FILE-SECTION.
Identifier is a working-storage section variable
The length of the identifier should be equal to the length of the record.
Notes:
To Create a file, program can accept the data from the terminal into file record and write it.
If the data need to be processed, it can be accepted in a W-S identifier. After processing the data the above
WRITE..FROM statement can be issued.
Each WRITE statement writes one record at a time.
READ.INTO
PROCEDURE DIVISION.
READ FILE-name (INTO W-S-Rec) | (AT END Statement)
File name is defined in SELECT clause.
W-S-Rec is working-Storage section identifier.
INTO clause moves the file record to W-S-rec.
AT END clause if used, indicates the next action after the last record is read.
OPEN INPUT Mode
Notes:
READ statement on sequential files reads one record at a time and makes it available to program.
Reading begins from first record and if the READ statement is put in a loop
That is executing the statement repeatedly, then it is possible to read consecutive records.
Loop can be terminated before AT END condition is reached if required so by the program.
If the file is left open next time when the read statement executes, reading continuous from where it was stopped
before the termination of loop.
Notes:
It is often required to change the existing data and the process is called UPDATING.
COBOL provides REWRITES verb to modify an existing record.
For example, changing the address field of an employee requires reading of employee number. Every record to
be updated needs to be read first. To search the record of an employee, whose employee number is known, the
process is as follows
Store the employee number in a variable
Open the file
Read first record
Compare the variable with Emp-No field of the file
If it matches update his address by REWRITE
Else read next record his address by REWRITE
When new records to be added to file open the file in EXTEND mode
EXTEND mode causes the pointer to move to the end of the file.
CLOSE Statement
Format :
CLOSE File-name-1, [File-name-2 .]
CLOSE Statement Releases the Resourcces which are assigned to that file.
Cannot Close the file which is not opened.
After performing the operations on the file (I,e no longer used in a program) needs to be closed but
not necessary.
If the FILE STATUS clause is specified in the FILE-CONTROL entry, the associated status key is
updated when the CLOSE statement is executed.
If the file is in an open status and the execution of a CLOSE statement is unsuccessful, the
EXCEPTION/ERROR procedure (if specified) for this file is executed.
Sequential Files
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL
SELECT file-name ASSIGN TO DEVICE-NAME
ORGANIZATION IS SEQUENTIAL.
ACCESS MODE IS SEQUENTIAL.
FILE STATUS IS data-name.
Area
B
Notes:
All the files used in the program should have an entry in FILE CONTROL paragraph.
For each file used, there should be one SELECT..ASSIGN clause.
The file-name is select clause is user defined word and can be used throughout the program wherever required.
ASSIGN clause specifies the device on which file stored.
Indexed Files
Index component consists of a index structure with a record key values and addresses of corresponding
records.
RECORD KEY is one or more fields of the records.
Suitable record key is to be chosen by the programmer depending on the functionality of the fields.
E.g :
Employee-code, Job-number.
ALTERNATE RECORD KEY can also be chosen.
E.g :
Employee-name, Job-name.
Indexed files facilitate faster accessing of records compared to that of sequential files.
Notes:
When an indexed file is created
An index component is also created containing some index tables based on record keys.
data component is created containing the actual records.
Record keys identify every record in the file.
The process of accessing a record involves searching for the record key with matching index value. Then locate the
record from the corresponding address.
This is done by the system itself.
INVALID KEY
(READ | WRITE | REWRITE | DELETE) File-name
(INVALID KEY Statement)
(AT END Statement).
Records and indexes of an indexed file are stored in key sequence order to facilitate faster access.
Invalid key clause checks whether any input-output operation is violating the
Uniqueness of primary keys
E.g. add a record with duplicate value.
Sequence of the records.
E.g. add a record with key value out of range.
Proper read
E.g. try to read a non-exist record
Reading of a record in indexed files required the key value to be provided by the program
Notes:
When READ NEXT statement is to be executed each time the records are read consecutively.
IF the access mode is RANDOM a record is read from corresponding key value.
In a situation demanding the access of more than one consecutive records from the middle of the file then
dynamic access is used.
The START verb places the read pointer to the record whose key value is compared with an identifier. Record is
accessed randomly.
READNEXT can be put into loop for sequential reading.
For the Rewrite/ Delete operations the records must be read at first .
Relative Files
FILE CONTROL
SELECT file-name ASSIGN TO Disk
ORGANIZATION IS RELATIVE
RELATIVE KEY data-name-1
RRN indicates the offset of a record from the first record of the file.
Notes:
In relative file Relative Record Number identifies the records of the file. Select clause should specify RELATIVE
KEY.
Value of data-name-1 indicates RRN.
Usage of READ/WRITE/ REWRITE/ DELETE statements, ACCESS modes, OPEN modes and START verb, are
exactly similar to that for sequential files.
Open modes
File Organization
Sequential
A
C
C
E
S
S
M
O
D
E
S
E
Q
U
E
N
TI
A
L
R
A
N
D
O
M
D
Y
N
A
M
IC
OPERATI
ONS
READ
WRITE
REWRITE
START
Relative
I
O
X
I-O
Indexed
E
X
X
O
X
X
X
X
X
X
X
X
X
X
X
X
X
X
REWRITE
X
X
X
X
X
X
X
X
X
X
X
I-O
X
START
DELETE
START
DELETE
X
X
X
WRITE
REWRITE
READ
WRITE
DELETE
READ
I-O
X
X
X
X
X
Unit 5
TABLE HANDLING
Multidimensional table
Table is a list of logically similar items.
Notes:
Obviously declaring 100 data items in W-S section and sorting them becomes
practically impossible.
Tables or Arrays provide the solution to handle situations discussed above.
If volume of data to be processed is large and if they are not stored in files,
then tables are used.
OCCURS Clause
Specifies number of occurrences or elements of the table.
WORKING-STORAGE SECTION
01 Marks.
02 Mark Table1
OCCURS 10 TIMES PIC 9(2).
Valid
02 Mark Table2
02 Mark Table3
Notes:
OCCURS clause causes setting up of area for holding the table elements.
Following rules must be followed with the usage of OCCURS clause.
1. The Integer must be positive.
2. Clause cannot be specified for an item whose level is 01, 66, 77, 88.
3. Value clause should not be specified with occurs clause.
4. OCCURS clause can be specified for file-section entries for both group
items as well as elementary items.
Valid
Subscript
Indicates the position of an element in the table.
PROCEDURE DIVISION
Marks Table (Subscript)
Parentheses required
Notes:
Subscript can be a COBOL variable or a literal. Value of subscript must not exceed the range of
no. of occurrences specified by OCCURS clause.
If OCCURS clause is specified for a group items subscript should be specified for all elementary
items of that group.
Subscript should be specified for only data items defined with OCCURS clause, whenever used in
procedure division.
INDEXING
An index-name is an identifier that becomes associated with a particular table. The value in an
index is the displacement from the beginning of the table based upon the length of the
table
element.
Notes:
Indexing allows such operations as table searching and manipulating specific items.
To use indexing you associate one or more index-names with an item whose data
description entry contains an OCCURS clause. An index associated with an index-name
acts as a subscript, and its value corresponds to an occurrence number for the item to
which the index-name is associated.
The INDEXED BY phrase, by which the index-name is identified and associated
with its table, is an optional part of the OCCURS clause. There is no separate
entry to describe the index associated with index-name. At run time, the contents of the
index corresponds to an occurrence number for that specific dimension of the table
with which the index is associated.
XYZ(1)
If it requires storing the Marks of N subject for M students then we require two
OCCURS clauses.
Notes:
Two dimension tables are used most frequently in applications. Consider for examples, 10 Students of a class
appeared for 8 subjects in their annual exams and you need to code a program to store and retrieve the data.
Data includes names of all the students, marks and names of corresponding subjects.
To store the marks of n subjects of one student, one dimension table serves the purpose. If number of students
is more than one than for each student there OCCURS n subjects and marks. Next foil shows the W-S
declarations for this example.
Multidimensional Table
Each OCCURS clause adds a dimension in nested occurs.
Ex:
01
Multidimensional.
02
First-dim
OCCURS 10 TIMES
02
Second-dim
OCCURS 5 TIMES.
05Second
PIC
05Third-dim OCCURS 10 TIMES
10Third
PIC
Notes:
COBOL supports multidimensional tables up to 7 levels .
PIC
A.
5.
X.
Table-Sorting
SET Verb
SET verb initializes and / or changes the value of index.
E.g. :
SET K To 1
K is initialized to 1
SET K UP BY 2
SET K DOWN BY 2
Decrements by step of 2
This means an index indicates the position of an element in the table similar to subscript, but internally it is processed
a different manner, but more efficient
SEARCH Verb
Searches for a particular value in the table, which has an index.
SEARCH Table name AT END statement
WHEN condition statement
Ex : SET K TO 1
SEARCH table-name AT END DISPLAY not found.
WHEN field-1 = element (K) DISPLAY element (K).
Notes:
In the above example, field-1 contains the required value to be searched for in the table,
More than one condition can be checked, with more than one WHEN clause.
All valid arithmetic operators can be used.
This form of search statement is called serial search.
Binary Search
Searches the table previously sorted, by splitting the table.
Faster than serial search
Only one WHEN clause is allowed.
SEARCH ALL Table-Name
.
WHEN.
other clauses
remain same.
Notes:
Before applying SEARCH ALL clause the table must be sorted.
SEARCH ALL causes the table to split into two halves. Then it determines which half of the table contains
the required value by comparing it to the last element of the first half and first element of the second half.
Again the selected half-table splits and continues and so on until the value is located .
PROCEDURE DIVISION.
100-MAIN-PARA.
PERFORM 200-FILL-PARA VARYING CT FROM 1 BY 1.
UNTIL CT>5.
PERFORM 300-DISP-PARA VARYING CT FROM 1 BY 1.
UNTIL CT>5.
PERFORM 400-MNTH-PARA.
STOP RUN.
200-FILL-PARA.
COMPUTE RATE ( CT ) = CT*100.
300-DISP-PARA.
DISPLAY RATE ( CT ).
400-MNTH-PARA.
DISPLAY Month as a number ?
ACCEPT CT.
IF CT< 1 OR > 12 DISPLAY Error in number
ELSE DISPLAY MONTH ( CT ).
PROCEDURE DIVISION.
MAIN PARA.
DISPLAY Months Name please.
ACCEPT M-NAME.
SET CT TO 1.
SEARCH MONTH AT END DISPLAY Not Found.
WHEN M-NAME = MONTH ( CT ).
DISPLAY FIRST-THREE ( CT ).
STOP RUN.
AVERAGE-TEMP
PIC S999.
PROCEDURE DIVISION.
100-MAIN-PARA.
PERFORM 200-DATA-ACCP-RTN UNTIL NO-MORE-DATA.
PERFORM 300-DATA-DISP-RTN.
STOP RUN.
200-DATA-ACCP-RTN.
DISPLAY Day of the Week : 1-Sunday.7-Saturday :
ACCEPT DAY-OF-THE-WEEK.
DISPLAY Time of the Day during Data Collection :
ACCEPT TIME-OF-THE- WEEK.
DISPLAY Temperature
ACCEPT DEGREE-TEMP (DAY-OF-THE-WEEK, TIME-OF-THE-DAY).
DISPLAY Anymore (Y/N):
ACCEPT MORE-DATA.
300-DATA-DISP-RTN.
PERFORM VARYING
DAY-COUNT FROM 1 BY 1
UNTIL DAY-COUNT > 7.
PERFORM VARYING
DAY-COUNT FROM 1 BY 1
UNTIL HOUR-COUNT > 24.
DISPLAY DAY : , DAY-COUNT, HOUR: ,
HOUR-COUNT, TEMP : ,
DEGREE-TEMP ( DAY-COUNT, HOUR-COUNT )
ADD DEGREE-TEMP ( DAY-COUNT, HOUR-COUNT )
TO TOT-TEMP.
COMPUTE AVERAGE-TEMP = TOT-TEMP / 168.
DISPLAY Weeks Average Temperature Is : ,
AVERAGE-TEMP.
200-ACC-PARA.
DISPLAY ENTER FACULTY NAME.
ACCEPT FAC (F1, D1, Y1).
DISPLAY ENTER DEPARTMENT NAME:.
ACCEPT DEPT (F1, D1, Y1).
DISPLAY ENTER YEAR.
ACCEPT YY (F1, D1, Y1).
IF Y1 = 5
IF D1 = 6
IF F1 = 3
MOVE N TO ANYMORE
ELSE
SET F1 UP BY 1
END-IF
ELSE
SET D1 UP BY 1
END-IF
ELSE
SET Y1 UP BY 1.
DISPLAY ANYMORE.
ACCEPT ANYMORE
UNIT 6
Library Services
COPY Statement
The COPY statement is a library statement that places prewritten text in
a COBOL program
Each COPY must be terminated by a period
If library-name is omitted, then SYSLIB is assumed
Format:
>>____COPY____ _____text-name___ _____ _____________________________________>
|_
literal __|
|_ _OF _ ____ library-name_ ___|
|_IN_| |_ literal 2_______|
>____ ____________ _____ _________________________________________ ___ ______><
|_SUPPRESS__|
|
<______________________________ _|
|__REPLACING_______operand-1___BY__operand-2___|_|
Notes:
SUPRRESS means that the imbedded text will not be printed in the source program listing
COPY requires the LIB compiler option to be in effect
The COPY statement is a library statement that places prewritten text in a COBOL program.
Prewritten source program entries can be included in a source program at compile time. Thus, an installation
can use standard file descriptions, record descriptions, or procedures without recording them. These entries
and procedures can then be saved in user-created libraries; they can then be included in the source program
by means of the COPY statement.
Compilation of the source program containing COPY statements is logically equivalent to processing
all COPY statements before processing the resulting source program.
The effect of processing a COPY statement is that the library text associated with text-name is copied into
the source program, logically replacing the entire COPY statement, beginning with the word COPY and
ending with the period, inclusive. When the REPLACING phrase is not specified, the library text is copied
unchanged
Each COPY statement must be preceded by a space and ended with a separator period.
Debugging lines are permitted within library text and pseudo-text.
Comment lines or blank lines can occur in library text. Comment lines or blank lines appearing in library text
are copied into the resultant source program unchanged with the following exception: a command line or blank
line in library text is not copied if that comment line or blank line appears within the sequence of text
words that match operand-1
A COPY statement can appear in the source program anywhere a character string or a separator can appear;
however, a COPY statement must not be specified within a COPY statement. The resulting copied text
must not contain a COPY statement.
Nested COPY
COPY FILEA.
FILEA contains:
01 FILEA.
05 NAME PIC X(40).
COPY ADDRESS.
05 DATA PIC X(100).
Compile produces:
01 FILEA.
05
NAME
05 STREET
05
CITY
05
STATE
05
ZIP
05
DATA
PIC X(40).
PIC X(40).
PIC X(20).
PIC X(02).
PIC X(09).
PIC X(100).
ADDRESS contains:
05 STREET PIC X(40).
05 CITY
PIC X(20).
05 STATE PIC X(02).
05 ZIP
PIC X(09).
Notes:
COBOL allows nested COPY statements.
Nested COPY statements cannot contain the REPLACING phrase.
A COPY statement can appear in the source program anywhere a character string or a separator can appear.
As an IBM extension, COPY statements can be nested. However, nested COPY statements cannot
contain the REPLACING phrase, and a COPY statement with the REPLACING phrase cannot contain
nested COPY statements.
A COPY statement cannot cause recursion. That is, a COPY member can be named only once
in a set of nested COPY statements until the end-of-file for that COPY member is reached.
COPY REPLACING
To change some, or all, of the names in the library (COPYed) text, the programmer
can use the REPLACING option.
The text in the library is unchanged.
COPY PAYLIB REPLACING
FLDA BY PAY-RECORD
FLDA BY HRLY-RATE
FLDA BY HRS-WORKD.
LIBRARY TEXT
01 FLDA.
02 FLDB PIC 999V99.
02 FLDC PIC 999V99.
SOURCE PROGRAM
01 PAY-RECORD.
02 HRLY-RATE PIC 999V99.
02 HRS-WORKD PIC 999V99.
In the discussion that follows, each operand can consist of one of the following:
Pseudo-text
An identifier
A literal
A COBOL word
Function identifier
COPY Pseudo-Text
To change only part of the data-name(s) in the library text, the programmer can
use the REPLACING option with the standard pseudo-text delimiters (==)
COPY PAYLIB REPLACING
= = : PFFX: = =
BY = = PAY = =.
LIBRAR TEXT
SOURCE PROGRAM
01 :PFFX:.
02 :PFFX:-RTE
PIC 999V99.
02 :PFFX: - HRS
PIC 999V99.
01 PAY.
02 PAY-RTE
PIC 999V99.
02 PAY-HRS
PIC 999V99.
Notes :
Pseudo-text A sequence of character-strings and/or separators bounded by, but not including, pseudo-text-1
delimiters (= =). Both characters of each pseudo-text-1 delimiter must appear on one line; however,
character-strings within pseudo-text-1 can be continued.
Any individual character-string within pseudo-text-1 can be up to 322 characters long.
Pseudo-text-1 cannot be null, nor can it consist solely of the space character, separator comma, separator
semicolon, and/or of comment lines. Beginning and ending blanks are not included in the text
comparison process. Embedded blanks are used in the text comparison process to indicate multiple text words.
Pseudo-text must not contain the word COPY.
REPLACE Pseudo-test
Replace can be applied to the entire program, including text introduced through
COPY members
REPLACE statements are processed by the compiler after any COPY statements
are processed
UNIT 7
CHARACTER HANDLING
STRING
STRING
DELIMITED BY
DELIMITED BY
INTO id 7
Notes:
Delimited by clause specifies how the fields are concatenated, Its usage is described in
following foils.
With pointer option if used gives the total no. of characters in the concatenated field (id-7)
If the length of id-7 is not enough to hold the transferred characters, the statement after on
overflow option is executed.
One STRING statement can be written instead of a series of MOVE statements.
The following rules should be followed when this verb is used.
(i). This statement is used to concatenate one or more strings into one by placing them
side by side.
(ii). Sending strings may be alphanumeric literals, figurative constants or identifiers
with usage DISPLAY.
(iii). The receiving string, i.e., identifier- 7 must also be with usage DISPLAY.
STRING example :
DATA DIVISION.
WORKING-STORAGE SECTION.
77 ID-1 PIC X(7) VALUE 'CON,CON'.
77 ID-2 PIC X(7) VALUE 'CAT,CAT'.
77 ID-3 PIC X(6) VALUE 'ENATED'.
77 ID-4 PIC X(12).
77 COUNTER PIC 9(3) VALUE ZEROS.
PROCEDURE DIVISION.
STRING ID-1, ID-2, ID-3
DELIMITED BY ',' INTO ID-4
RESULT
Content if id-4: CONCATENATED.
X(30).
X(10)
X (10)
X (10)
VALUE SPACES.
VALUE SPACES.
VALUE SPACES.
PROCEDURE DIVISION.
100-MAIN-PARA.
MOVE RAJA TO FIRST-NAME.
MOVE ROMOHAN TO MIDDLE-NAME.
MOVE ROY TO LAST-NAME.
STRING FIRST-NAME,MIDDLE-NAME,LAST-NAME DELIMITTED BY
SPACE INTO FULL-NAME.
UNSTRING Statement
The UNSTRING statement is used to split a single data item into several data items
Format:
>>__UNSTRING___identifier-1__________________________________________________________>
>__ _____________________________________________________________________________ ___>
|_DELIMITED___ _____ ___ _____ ___ __identifier-2__ ____ __________________________|
|_BY_|
|_ALL_| |_literal-1______|
| <_____________________ |
|__OR_ ___ __ identifier-3_ _| |
|_ALL_| |_literal-2__|
>___INTO____________________________________________________________________________>
>____identifier-4__ _____________________________ ____ ___________________________ __| __>
|_DELIMITER__ ___ identifier-5 _|
|_COUNT__ ____ identifier-6___|
|_IN_|
|_IN__|
>___ ___________________________ ____ _______________________________ ______________>
|_ ____ _POINTER__identifier-7_|
|_TALLYING___ ____ __identifier-8_|
|_WITH_|
|_IN_|
>__ _____________________________________________ _________________________________>
|_ _____ ___OVERFLOW__imperative-statement-1___|
|_WITH_|
>___ __________________________________________________ ___ _________________ _______>
|_ NOT__ _____ __OVERFLOW__imperative-statement_2_|
|_END-UNSTRING_|
|_ON_|
Notes:
The UNSTRING statement causes contiguous data in a sending field to be separated and placed into multiple
receiving fields.
One UNSTRING statement can take the place of a series of MOVE statements, except that evaluation or
calculation of certain elements is performed only once, at the beginning of the execution of the UNSTRING
statement.
When the TALLYING phrase is specified, the field-count field contains a value equal to the initial value,
plus the number of data receiving areas acted upon.
X(30).
X(10)
X (10)
X (10)
VALUE SPACES.
VALUE SPACES.
VALUE SPACES.
PROCEDURE DIVISION.
100-MAIN-PARA.
MOVE RAJA ROMOHAN ROY TO FULL-NAME.
UNSTRING FULL-NAME DELIMITTED BY SPACE INTO FIRST-NAME,
MIDDLE-NAME,LAST-NAME.
EXAMINE Statement
ALL
LEADING
UNTIL FIRST
ALL
LEADING
UNTIL FIRST
ALL
LEADING
UNTIL FIRST
REPLACING BY Literal - 5
Literal - 1
Literal - 2 BY Literal - 3
Literal - 4
Notes:
This verb is used to scan a string to find the number of occurrences of a given character in it.
In addition, the Verb can also be use to replace some or all occurrences of the said character
by another character.
Eg :
Let us consider the following DATA DIVISION entry
77 A PIC X(5) VALUE IS PPRIP.
Now the statement
EXAMINE A TALLYING ALL P.
Will store 3 in the TALLY register as there are altogether three Ps in the string.
However the statement
EXAMINE A TALLYING LEADING P
Will store 2 in the TALLY , Since there are only Two leading Ps.
The statement
EXAMINE A TALLYING UNTIL FIRST I.
Will store 3 in the TALLY as there are only Three characters before the character I.
It may be noted here that if a particular character is not found, TALLY is set to
Zero, When the ALL or LEADING phrase is used. For e.g.. In the statement
EXAMINE---REPLACING.
Will store 3 in the TALLY register and will change the content of A to QQRIQ.
EXAMINE A REPLACING FIRST I BY M
Format:
>>___INSPECT___identifier-1______TALLYING____________________________________________________>
<___________________________________________________________________________________
<_______________________________________________________
|
>____identifier-2___FOR____ __CHARACTERS____ ____________ _| _____________________ __ | __|_____>
|
|_|phrase 1 |__|
|
|
< _____________________________________ |
|
<_______________________ | |
|__ __ALL _________ ___ __identifier-3___ __ ___________ _| _| _|
|_LEADING______|
|_literal________|
|_ | phrase 1 _|
>_____REPLACING____________________________________________________________________________>
<_______________________________________________________________________________
>_______ __CHARACTER BY____ _identifier-5__ ______ _______________ __|__________________ __|____>
|
|_literal-3____|
|__| phrase
|_|
|
|
<_______________________________________________________
|
|
<________________ | |
|__ ALL_____ ______ ___identifier-3___ ___BY__ _identifier-5__ ____ ______________| _| _|
|_LEADING_|
|_literal-1________|
|_literal-3____|
|_| phrase 1 |__|
phrase 1:
|__ __BEFORE__ __ _____________ __ _identifier-4__________________________________________________|
|_AFTER___|
|_INITIAL_____| |_literal-2__|
Notes:
Eg:
PROCEDURE DIVISION.
INSPECT HELLO TALLYING TALLY-COUNT FOR ALL A
Let the picture of HELLO be X(20) and suppose its content before the execution of the
above statement is as follows :
APARNAbKUMARIbAMMAbb
If picture of TALLY-COUNT is 9(2) and originally contains 08, then after the execution
of the statement, TALLY-COUNT will contain 14, as there are a total of 6 As in HELLO.
REPLACING Phrase
-identifier-3 or literal-1
Is the subject field (the item whose occurrences are replaced).
Identifier-3 can be:
When the substitution field is a figurative constant, the substitution field replaces each
non-overlapping occurrence of the subject field in the inspected item.
When the subject and substitution fields are character-strings, the character-string specified
in the substitution field replaces each non-overlapping occurrence of the subject field in the
inspected item
UNIT 8
SORT / MERGE
SORT/MERGE
SORT Statement
MERGE Statement
SORT PROCEDURES
RELEASE/RETURN Statements
SORT Statement
The SORT statement accepts records, sorts them according to specified keys, and makes the
sorted results available for further processing.
Format 1:
SORT file-name-1 ON ASCENDING/DESCENDING KEY data-name-1 USING file-name-2
GIVING file-name-3.
Format 2:
SORT file-name-1 ON ASCENDING/DESCENDING KEY data-name-1 INPUT PROCEDURE IS
Procedure-name-1[THRU Procedure-name-2] USING file-name-2 GIVING file-name-3.
Format 3:
SORT file-name-1 ON ASCENDING/DESCENDING KEY data-name-1 INPUT PROCEDURE IS
Procedure-name-1[THRU Procedure-name-2] USING file-name-2
OUTPUT PROCEDURE IS Procedure-name-3[THRU Procedure-name-4]
GIVING file-name-3.
Notes:
The SORT Statement accepts records from one or more files. Sorts them according to the specified key(s),
and makes the sorted records available either through an OUTPUT PROCEDURE or in an output file.
The SORT Statement can appear any where in the procedure division except in the declarative portion.
File-name-1
The name given in the SD entry that describes the records to be sorted.
No pair of file-names in a SORT statement can be specified in the same SAME SORT AREA , or Same
SORT-MERGE AREA clause. File-names associated with the giving clause (file-name-3)
cannot be specified in the SAME AREA clause.
File-names associated with the giving clause (file-name-3) can be specified in the SAME AREA clause.
ASCENDING / DESCENDING KEY phrase
This Phrase specifies that records be to be processed in ascending or descending sequence
(depending on the phrase specified), based on the specified sort keys.
When the GIVING phrase is specified , all the sorted records I the file-name-1 are automatically transferred
to the output files ( file-name-3).
MERGE Statement
The MERGE statement combines two or more identically sequenced files(that is, files that have already
been sorted according to an identical set of ascending/descending keys) on one or more keys and makes
records available in merged order to an output procedure or output file.
Format:
>>___MERGE__file-name-1____ _____ ___ __ASCENDING__ ___ _______ __data-name-1__| __|_>
>___ _____________________________________________________ __USING__file-name-2_______>
|__ ________________ __SEQUENCE__ ____ _alphabet-name-1_|
|_COLLATING____|
|_IS_|
<__________________
>_____file-name-3__|___________________________________________________________________>
>___ __OUTPUT PROCEDURE___ ___ __procedure-name-1__ __________________________ _ _><
|_
|_IS_|
|_ _ THROUGH_ procedure-name-2_| _|
|
|_THRU____|
|
|
<________________
|
|_ GIVING___file-name-4__| _________________________________________________________|
Notes:
The MERGE statement combines two or more identically sequenced files(that is, files that have already
been sorted according to an identical set of ascending/descending keys) on one or more keys and makes
records available in merged order to an output procedure or output file.
A MERGE statement can appear anywhere in the Procedure Division except in a Declarative Section.
The file names given must be in the SD entry.
When the MERGE statement is executed, all records contained in file-name-2, file-name-3,., are
accepted by the merge program and then merged according to the key(s) specified.
SORT PROCEDURES
In an input procedure the RELEASE statement is used to place a record into the
file to be sorted
Notes:
RELEASE Statement
The RELEASE statement is only used within the INPUT PROCEDURE of a SORT
The RELEASE statement makes the contents of record-name-1 available to the initial phase of
the SORT process
Upon completion of the INPUT PROCEDURE, the sort file consists of all records placed
there by the RELEASE statement
Format:
____RELEASE____record-name-1____ _____________________________ ____________________><
|_FROM___identifier-1___________|
RETURN Statement
Format:
>>___RETURN___file-name-1___ ______________ ____ _____________________________ _______>
|_ RECORD __|
|_INTO___identifier-1___________|
>___ _____ ____END___imperative-statement-1____________________________________________>
|_ AT _|
>___ _____________________________________________________ ___ ______________ _____>
|_NOT____ _____ __END______imperative-statement-2______|
|_ END-RETURN_|
|_AT__|
Notes:
The RETURN statement transfers records from the final phase of a sorting or merging operation to an
OUTPUT PROCEDURE.
The RETURN statement can be used only within the range of an OUTPUT PROCEDURE associated with a
SORT or MERGE statement.
EXAMPLE : SORT
IDENTIFICATION DIVISION.
PROGRAM-ID. SORTING.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT IN-FILE ASSIGN TO DD1
ORGANIZATION IS SEQUENTIAL.
SELECT WORK-FILE ASSIGN TO DD2
SELECT OUT-FILE ASSIGN TO DD3
ORGANIZATION IS SEQUENTIAL.
DATA DIVISION.
FILE SECTION.
FD IN-FILE.
01 IN-REC.
02 NUMPICX(2).
02 NAMEPICX(10).
02 ADDR PICX(10).
02 FILLERPICX(58).
SD WORK-FILE.
01 WORK-REC.
02 WNUMPICX(2).
02 WNAMEPICX(10).
02 WADDR PICX(10).
02 FILLERPICX(58).
FD OUT-FILE.
01 OUT-REC PICX(80).
WORKING-STORAGE SECTION.
PROCEDURRE DIVISION.
SORT WORK-FILE ON ASCENDING KEY WNUM USING IN-FILE GIVING OUT-FILE.
STOP RUN.
UNIT 9
CALL Statement
CALL Statement
The CALL statement transfers control from one object program to another within the run unit
CALL identifier-1
name-1 [, data-name-2]
Literal-1
[ ; ON OVERFLOW imperative-statement ]
Notes:
The CALL statement transfers control from one object program to another within the run unit.
The program containing the CALL statement is the calling program; the program identified in the CALL
statement is the called subprogram. Called programs can contain CALL statements; however, a called program
must not execute a CALL statement that directly or indirectly calls the calling program unless it has the
RECURSIVE attribute.
CALL BY CONTENT/REFERENCE
The CALL.BY REFERENCE technique allows the sub-program to access and process the
data- items in the callers storage.
The CALL.BY CONTENT technique allows the sub-program to access and process a copy of the
items from the callers storage. The sub-program cannot change the original data values in the
callers
storage.
A single CALL statement may have both data passing techniques.
data-
WORKING-STORAGE SECTION.
01 RECORD-A.
05 FIELD1 PIC
05 FILLER
.
PROCEDURE DIVISION.
.
CALL xxxxxxxx USING BY REFERENCE RECORD-A
BY CONTENT LENGTH OF RECORD-A
Notes:
BY REFERENCE Phrase
If the BY REFERENCE phrase is either specified or implied for a parameter, the corresponding data item in the
calling program occupies the same storage area as the data item in the called program.
BY CONTENT Phrase
If the BY CONTENT phrase is specified or implied for a parameter, the called program cannot change the
value of this parameter as referenced in the CALL statements USING phrase, though the called program
can change the value of the data item referenced by the corresponding data-name in the called programs
Procedure Division header. Changes to the parameter in the called program do not affect the
corresponding argument in the called program.
BY VALUE Phrase
The BY VALUE phrase applies to all arguments that follow until overridden by another BY REFERENCE
or BY CONTENT phrase.
If the BY VALUE phrase is specified or implied for an argument, the value of the argument is passed, not
a reference to the sending data item. The called program can modify the formal parameter corresponding
to the BY VALUE argument, but any such changes do not affect the argument since the called program
has access to a temporary copy of the sending data item.
These options are Compiler dependent.
LINKAGE SECTION
The LINKAGE SECTION of the DATA DIVISION describes data made available
from another program
The VALUE clause may not be specified (except for level-88 items)
Notes:
The Linkage Section describes data made available from another program or method. The Linkage Section may be
composed of two entry types:
Record-description-entry
Data-item-description-entry
GLOBAL DATA
The GLOBAL clause specifies that a data-name is available to every program contained
within the program that declares it, as long as the contained program does not itself have a
declaration for that name. All data-names subordinate to or condition-names or indexes
associated with a global name are global names.
The GLOBAL clause can be specified in the Working-Storage Section, the File Section,
the Linkage section, and the Local-Storage Section, but only in data description entries
whose level-number is 01 or FD.
An item may have both GLOBAL and EXTERNAL clauses.
GLOBAL only applies to Nested Programs.
Notes
GLOBAL in FILE SECTION.
The GLOBAL clause specifies that the file connecter named by a file-name is a global name. A global file-name is availabl
to the program that declares it and to every program that is contained directly or indirectly in that program.
A file name is global if the GLOBAL clause is specified in the file description entry for that file-name. A record name is
global if the GLOBAL clause is specified in the record description entry by which the record-name is declared or, in the
cause of record descreiption entries in the File Section, if the GLOBAL clause is specified in the file description entry for th
file-name associated with the record description entry
A data-name is global if the GLOBAL clause is specified either in the data description entry by which the
data-name is declared or in another entry to which that data description entry is subordinate.
A statement in a program contained directly or indirectly within a program which describes a global name
reference that name without describing it again.
Two programs in a run unit can reference common data in the following circumstances:
1.
The data content of an external data record can be referenced from any program provided that
program has described that data record.
2.
If a program is contained within another program, both programs can refer to data possessing the
global attribute either in the containing program or in any program that directly or
indirectly contains the containing program.
Sample Program
ID DIVISION.
PROGRAM-ID. MPGM.
..
DATA DIVISION.
WORKING-STORAGE SECTION.
01 MNTEC PIC X(32) GLOBAL.
PROCEDURE DIVISION.
MOVE BEGINNING CONTENTS TO MNTEC
CALL SUBPGM
DISPLAY MNTEC.
STOP RUN.
IDENTIFICATION DIVISION.
PROGRAM-ID. SUBPGM.
DATA DIVISION.
WORKING-STORAGE SECTION.
PROCEDURE DIVISION.
DISPLAY ENTERING SUBPROGRAM.
DISPLAY MNTEC.
MOVE ENDING CONTENTS TO MNTEC.
DISPLAY LEAVING SUBPGM.
EXIT PROGRAM.
END PROGRAM SUBPGM.
END PROGRAM MPGM.
UNIT 10
COMPILATION
LINK-EDITING
Compilation
Link-editing
Load module execution
SOURCE
PROGRAM
COMPILATION
OBJECT
MODULE
MESSAGES AND
LISTING
LINK
EDITING
LOAD
MODULE
LOAD
MODULE
EXECUTION
OUTPUT
MESSAGES AND
LISTINGS
Notes:
The source program is the input to the compilation step. The output from the compilation step is
called an object module.
The object module is the input to the link-edit step. The output of the link-edit step is the load module,
which must be saved as a member of a partitioned dataset.
The load module created from the source program is executed in execution step.
COMPILATION PROCESS
A specific computer has a specific set of instruction that is fixed during the design
of the machine. This set of instructions constitutes what is commonly called
he machine language.
A program written in language other than the machine language is called a source
program. Whether it is a high-level language program or an assembly-language
program, the program cannot be executed directly.
The source language program should be translated to a machine language
program known as the object program.
If the source is a high level language, the corresponding translator program
is called a compiler.
Compiler is used to translate COBOL program into language that the computer
can process i.e. object code.
GENERAL COMPILER
//
//
The following statements show general JCL for a compilation job step.
//JOBNAME JOB ,,
CLASS=A,MSGCLASS=H,MSGLEVEL=(1,1),
NOTIFY=&SYSUID
JCL KEYWORDS
STEP1 - The name of the job step. The exec statements specify that the COBOL
compiler (IGYCRCTL) is to be invoked.
STEPLIB - Definition of the data set where the COBOL compiler resides.
SYSLIN Definition of the data set that receives output.
CONTROL ON COMPILATION
The compiler lists errors in COBOL program statements and provides information to
help you debug program. You can direct and control compilation with the following:
Compiler-directing statements
Compiler options
COMPILER-DIRECTING STATEMENTS
COMPILER OPTIONS
Compiler options help to control the compilation of program. Specify these options
in the PARM field of the JCL or on the process statement in program before
IDENTIFICATION DIVISION.
Syntax:
//STEP1 EXEC PGM=IGYCRCTL, PARM=SSRANGE,LIB,DYNAM,LIST
A] Diagnostic options
SSRANGE: SSRANGE is use to generate code that checks if subscripts or indexes
attempt to reference an area outside the region of the table. Variable-length items also
checked to confirm that their current length is within their maximum defined length.
Default is NOSSRANGE.
DUMP: Default is NODUMP. The dump option is use to produce a system dump at compile time.
FLAG: Default is FLAG (I). The syntax is FLAG (x, y), where x and y can be I, W, E, S, U.
To produce diagnostic messages for errors o a severity level x or above at the
end of the source listing using FLAG (x).
TEST: Default is NOTEST. Test is use to produce object code that can be executed
with batch or interactive debug.
ADV: Default is ADV. ADV is meaningful only if you use WRITEADVANCING in source code. With ADV in effect,
the compiler adds 1 byte to the record length to account for the printer control character. Use NOADV if you have
already adjusted record length to include 1 byte for the printer control character.
AWO: Default is NOAWO. With AWO specified, the apply WRITE-ONLY clause will be in effect if any file within the
program is physical sequential with blocked V-mode records. The clause will be in effect even if it was not specified
within the program.
FASTSRT: FASTSRT allows IBM DFSORT or its equivalent, to perform the input and output instead COBOL. Default
is NOFASTSRT.
NUMPROC: Default is NUMPROC (NOPFD). Use NUMPROC(NOPFD) if you want the compiler perform invalid
sign processing. NUMPROC (PFD) is a performance option that can be used to bypass invalid sign processing.
OPTIMIZE: Default is NOOPTIMIZE. Use OPTIMIZE to reduce the run time of object program.
OUTDD: Default is OUTDD (SYSOUT). Use OUTDD if you want to run-time display output on the data set other than
SYSOUT.
TRUNC: Default is TRUNC (STD). TRUNC (STD) to control the way arithmetic fields are truncated during MOVE
and arithmetic operation.
ZWB: Default is ZWB. With ZWB, the compiler removes the sign from a sign external decimal field when comparing
this field to an alphanumeric elementary field during execution.
G] OTHER OPTIONS:
EXIT: DEFAULT is NOEXIT. If you specify the EXIT option without providing a least
one sub option, NOEXIT will be in effect. The sub options can be specified
in any order, separated by either commas or spaces
Mwssage code
IGYppxxxx-L
Message text
Text of Message
nnnnnn The number of the source statement of the last line the compiler was processing.
IGY The Prefix that identifies this message as coming from COBOL compiler.
pp - Two characters that identify which phase of the compiler discover the error.
xxxx A 4-digit number that identifies the error message.
L A character that indicates the severity level of the error I, W,E,S or U
LINK-EDITING
Creating a Load Module
Large program may be developed in parts so that the program is in the form of a number
of routines. Each of these routines is separately translated. The object routines or object
module must then be combined together to form a load module or run unit, which is finally executed.
The step that accomplishes the job of linking the object routines or load modules into one
load module is called linkage editor.
The linkage editor converts an object module into a load module, and stores it in a partitioned
data set.
Linkage editor
//STEP2 EXEC PGM=HEWL
//SYSLIB DD DSNAME=CEE.SCEELKED,DISP=SHR
//SYSPRINT DD SYSOUT=*
//SYSLIN DD DSNAME=MTPLB00.COBOL.OBJLIB,DISP=(OLD,DELETE)
//SYSLMOD DD DSNAME=MTPLB00.COBOL.LOADLIB(PGM1),
//
DISP=(MOD,PASS),
//
SPACE=(TRK,(10,10,1))
SYSLMOD and SYSPRINT are the data sets used for linkage editor output.
LINK-EDIT OPTIONS
Syntax:
//STEP2 EXEC PGM=HEWL, PARM=CALL,PRINT,AMODE
Figure: Link-edit Options
Notes:
CALL: Use CALL if your program calls external routines, in which case you want external references to
be resolved by automatic library call.
PRINT: When you use the print option, link-edit messages and the module map are written on the data set
defined by the SYSLOUT DD statement.
AMODE: AMODE use to override the default RMODE attribute established by the compiler.
RENT: RENT option is use to have the linkage editor mark the load module as being reentrant and reusable.
REUS: REUS option is use to have the linkage editor mark the load module as being reusable.
UNIT 10
Intrinsic Functions
Intrinsic functions allow you to access certain values that are derived at run time
Examples
Current-date
Length
Lower-case
Date-of-integer
Notes:
Intrinsic functions are coded in statements in the procedure division. The function is evaluated and the
value participates in the statement execution. Functions may not stand alone they must be coded as part of
another statement.
Notice that the word FUNCTION is now a reserved word in COBOL. But the names of the functions are
not reserved.
Numeric and integer functions may only be used where arithmetic expressions may be used
The length of the result depends on the function and the length of the argument(s)
COBOL
Integer date
An integer in the range 1 to 3,067,671
Represents the number of days since December 31, 1600
For example, January 1, 1994 is 143908 as an integer date
Julian date
A seven digit integer of the form YYYYDD
DDD is between 1 and 366, must be valid for the year(that is, leap year are
taken into account)
Representing
A Gregorian date(YYYYMMDD)
Current time in hours (24-hour clock), minutes, seconds, and hundredths of a
second(HHmmsshh)
Difference of local time zone from Greenwich Mean Time as a + or - followed by
the hours and minutes difference (Shhmm)
Notes:
Notes:
Integer-of-day converts a Julian date to an integer date
Function integer-of-day(argument)
The argument must be a valid Julian date(YYYYDDD)
The function reference is an integer date
Notes:
Day-of-integer converts a Integer date to an Julian date
Function integer-of-day(argument)
The argument must be a valid integer date
The function reference is an integer representing YYYYDDD
date
Notes:
For example, the ranges are 00-18 and 19-99, so given a year of 82, assign a century
of 19; given a year of 17, assign a century of 20.
Syntax
Examples
VALUE EXAMPLES:
RUN-TIME
YEAR
1998
INPUT VALUE
SW Argument
FUNCTION VALUE
890315
-10
18890315
1998
770122
-10
19770122
1998
890315
-1
19890315
1998
770122
-1
19770122
1998
890315
19890315
1998
770122
19770122
1998
890315
85
19890315
1998
770315
85
20770315
1998
890315
-120
1998
890315
120
Syntax
Examples
VALUE EXAMPLES:
RUN-TIME
YEAR
1998
INPUT VALUE
SW Argument
FUNCTION VALUE
89315
-10
1889315
1998
77122
-10
1977122
1998
89315
-1
1989315
1998
77122
-1
1977122
1998
89315
1989315
1998
77122
1977122
1998
89315
85
1989315
1998
77315
85
2077315
1998
89315
-120
1998
890315
120
Syntax
Examples:
VALUE EXAMPLES:
RUN-TIME
INPUT VALUE
YEAR
1998
89
SW Argument
FUNCTION VALUE
-10
1889
1998
77
-10
1977
1998
89
-1
1989
1998
77
-1
1977
1998
89
1989
1998
77
1977
1998
89
85
1989
1998
77
85
2077
1998
89
-120
1998
89
120
COMPUTE NEW-DUE-DATE =
FUNCTION DATE-OF-INTEGER
(FUNCTION INTEGER-OF-DATE(DATE-OF-ORDER) + 30)
After Converting a Gregorian due to an integer date, and adding 30 days to the integer date, the
newly calculated Gregorian date is displayed
CHAR(n) returns the character that is the n the character in coding sequence
ORD(char) returns the position that character belongs in the collating sequence
* Used where coding scheme, ASCII or EBCDIC are not know until compile time.
Value returned
ACOS
ASIN
ATAN
COS
LOG
LOG10
SIN
TAN
Value returned
FACTORIAL
INTEGER
INTEGER-PART
MAX
Largest value in a list of values; all items in the list are of the
same type, one of: alphabetic, integer, numeric, or
alphanumeric
MEAN
MEDIAN
MIDRANGE
MIN
Value returned
MOD
ORD-MAX
ORD-MIN
RANDOM
RANGE
REM
SQRT
SUM
Value returned
NUMVAL
NUMVAL-C
Value returned
ANUITY
PRESENTVALUE
STANDARDDEVIATION
VARIANCE
* If a multidimensional table, ALL may be used in place of one or more of the subscripts