VS COBOL II
VS COBOL II Training Programme
Duration
5 Days Theory + 5 Hands-on
Pre-requisite
TSO/ISPF Concepts
Session Topics
History and Basics of COBOL
File Concepts
Identification Division
Environment Division
Session Topics ...
Data Division
Data types, PICTURE clause and Editing
File Section
Working Storage & Linkage
Procedure Division
Input / Output
Arithmetic
Session Topics ...
Procedure Division
Table Handling
Control flow
Non-numeric Data Handling
Sub-program linkage
Sort and Merge
Compiler Directive
Compiler Options
History and Basics of COBOL
History of COBOL
Conceived in 1959
Prelim. Ver. in DEC 1959
First Standard COBOL in 1961
ANSI Approved Versions in 1968, 1974
Latest COBOL Version in 1985
COBOL II / COBOL 85
About COBOL
Programming Language
Oriented towards Business applications
Not Suited for Scientific Problem Solving
High Level Language
Problem Oriented
Machine Independent
Easy to Learn/Read/Write/Maintain
About COBOL
English Like
Common to most Computers
Self Documenting
Program Composition
Program
Contains Four
Division
Contains Many
Section
Contains Many
Paragraph
Is Either
Descriptive Or Imperative
Contd..
Program Composition
Descriptive Imperative
Contain Many
Entry Sentence
Contain Many
Clause Statement
Contain Many
Word Word
Contd..
Program Composition
Word
Is Is
User Defined Or Reserved
• Keywords
• As Per Rules
• Connectives
• Special Registers
• Figurative Constants
• Optional Words
Character Set
0, 1 .. 9 Digits
A, B.. Z Letters
b Space
+-,.*/( Special
)=$;“‘ Symbols
<>
Rules for User Defined Words(Datanames)
Max. Length 30 Chars
Must contain only Digits, Letters and Hyphens
Must not be a Reserved Word
Include at least one Letter
Hyphens are imbedded
Must not have Spaces
Examples of User Defined Words
SALES-TOTAL
INSURANCE-PREMIUM
A5-2134B
1X1
l-FILE-OPEN-FLAG
NO-MORE-RECORDS-FLAG
Examples of Reserved Words
RECORD CONTAINS 100 TO 300
CHARACTERS DEPENDING ON file-len
Keywords : RECORD, DEPENDING
Optional Words : CONTAINS, CHARACTERS ON
User defined Words : file-len
Examples of FIGURATIVE CONSTANTS
One or more
ZERO, ZEROES,
zerosZEROS
QUOTE,
One or more
QUOTES
“
SPACE,
One or more
SPACES
blanks
HIGH-VALUE,
Highest Value in Collating Sequence
HIGH-VALUES
Lowest Value in Collating Sequence
LOW-VALUE,
One or more string characters
LOW-VALUES
Indicate POINTER item do not contain a valid
ADDRESS
ALL
NULL, NULLS
Literals
Are Constants
Can be Numeric or Non-Numeric
Examples:
Numeric NON-Numeric
123.345 “COBOL PRG”
9999 “MY NAME”
-100.95
0.54E-78
Rules for Numeric Literals
Contains minimum 1 digit and can have maximum 18
digits
Sign, if used, must be left-most character and must not
be more than one
Decimal, if used, may not be right-most character and
must not be more than one
Rules for Non-Numeric Literals
Any character in the Character Set allowed
Must be enclosed in Quotes
2 continuous Quotes to get 1 Quote
Numeric Literal in Quotes is Non-Numeric
Maximum Length is 160 Characters
COBOL Coding Form
1 6 7 8 11 12 72 73 80
Columns
1 to 6 : Sequence Number
7 :*/- (Indicator Area)
8 to 11 : Area A (Margin A 8th)
12 to 72 : Area B (Margin B 12th)
73 to 80 : Identification Field
Overview
4 DIVISIONS
IDENTIFICATION
ENVIRONMENT
DATA
PROCEDURE
SECTIONS / PARAGRAPHS
Fixed for first 3 Divisions
Various Specifications have fixed positions and
indentations
Coding Rules
Division, Section and Paragraphs in Area A
Division names and Section names must be coded on
separate lines
All other entries may have several statement combined
on a single line (Using space can?)
Continuation
Any sentence, entry, clause, or phrase that requires
more than one line can be continued in Area B of the
next line which is not a
comment line
blank line
i.e, Area A of a continuation line must be blank
(no need of ‘–’)
Continuation ...
If no hyphen (-) in indicator Area
last character of the preceding line is assumed to be
followed by a space
If hyphen in Indicator Area
first non-blank character of this continuation line
immediately follows the last non-blank char of continues
line
Ex: Muralikrishna
- vaspari =>Muralikrishnavaspari
Continuation ...
If the continued line contains a non-numeric literal
without a closing quotation mark:
all spaces at the end of the continued line (through column
72) are part of the literal
Continuation line must contain a hyphen in the indicator
area
First non-blank character must be a quotation mark and
Literal continues with the character following the quotation
mark
Identification Division
Session 2
About Identification Division
Is the header for a program
It documents the name of the program, author, the date
it was written etc.
Syntax for Identification Division
{IDENTIFICATION DIVISION
ID }
PROGRAM-ID. pgmname
[IS [COMMON] [INITIAL] PROGRAM] .
[AUTHOR. comment.]
[INSTALLATION. comment.]
[DATE-WRITTEN. comment.]
[DATE-COMPILED. comment.]
[SECURITY. comment.]
Identification Division
Common Clause
Program is contained within another program
Can be called from siblings of the common program
and programs contained within them
This clause can be used only if the program named by
pgm1 is contained within another program.(means
common sub program for 2 main programs??)
Identification Division
Initial Clause
When PROGRAM pgm1 is called, it is placed in
initial state (Also contained programs (in it)).
When in INITIAL state
Working storage vars are initialized using VALUE
CLAUSE values, if any
All files not in open state
Control mechanism for PERFORM & GOTO in initial
state
GLOBAL/EXTERNAL/COMMON are specified to use
variables in other programs.
Recommended Guidelines for Identification
Division
No abbreviation of IDENTIFICATION
It must have :
PROGRAM-ID, AUTHOR, DATE-WRITTEN, DATE-
COMPILED
It must have a Comment Block explaining the function
of the program
It must have a Maintenance Log Block (for future use)
Sample Identification Division
1 6 7 8 11 12 73 80
72
IDENTIFICATION DIVISION.
PROGRAM-ID. PRG001.
AUTHOR. DBSS.
DATE-WRITTEN. 01/01/95.
DATE-COMPILED.
* THIS PROGRAM DOES NOTHING
*
* PROGRAM MAINTENANCE LOG
* S.NO DATE AUTHOR PATCH-REF
* ------- ------- ------------- -----------------
*
Environment Division
Session 4
About Environment Division
Describes
Computer Used
Peripheral Devices
Contains 2 Sections
CONFIGURATION
INPUT-OUTPUT
CONFIGURATION SECTION
Specify source/object computers
Relate environment-names to user-defined mnemonic
Specify collating sequence
Specify currency sign substitution
CONFIGURATION SECTION
Swap role of comma & period
Relate alphabet-names to character sets or collating
sequences
Specify symbolic-characters
Relate class names to sets of characters.
CONFIGURATION SECTION
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
[SOURCE-COMPUTER. source m/c.]
[OBJECT-COMPUTER. target m/c
Contd..
Example Altering Collating Sequence
Default collating sequence is EBCDIC on the IBM.
Supposing we want ASCII.
CONFIGURATION SECTION.
SOURCE COMPUTER. IBM 3090.
OBJECT COMPUTER. VAX-6410.
COLLATING SEQUENCE IS ASCII-order.
SPECIAL-NAMES. ??
ASCII-order IS STANDARD-1.
Input-Output Section
Contains information regarding files to be used in the
program
Consists of two paragraphs
FILE-CONTROL, I-O-CONTROL
FILE-CONTROL paragraph..**
Names each file
Identifies file medium
Allows H/W assignments
FILE CONTROL SELECT
Association to external dataset name (thru ddname)
File Organisation
Sequential, Indexed, Relative
Access Mode
Sequential, Random, Dynamic
Organisation Specific
Like Keys
File Status
Recommended Guidelines for Environment
Division
CONFIGURATION SECTION must have
SOURCE-COMPUTER
OBJECT-COMPUTER
In INPUT-OUTPUT SECTION
Each SELECT starts at Col. 12
Blank line before SELECT
Each clause of SELECT on a separate line
Each clause starts at Col. 16
Sample Environment Division
CONFIGURATION SECTION.
SOURCE COMPUTER. IBM 3090.
OBJECT COMPUTER. IBM 3090.
*
INPUT-OUTPUT SECTION.
*
FILE-CONTROL.
SELECT input-file
ASSIGN TO inpfile
ACCESS IS SEQUENTIAL (or ACCESS MODE)
FILE STATUS IS inpfile-status .
Data Division
About Data Division
Describes the Variables and File Layouts used
Has three Sections
FILE SECTION
WORKING-STORAGE SECTION
LINKAGE SECTION
Has Level Structure
Data Type established using Picture Clause
Levels
Mimic the hierarchy in the Logical Record
The lowest subdivision is an Elementary Item
Elementary items can be combined into group items
Elementary Items may form part of one or more
Groups
Level Numbers 01 to 49, 66, 77, 88.
Example
01 ASSOC-REC.
05 ASSOC-NO
05 ASSOC-NAME.
10 FIRST-NAME
10 LAST-NAME
05 ASSOC-ADDRESS.
10 ADDR-LINE-1
10 ADDR-LINE-2
10 ADDR-LINE-3
10 TELEPHONE-NO
Data Types
Elementary Data Items :
Alphanumeric
Alphabetic
Numeric (Zoned, Packed(Comp-3), Binary) i.e, for all 9( )
Numeric Edited
Alphanumeric Edited
Group Data Items are Alphanumeric?? and their size is
the sum of the sizes of its Elementary Data Items
PICTURE Clause
{ PICTURE IS pic-string1
PIC }
Specified for every Elementary Item
pic can contain a max of 30 Code Characters
A,X,9,V,S,B, /, 0 , $ , “,” , ”.” , * etc..30
can be in lower case
Code Character repetitions can be indicated by an
integer within ( )
Code Characters
Code Meaning Sample
Char Picture
9 Numeric Data Item 9999
X Any allowable character XXXX
from the character set
A a Letter or Space AAAA
V Assumed Decimal Point 99V99
P Position of assumed Decimal 99PPVPPP99
Point when it lies outside
S Data Item is Signed S9(4)
Code Characters (Contd)
Code Meaning Sample PIC
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
* Replace leading zeros ****9.99
$ Inserts Currency sign $9,999.99
+-CRD Inserts Sign +99.99 -99.99
99.99DB 99.99CR
PICTURE String - Rules
Code characters can be in lower case
Codes usable once or more
A B P X Z 9 0 / , + - * $
Codes usable just once
S V . CR DB
PICTURE String - Rules for data categories
Alphabetic item
Only A allowed
PICTURE String - Rules for data categories
Numeric Items
9 P SV
PICTURE Valid Range of Values
9999 0 through 9999
S99 -99 through +99
S999V9 -999.9 through +999.9
PPP999 0 through .000999 =>before 3 positions.
S999PPP -1000 through -999000
+1000 through +999000 & ZERO
Contd..
PICTURE String - Rules for data categories
Numeric-edited items
B P V Z 9 0 / , . + - CR DB * $
At least one edit char or BLANK WHEN ZERO clause
PICTURE String - Rules for data categories
Alphanumeric items
The symbol X or
Combinations of the symbols A, X, and 9.
Alphanumeric-edited items
A X 9 B 0 /
Must contain at least one A or X, and at least one B or 0
or /.
PICTURE Clause Editing
Insertion
Simple insertion
Special insertion
Fixed insertion
Floating insertion.
PICTURE Clause Editing
Suppression & Replacement
Zero suppression and replacement with asterisks or spaces
EDITING ALLOWED ONLY for Categories:
Numeric-edited (All edits)
Alphanumeric-edited (Only Simple insertion)
Editing(Modifying the Value assigned) allowed for N&X
types
PICTURE Clause Editing
Simple insertion
B0/
, 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
PICTURE Clause Editing
Special Insertion Editing
Period (.) is the special insertion symbol; it also represents
the actual decimal point for alignment purposes
PICTURE Value of Data Edited Results
999.99 1.234 001.23
999.99 12.34 012.34
999.99 123.45 123.45
999.99 1234.5 234.50
PICTURE Clause Editing
Fixed Insertion Editing
$ (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
PICTURE Clause Editing
Fixed Insertion Editing (Contd..)
PICTURE Value of Data Edited Result
$9999.99CR +123.45 $0123.45
$9999.99DB -123.45 $0123.45DB
$9999.99DB +123.45 $0123.45
$9999.99CR -123.45 $0123.45CR
PICTURE Clause Editing
Floating Insertion
$ + -
Mutually exclusive
PICTURE Value of Data 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
PICTURE Clause Editing
Zero Suppression and Replacement
Z * (Mutually exclusive)
as floating replacement Z * + - $ are mutually exclusive
PICTURE Value of Data Result
****.** 0000.00 ****.**
ZZZZ.ZZ 0000.00 bbbbbbb
ZZZZ.99 0000.00 bbbb.00
ZZ99.99 0000.00 bb00.00
Z,ZZZ.ZZ+ +123.456 bb123.45+
PICTURE Clause Editing
Zero Suppression and Replacement (Contd.)
PICTURE Value of Data Result
*,***.**+ -123.45 **123.45-
**,***,***.**+ +12345678.9 12,345,678.90+
$ZZ,ZZZ.ZZCR +1234.56 $b1,234.56bb
$B*,***,***.**BBDB -12345.67 $***12,345.67bbDB
Input - Output Verbs
Are for processing datasets
Displaying information to and Capturing information
from the user
ACCEPT
ACCEPT identifier1 [ FROM
{ mnemonic-name
environment-name
DATE
DAY??
DAY-OF-WEEK=>1/2/3..7
TIME } ]
ACCEPT ...
Mnemonic-Name is as specified in SPECIAL-
NAMES
Environment-Name can be SYSIN, SYSIPT,
CONSOLE
ACCEPT ...
DATE - YYMMDD(reverse) - 9(6)
DAY-OF-WEEK - 9(1)
1 TO 7 (Monday to Sunday)
DAY - YYDDD (Julian day) - 9(5)
TIME - HHMMSShs - 9(8)
In general DATE=>10bytes,Time=>8bytes
Time stamp=>26bytes(10+8+6n+2spaces)
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?.
RECFM can be Fixed or Variable
Records are read until identifier is filled or EOF
reached
DISPLAY
DISPLAY { identifier1
literal1 } ...
[ UPON { mnemonic-name1
environment-name1}]
[ WITH NO ADVANCING ]
DISPLAY ...
When the UPON is omitted, SYSOUT is the default
device
Mnemonic-name is as specified in SPECIAL-NAMES
Environment-name can be SYSOUT, SYSLIST,
SYSLST, SYSPCH, SYSPUNCH, CONSOLE ..
DISPLAY - Example
COBOL statement
DISPLAY ‘Return code:’ i-ret-code
DISPLAY ‘Return code:’ i-ret-code
ex:- UPON SYSLIST
JCL statement:
//SYLIST DD applicable parameters
Instead of..
//SYOUT DD applicable parameters
Default LRECL for SYSOUT is 121 and RECFM is
FBA
Records will be folded if length > LRECL – 1(120?).
DISPLAY - Rules
Identifier-1 is converted automatically to external
format, if required
Negative signed values cause a low-order sign
overpunch
POINTERs are converted to an external PIC 9(10)
INDEX names can’t be specified
SECTIONs & PARAs
SECTION is recognised by keyword SECTION
Example
MAIN-PROCESS SECTION
PARAGRAPHs consist of SENTENCEs
Paragraph is Identified by Para Name
Example
9999-READ-FILE.
Rules for SECTION/PARA Names
Must not have more than 30 characters
Can contain (0-9) DIGITs, (A-Z) LETTERs &
Hyphens (-) only
Hyphen should be embedded
SENTENCEs & STATEMENTs
SENTENCE is composed of one or more
STATEMENTs.
STATEMENT is a syntactically valid combination of
words and symbols beginning with a verb
STATEMENT can be
Conditional
Imperative
Compiler Directing
Arithmetic Verbs
Arithmetic Verbs
Operations : ADD, DIVIDE ...
Operands : Numeric
5 statements
ADD SUBTRACT
MULTIPLY DIVIDE
COMPUTE
Each has many formats with slight variations
ARITHMETIC OPERATORS
BINARY : + - * / **
UNARY : + -
Precedence
Unary
Exponentiation
Multiplication and Division
Addition and Subtraction
ARITHMETIC OPERATORS
ROUNDED Phrase
Adds one to low order digit whenever absolute value of the
next least significant digit is(LSB) >= 5.
SIZE Error
Occurs if absolute value exceeds the largest value that can
be contained in the associated identifier.
Example
Result = 12345.6789
Result Picture 9(5)V99
Result Stored 12345.67
Truncation on Right Size Error is Off
Result Stored with Rounded Option 123456.68
Result Picture 9(4)V9(2)
Value Stored 2345.67
Truncation on both Sides
Size Error is On
CORRESPONDING Phrase
A pair of subordinate items from the identifiers of
CORR phrase correspond if :
Both have same name and qualifiers
Atleast one is an elementary item in case of MOVE
Both are elementary Numeric items for ADD/SUBTRACT
Levels are not 77,66, 88
Usage Is not Index clause
CORRESPONDING Phrase ...
Not FILLER items
Both do not include a REDEFINES, RENAMES, OCCURS
CORRESPONDING will not effect on
66,77,88,USAGE,INDEX, REDEFINES, RENAMES,
OCCURS& FILLER items.???
Corresponding Example
05 ITEM-1 OCCURS 6 INDEXED BY X.
10 ITEM-A PIC S9(3). CORR FOR ADD
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 CORR FOR MOVE
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.
ADD
Two or more numeric operands are summed up and
stored
Rules
Elementary Numeric Items
Literals should be Numeric
Decimal Point Alignment
Internal Format Transformation in case of
mixed usage clause
ADD
Format 1
ADD { id-1
lit-1 } ...
TO ( id-m [ ROUNDED ] ) ...
[ ON SIZE ERROR imper-stmt1 ]
[ NOT ON SIZE ERROR
imper-stmt2 ]
[ END-ADD ]
ADD
Format 2
ADD { id-1 TO { id-3
lit-1 } ... lit-3 }
GIVING ( id-m [ ROUNDED ] ) ...
[ ON SIZE ERROR imper-stmt1 ]
[ NOT ON SIZE ERROR
imper-stmt2 ]
[ END-ADD ]
ADD
Format 3
ADD { CORRESPONDING
CORR }
grp-1 TO grp-2 [ ROUNDED ]
[ ON SIZE ERROR imper-stmt1 ]
[ NOT ON SIZE ERROR
imper-stmt2 ]
[ END-ADD ]—Optional..
ADD - Examples
ADD A TO B
ADD 1 TO B
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
Add CORR X to Y (Example)
01 X.
05 X-1 PIC 9(3) VALUE 1.
05 X-2 PIC 9(3) VALUE 2.
05 X-3 PIC 9(3) VALUE 3.
01 Y.
05 X-1 PIC 9(5) VALUE 5.
05 X-2 PIC 9(5) VALUE 9.
05 X-3 PIC 9(5) VALUE 12.
After Add, Under group Y:
X-1 = 6; X-2 = 11; X-3 = 15
SUBTRACT
To subtract one or the sum of two or more numeric
items from one or more items and set the values of one
or more items to the result
Valid only for Numeric Items
Automatic Decimal Alignment
SUBTRACT
SUBTRACT { id-1
lit-1 } ...
FROM ( id-m [ ROUNDED ] ) ...
[ ON SIZE ERROR imper-stmt1 ]
[ NOT ON SIZE ERROR
imper-stmt2 ]
[ END-SUBTRACT ]
SUBTRACT
SUBTRACT { id-1
lit-1 } ...
FROM { id-2
lit-2 }
GIVING ( id-m [ ROUNDED ] ) ...
[ ON SIZE ERROR imper-stmt1 ]
[ NOT ON SIZE ERROR imper-stmt2 ]
[ END-SUBTRACT ]
SUBTRACT
SUBTRACT { CORRESPONDING
CORR }
grp-1 FROM grp-2 [ ROUNDED ]
[ ON SIZE ERROR imper-stmt1 ]
[ NOT ON SIZE ERROR imper-stmt2
[ END-SUBTRACT ]
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 C ROUNDED
SUBTRACT A FROM B
ON SIZE ERROR MOVE 1 TO ERROR-FLAG
MULTIPLY
MULTIPLY { id-1
lit-1 }
BY ( id-2 [ ROUNDED ] ) ...
[ ON SIZE ERROR imper-stmt1 ]
[ NOT ON SIZE ERROR imperative-stmt2 ]
[ END-MULTIPLY ]
MULTIPLY
MULTIPLY { id-1 BY id-2
lit-1 }
GIVING id-3 ( [ ROUNDED ] ) ...wts the result.
[ ON SIZE ERROR imper-stmt1 ]
[ NOT ON SIZE ERROR
imperative-stmt2 ]
[ END-MULTIPLY ]
MULTIPLY - Examples
MULTIPLY 5 BY A
MULTIPLY 5 X 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
DIVIDE
DIVIDE { id-1 INTO
lit-1 }
( id-2 [ ROUNDED ] ) ...
[ ON SIZE ERROR imper-stmt1 ]
[ NOT ON SIZE ERROR imperative-stmt2 ]
[ END-DIVIDE ]
DIVIDE
DIVIDE { id-1 {BY { id-2
lit-1 } INTO} lit-2 }
GIVING ( id-3 [ ROUNDED ] ) ...
[ ON SIZE ERROR imper-stmt1 ]
[ NOT ON SIZE ERROR imperative-stmt2 ]
[ END-DIVIDE ]
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
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 GIVING C 6 2 - 6 2 3
DIVIDE A BY 5 GIVING B 8 - - 8 1 2
REMAINDER C
COMPUTE
COMPUTE
More than one operation in a single statement
Shortens Programs
Avoids Intermediate data names
EXPRESSIONS
Made up of Operators, Data Names & Literals
Operators evaluated based on parenthesis and/or precedence
COMPUTE
COMPUTE id-1 [ ROUNDED ]
[ id-2 [ ROUNDED ] ] ...
= arithmetic-expression
[ ON SIZE ERROR imper-stmt1 ]
[ NOT ON SIZE ERROR imperative-stmt2 ]
[ END-COMPUTE ]- Optional??
Examples
PROFIT = PRICE - COST
A =B+C*2
CONDITION NAMES (88-LEVEL)
88 data-name { VALUE IS
VALUES ARE }
( lit-1 [THRU lit-2] ) ...
Used for Condition Checking
Example
01 l-GENDER PIC X. (Only 1byte)
88 C-MALE VALUE ‘M’.
88 C-FEMALE VALUE ‘F’.
88 C-VALID-GENDER VALUE ‘M’ ‘F’.
88 level doesn’t contain PIC clause.
Procedure Division
Control Flow Verbs
RELATION CONDITION
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.
RELATION CONDITION ...
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 <=
RELATION CONDITION
For Numeric operands the comparison is algebraic
Example:
012
12.00
12
+12 are all equal (for operator’=‘)
Comparison permitted regardless of Usage
Non-numeric operands
or one numeric & one non-numeric
Comparison is made as per the collating sequence
if both operands’ Usage are same and relational
operator = or NOT = no conversion
All other comparison operands with Usage other than
display are converted to display
Non-numeric operands
or one numeric & one non-numeric
Comparison starts from left most character
For operands size unequal the comparison proceeds as
if the shorter operand had been padded by blanks on
the right
Non-numeric operands
or one numeric & one non-numeric
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
CLASS CONDITION ...
Syntax
IF id-1 IS [ NOT ]
{NUMERIC
ALPHABETIC
ALPHABETIC-LOWER (to check LC letters)
ALPHABETIC-UPPER
class-name }
SIGN CONDITION
operand-1 IS [ NOT ]
{POSITIVE
NEGATIVE
ZERO }
Determines whether algebraic value is less than or
greater than or equal to zero
operand-1 must be a numeric identifier, or arithmetic
containing at least one reference to a variable
IF
IF condition-1 THEN
{ statement-1 ...
NEXT SENTENCE }
[ ELSE [ statement-2 ...
NEXT SENTENCE ] ]
[ END-IF ]
NEXT SENTENCE means execution should move to
stmt after the next separator period
Never use NEXT SENTENCE and Period as IF
terminator. It is not a good programming practice
CONTINUE
Allows you to specify a no operation statement. It
indicates that no executable instruction is present.
Syntax :
CONTINUE
It can be used anywhere a conditional statement or an
imperative statement can be used. It has no effect on
the execution of the program.
CONTINUE - Example
IF YEAR-IS-NOT-LEAP
CONTINUE
ELSE
ADD 1 TO NO-OF-FEB-DAYS
END-IF
The above IF usage is preferred compared to IF NOT
given below:
IF NOT YEAR-IS-NOT-LEAP
ADD 1 TO NO-OF-FEB-DAYS
END-IF
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.
Syntax : condition-name-1
Conditional expression
Examples
IF EMP-AGE > 15
SET CHILD TO TRUE
END-IF
IF EMP-SAL IS POSITIVE
SET DEBIT-AMOUNT TO TRUE
END-IF
IF EMP-PHONE IS NUMERIC
SET CELULER-PHONE TO TRUE
END-IF
IF ASSOC-FEMALE
MOVE 18000 TO std-deduction
END-IF
COMPLEX CONDITIONS
Formed by
Combining simple conditions
Nested IFs
Logical Connectives
Logical Operators
Used to combine simple conditions
Abbreviating conditions
For negation
LOGICAL OPERATORS
NOT
Logical Negation
OR
Logical Inclusive
AND
Logical Conjunction
EVALUATION RULES
Precedence
Arithmetic Expression
All Relational Operators
NOT
AND
OR
If a condition is put in parenthesis, it is evaluated and
its truth value depends on the truth value of its
constituents
Abbreviated compound conditions
IF A = B AND A = C is same as
IF A = B AND = C
Here identical subjects are omitted in a consecutive
sequence of relational conditions
IF A = B AND A = C is same as
IF A = B AND C
Here identical subjects and relational operators are
omitted in a consecutive sequence of relational
conditions
Abbreviated compound conditions
As indicated in the examples compound conditions can
be abbreviated by having implied subjects, or, implied
subjects and relational operators.
Examples
A > B OR NOT C OR D
= (A>B) OR NOT (A>C) OR (A>D)
A > B OR NOT > C OR D
= (A>B) OR (A NOT > C) OR (A NOT> D)
GO TO
Transfers control from one part of the Procedure
Division to another .
Unconditional GO TO
GO TO procedure-name
Gives control to the first statement in the paragraph or
section named in procedure-name
GO TO - Conditional
GO TO procedure-name-1 ...
DEPENDING ON id-1
Id-1 must be numeric item
Transfer control to procedure names listed based on
the value of id-1:
if 1 go to procedure-name-1
if 2 go to procedure-name-2 ...
When value is > than nbr of proc then executes then it
is a no operation (CONTINUE)
EVALUATE
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.
Provides better readability.
When a satisfiable WHEN is met, processing breaks
off from the rest of the evaluate block
EVALUATE
EVALUATE
{ id-1 [ ALSO id-2
literal-1 literal-2
expression-1 expression-2
TRUE TRUE
FALSE } FALSE ] ...
( WHEN phrase 1 [ ALSO phrase-2 ] ...
imperative-statement-1) ...
[ WHEN OTHER imperative-statement-2 ]
[ END-EVALUATE ]
EVALUATE
phrase 1 & 2 :
{ ANY
condition-1
TRUE
FALSE
[NOT] { identifier-3 [ { THROUGH
literal-3 THRU } { identifier-4
arith-exp-1} literal-4
arith-expr-2} ] }
EVALUATE - Example
EVALUATE proc-type ALSO cust-type
WHEN 1 ALSO 1
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
EVALUATE
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
If a WHEN does not have a associated imperative statement it
is a do-nothing condition (same as coding CONTINUE)
PERFORM
Executes group of consecutive statements written
inline (called INLINE PERFORM) or elsewhere
(called OUT-OF-LINE PERFORM) in a program
Has four formats
Departs from normal sequence of execution and
implicit return to next statement after completion
PERFORM (Basic)
PERFORM
{ proc-name1[{ THRU proc-name2
THROUGH } ]
imp-statement-1 END-PERFORM
}
PERFORM (Basic)
Example 1 (Out-of-line)
PERFORM PARA-1 THRU PARA-2
Example 2 (Inline)
PERFORM
MOVE 1 TO FLAG-1
MOVE 2 TO FLAG-2
END-PERFORM
PERFORM - Overlap Rules
When the performed procedures executes another
PERFORM the procedures associated with the 2nd
level PERFORM must be totally included in or totally
excluded from the procedures of the first level
PERFORM statement.
Two or more such active PERFORM must not have a
common exit.
Perform - Overlap Examples
X - Perform A thru M
A-
B - Perform C thru E
C-
E-
M-
Y - Perform P thru S
P-
Q - Perform C thru E
R-
S-
PERFORM (TIMES option)
PERFORM
{ proc-name1 [THRU proc-name2] { id-1 TIMES
int-1}
{ id-1
init-1 } TIMES imp-stmt-1 END-PERFORM
}
PERFORM (TIMES option) - Rules
Once the perform statement is initiated any changes to
the id-1 will have no effect on the nbr of times the para
is to be executed
PERFORM (TIMES)
Example
PERFORM B1-PROCESS
THRU B1-PROCESS-EXIT
10 TIMES
PERFORM I-CNT TIMES
WRITE OUT-REC FROM I-ERR-REC(I-CNT)
SUBTRACT 1 FROM I-CNT
END-PERFORM
PERFORM (UNTIL option)
PERFORM
{ proc-name1[THRU proc-name2] until-phrase
imp-statement-1 until-phrase END-PERFORM
}
until-phrase
UNTIL condition WITH TEST { BEFORE
AFTER } ]
TEST AFTER can be used to have a DO UNTIL
structure. Default is TEST BEFORE.
PERFORM (UNTIL)
Example
PERFORM I-CNT TIMES
WRITE OUT-REC FROM I-ERR-REC(I-CNT)
SUBTRACT 1 FROM I-CNT
END-PERFORM
PERFORM UNTIL I-CNT = ZERO
WRITE OUT-REC FROM I-ERR-REC(I-CNT)
SUBTRACT 1 FROM I-CNT
END-PERFORM
PERFORM (VARYING)
PERFORM
{ proc-name1[THRU proc-name2]
varying-phrase after-phrase
varying-phrase imp-stmt-1 END-PERFORM
}
PERFORM (VARYING) ...
varying-phrase
[ WITH TEST {BEFORE
AFTER } ]
VARYING { id-1 FROM { id-2 lit-1 inx-nm1 }
inx-nm-2}
BY { id-3 UNTIL cond-1 lit-2 }
PERFORM (VARYING) ...
after-phrase
( AFTER { id-4 FROM { id-5 lit-1
inx-nm1 } inx-nm-2}
BY { id-6 UNTIL cond-2
lit-2 } ) ...
After-phrase provides for varying more than one
identifier
PERFORM (VARYING) ...
PERFORM PROC1 THRU PROC2
VARYING ID-2 FROM ID-3
BY ID-4 UNTIL CONDITION-1
AFTER ID-5 FROM ID-6
BY ID-7 UNTIL CONDITION-2
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.
MOVE
MOVE { id-1 TO id-2 ...
lit-1 }
MOVE {CORRESPONDING
CORR} id-1 TO id-2
BLANK WHEN ZERO
BLANK WHEN { ZERO
ZEROS
ZEROES }
A Numeric or Numeric Edited Data Item will contain
spaces when it has a value of zero
Useful for printing
Not allowed on 66 and 88 levels & on POINTER and
INDEX data items
Procedure Division
String manipulation
Session 12
String Manipulation
Move data items - MOVE
Count and replace data items - INSPECT
Join data items - STRING
Split data items - UNSTRING
Initialize variables - INITIALIZE
Manipulate addresses with pointer data items - SET
Data Movement and Sub-string Handling
Group moves
Elementary moves
Move corresponding
Format conversion for numeric data types
Sub-string operation (Move by reference)
MOVE
MOVE { id-1 TO id-2 ...
lit-1 }
MOVE {CORRESPONDING
CORR} id-1 TO id-2
Move - Reference modification
77 name pic x(25).
77 first-name pic x(10).
77 last-name pic x(15).
MOVE name(1:10) TO first-name
MOVE name(11:) TO last-name
Move - Rules
Pointer and Index variables not allowed
In MOVE CORR - ignored
Length, Sub-string, Reference modification evaluation
For source variable only once - before the move to the 1st
target variable
For each target variable before the move
MOVE a(b) TO b, c(b)
Move - Rules ...
Occurs depending on Clause object (ODO) location
When not in same group
ODO object value decides the length
Set value prior to MOVE
When in same group
When no non-subordinate
When there are non-subordinates
Updating ODO object with complex structures
INITIALIZE
Sets selected categories of data fields to predetermined
values.
It is functionally equivalent to one or more MOVE
Can be at
Group level
Elementary level
INITIALIZE
INITIALIZE ( id-1
[REPLACING
{ ALPHABETIC
ALPHANUMERIC DATA NUMERIC
ALPHANUMERIC-EDITED
NUMERIC-EDITED }
BY {id-2
lit-1 }] ) ...
INITIALIZE - Rules
Category of Id-2 should be compatible that of CORR
REPLACING
Same Category can’t be repeated
SPACE is implied source for
Alpha, Alpha-numeric and Alpha-numeric edited
ZERO is implied source for
Numeric and Numeric edited
INITIALIZE - Rules
For Group initialize the following will not participate
Index variables
Pointer variables
Filler
Redefines
Elementary items that are not of category mentioned in
REPLACING
INITIALIZE - Examples
INITIALIZE id-1
id-1 before After
9(5) 12345 00000
X(5) AB123 bbbbb
99XX9 12AB3 bbbbb
XXBX/XX ABbC/DE bbbb/bb
**99.9CR 1234.5CR **00.0
A(5) ABCDE bbbbb
+99.99E+99 +12.34E+02 +00.00E+00
INSPECT
Specifies that characters, or groups of characters in a
data item are to be
Counted (tallied)
Replaced
or both.
CONVERTING is a special form of replacing
INSPECT
Format 1
INSPECT id-1
TALLYING id-2 FOR
{CHARACTERS =>total characters in that
ALL {id-3 lit-1} => =>particular(ex:ALL ‘a’)
LEADING {id-3 lit-1}}
[{BEFORE
AFTER} INITIAL {id-4 lit-2}]
INSPECT
Format 2
INSPECT id-1
REPLACING
{CHARACTERS =>total char in that
ALL {id-2 lit-1} =>particular(ex:ALL ‘a’)
LEADING {id-2 lit-1}}
BY {id-3 lit-2}
[{BEFORE
AFTER} INITIAL {id-4 lit-3}]
INSPECT
Format 3
INSPECT id-1
CONVERTING
{id-2 lit-1}
TO {id-3 lit-2}
[{BEFORE
AFTER} INITIAL {id-4 lit-3}]
INSPECT - Examples
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
INSPECT - Examples
INSPECT data-1 REPLACING CHARACTERS BY
ZEROS
BEFORE INITIAL QUOTE.
DATA-1 COUNTR DATA-1
before After After
ANS”LM 0 000”LM
SACK”T 0 0000”T
INSPECT - Examples
INSPECT data-1 CONVERTING
”abcdefghijklmnopqrstuvwxyz" TO
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
AFTER INITIAL "/" BEFORE INITIAL"?"
Before After
a/five/?six a/FIVE/?six
r/Rexx/RRRr r/REXX/RRRR
zfour?inspe zfour?inspe
STRING
Strings together the partial or complete contents of two
or more data items or literals into one single data item.
One STRING statement can be written instead of a
series of MOVE statements.
Process is called concatenation
STRING
STRING {id-1 lit-1} ...
DELIMITED BY {id-2 lit-2 SIZE}
INTO id-3 [WITH POINTER id-4 ]
[ON OVERFLOW imperative stmt-1]
[NOT ON OVERFLOW
imperative stmt-2]
[END-STRING]
STRING - Example
LAST-NM = ‘EDISON’ FIRST-NM = ‘THOMAS’
MID-NM = ‘ALVA’ l-COUNT =0
MOVE 1 TO l-COUNT
STRING LAST-NM DELIMITED BY ‘ ‘
‘, ‘ DELIMITED BY SIZE
FIRST-NM DELIMITED BY ‘ ‘
‘ ‘ DELIMITED BY SIZE
MID-NM DELIMITED BY ‘ ‘
INTO FULL-NM WITH POINTER l-COUNT
FULL-NM = ‘EDISON, ALVA THOMAS’ l-COUNT= 20
STRING - Rules
Receiving fields must not be
Edited field
With Justified clause
With reference modification
Pointer variable must be
Elementary and Numeric
Large enough to hold max length of receiving field
ON OVERFLOW executed when pointer Value <= 0
or exceeds max length of receiving field
UNSTRING
Causes contiguous data in a sending field to be
separated and placed into multiple receiving fields:
Number of characters placed in each receiving field
Count of the total number of characters transferred
Special action when all the receiving fields are filled before
the end of the sending item
Useful to convert display format data to compact form
UNSTRING
UNSTRING id-1
[DELIMITED BY ALL {id-2 lit-1}
[OR ALL {id-3 lit-2} ...]]
INTO ( id-4
[DELIMITER IN id-5] [ COUNT IN id-6] ) ...
[WITH POINTER IN id-7 ] [TALLYING IN id-8 ]
[ON OVERFLOW imperative stmt-1]
[NOT ON OVERFLOW imperative stmt-2]
[END-UNSTRING]
UNSTRING - Example
FULL-NM = ‘EDISON, THOMAS ALVA ’
UNSTRING
FULL-NM DELIMITED BY ‘,’ OR SPACE
INTO LAST-NM COUNT IN LAST-NM-CNT
FIRST-NM COUNT IN FIRST-NM-CNT
MID-NM COUNT IN MID-NM-CNT
LAST-NM = ‘EDISON’ LAST-NM-CNT = 6
FIRST-NM= ‘THOMAS’ FIRST-NM-CNT = 6
MID-NM = ‘ALVA’ MID-NM-CNT = 4
UNSTRING - Rules
If the DELIMITED BY phrase is not specified, the
number of characters examined is equal to the size of
the current data receiving field.
If the POINTER phrase
Is not specified an implicit value of 1 is assumed
If specified, the source field is examined from the relative
character position specified by the value in the pointer field.
SET - Condition Name
SET cond-name1 ... TO TRUE
The value associated with a cond-name1 is placed in
its conditional variable
If more than one Value is defined for the cond-name1
then the 1st is used
SET - Condition Name
Example
77 I-EOF-FLAG PIC x.
88 C-EOF VALUE ‘Y’.
SET C-EOF TO TRUE
77 I-ACTION-FLAG PIC X.
88 C-ADD VALUE ‘A’ space.
88 C-DEL VALUE ‘D’.
88 C-MOD VALUE ‘M’.
SET C-ADD TO TRUE
(Will get value ‘A’ - first lit in value clause)
SET - Pointer Data
SET { id-1
ADDRESS OF id-2 } ...
TO { ADDRESS OF identifier-3
id-4
NULL
NULLS }
id-1 and id-4 must be POINTERs
id-2 and id-3 must be 01 or 77 levels in LINKAGE
SET - Pointer data Example
77 PTR-FIRST POINTER.
LINKAGE SECTION.
01 SALARY-REC.
05 PTR-NEXT-REC POINTER.
05 NAME PIC X(20).
05 DEPT PIC 9(4).
05 SALARY PIC 9(6).
PROCEDURE DIVISION USING SALARY-REC.
SET PTR-FIRST TO ADDRESS OF SALARY-REC
DISPLAY NAME, DEPT SALARY
IF PTR-NEXT-REC NOT = NULL
SET ADDRESS OF SALARY-REC
TO PTR-NEXT-REC
END-IF
Table handling
Table Handling
Tables eliminate the need for separate entries for
related data
OCCURS clause defines tables of contiguous data
items
Table Handling is by the specification of the
occurrence number
Element position defined by subscripts or indices
ONE DIMENSIONAL TABLE
01 ASSOC-REC
05 ASSOC-NAME PIC X(10).
05 ASSOC-LANGS-KNOWN OCCURS 10 PIC X(30).
MOVE ASSOC-REC TO NEW-REC.
MOVE ASSOC-NAME TO REPORT-NAME.
MOVE ASSOC-LANGS-KNOWN(1)
TO REPORT-LANGUAGE.
TWO DIMENSIONAL TABLE
01 ASSOC-DATA.
05 NAME PIC X(20).
05 PROJECTS OCCURS 2.
10 LANGS-KNOWN OCCURS 2 PIC X(30).
LANGS-KNOWN(1,1) = ‘COBOL’.
LANGS-KNOWN(2,2) = ‘C++’.
SORTED TABLES
02 ASSOC-DATA OCCURS 10 TIMES ASCENDING
KEY IS A-NAME
INDEXED BY INX-1.
05 A-NAME PIC X(20).
05 A-NUM PIC 9(04).
The data have to be sorted in the correct order
(ascending or descending) by the programmer.
SET
SET { id-1
index-name-1 } ...
TO { id-2
index-name-2
int-1 }
SET index-name-1 ...
{ UP BY { id-3
DOWN BY } int-1 }
SET - Examples
05 TABLE-ITEM OCCURS 10
INDEXED BY INX-A PIC X(8).
To set the index INX-A to 5th occurrence of TABLE-
ITEM use stmt:
SET INX-A TO 5
The Value in INX-A would be
(5 - 1) * 8 = 32.
SET - Examples
To refer to 6th element we could use relative indexing
TABLE-ITEM(INX-A+1)
Or Set the index first using
SET INX-A UP BY 1 and then refer as TABLE-
ITEM(INX-A)
Set - Sending and Receiving Fields
Receiving fields Index Index
Integer
Name Data item Data item
Sending fields
Index name V V* V
Index data item V* V* -
Integer data item V - -
Numeric literal V - -
Note : * - No conversion
Complex Tables
Data item with Occurs Depending On is followed by
Non-subordinate item
Non-subordinate item with Occurs Depending On
Data item with Occurs Depending On is nested
Complex Tables ...
01 FILLER.
05 CTR1 PIC S99.
05 CTR2 PIC S99.
05 FIELD-A. 1
10 TABLE-1.
15 REC-1 OCCURS 1 TO 5 DEPENDING ON CTR1 PIC X(3).
10 EMP-NR PIC X(5). 2
10 TABLE-2 OCCURS 5 3
INDEXED BY INDX. 4
15 TABLE-ITEM PIC 99. 5
15 REC-2 OCCURS 1 TO 3
DEPENDING ON CTR2.
20 DATA-NUM PIC S99.
Complex Table ...
Complex ODO item
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
Complex Table ...
Watch out...
The location of non subordinate items following the
item with OCCURS clause is affected by new value of
the ODO object.
If 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.
Complex Table ...
Watch out...
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.
Complex Table ...
Watch out...
To avoid making this error :
Save the value of index as an occurrence number before
changing ODO object.
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
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
SEARCH id-1
[ VARYING { id-2
index-name-1 } ]
[ AT END imperative-statement-1 ]
WHEN condition-1 { imper-stmt2
NEXT SENTENCE }
[ WHEN condition-2 { imper-stmt3
NEXT SENTENCE } ] ...
[ END-SEARCH ]
SEARCH - Sequential ...
WHENs are performed one after another for each table
entry until TRUE or NO more WHEN cond
AT END executed if no match
Set starting point of id-2 or index and SEARCH will
step through id-2 or index also apart from index of the
table being searched.
SEARCH
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’.
SEARCH - ALL
SEARCH ALL id-1
[ AT END imperative-statement-1 ]
WHEN { dataname-1= equal-clause
Condition-name-1}
[ AND { dataname-1= equal-clause
Condition-name-1} ] ...
{ imper-stmt2
NEXT SENTENCE }
[ END-SEARCH ]
SEARCH - ALL ...
Equal-clause can be { id-2
lit-1
arithexp-1}
SEARCH ALL
Initial setting of index ignored, but if set it must not be
greater than the maximum size
Duplicate index will indicate the first entry it
encountered
Unpredictable results if table is not in sorted order
SEARCH ALL
77 NAME PIC X(20).
05 ASSOC-TABLE OCCURS 350 TIMES
ASCENDING KEY IS A-NAME
INDEXED BY I-1.
10 A-NAME PIC X(20).
10 A-NUM PIC 9(4).
SEARCH ALL ASSOC-TABLE
AT END DISPLAY ‘NAME NOT FOUND’
WHEN NAME = A-NAME(I-1)
DISPLAY ‘NAME FOUND’.
DATA DIVISION
WORKING STORAGE
Working Storage Section
Succeeds File Section
Used for Intermediate Storage
Common Practice to Group related items together
01 I-ADDRESS.
05 I-ADD-LINE-1 PIC X(30).
05 I-ADD-LINE-2 PIC X(30).
05 I-ADD-LINE-3 PIC X(30).
Syntax for Data Description Entry
level {data-name-1
FILLER}
[REDEF clause]
[BLANK-WHEN-ZERO clause]
[EXTERNAL clause] [GLOBAL clause]
[OCCURS clause] [JUST clause] [PIC clause]
[SIGN clause] [SYNCH clause]
[USAGE clause] [VALUE clause] .
REDEFINES
level {data-name-1 FILLER}
REDEFINES data-name-2
Allows the same area of memory to be referenced by
more than one data-name with different format and
sizes
Multiple 01 levels of same FD are Implicitly
Redefined
Restrictions on REDEFINES
OCCURS and REDEFINES cannot be combined
Qualification of data-name-2 not required
Value Clauses only in Condition Names
Redefinition Ceases Whenever a Level No is <= that
of data-name-1 or data-name-2 is encountered
REDEFINES Examples
01 l-VARIABLES.
05 l-DATE PIC X(8).
05 l-DATE-DTLS REDEFINES l-DATE.
10 l-DAY PIC 9(2).
10 FILLER PIC X(1).
10 l-MONTH PIC 9(2).
10 FILLER PIC X(1).
10 l-YEAR PIC 9(2).
REDEFINES Examples
01 EMP-REC.
05 EMP-NBR PIC 9(4).
05 EMP-REC-TYP PIC X.
05 EMP-DATA PIC X(146).
05 EMP-NA-DATA REDEFINES EMP-DATA.
10 EMP-NAME PIC X(60).
10 EMP-ADDRS PIC X(60).
10 EMP-CITY PIC X(20).
10 EMP-PIN-CD PIC 9(6).
REDEFINES Examples
05 EMP-SKILL-DATA REDEFINES EMP-DATA.
15 EMP-SKILL PIC X(5) OCCURS 20.
JUSTIFIED
{ JUSTIFIED RIGHT
JUST}
The JUSTIFIED clause overrides standard positioning
rules for a receiving item of the alphabetic or
alphanumeric categories
Can’t be specified for other categories
JUSTIFIED ...
Does not affect initial values, as determined by the
VALUE clause
Does not affect the setting of conditional variable
when the associated condition name is set
JUSTIFIED - Examples
05 ALIGN-RT PIC X(5) VALUE ‘RT’.
88 C-RT VALUE ‘RT’.
1. MOVE ‘RT’ TO ALIGN-RT
2. SET C-RT TO TRUE
VALUE OF ALIGN-RT
BEFORE STMT-1 RTBBB
AFTER STMT-1 BBBRT
AFTER STMT-2 RTBBB
OCCURS
Used for defining Tables(a.k.a. 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.
Tables can be Fixed Length or Variable Length
OCCURS ...
Can’t be defined for a data item which:
Has a level number of 01, 66, 77, or 88.
Describes a redefined data item
Fixed Length Tables
OCCURS integer-2 TIMES
[ {ASCENDING KEY IS DESCENDING }
dataname-2 [ ... ] ]
[ INDEXED BY index-name-1 [ ... ] ]
Variable Length Tables
OCCURS int1 TO int2 TIMES
DEPENDING ON data-name-1
[ {ASCENDING KEY IS DESCENDING }
dataname-2 [ ... ] ]
[ INDEXED BY index-name-1 [ ... ] ]
OCCURS - Index Name
Required if item is indexed anywhere in the program
Index name is implicitly defined
Index name cannot be associated with any other data
hierarchy
INDEX is an offset
Must be initialized before it can be used using SET and
PERFORM VARYING
Occurs - Depending On Rules
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
GLOBAL definition needs rules similar to
EXTERNAL
Occurs - Depending On Rules ...
Length of group item containing Occurs depending
If ODO is outside the group the ODO value decides
If ODO is inside and group item is sending field then also
ODO value decides
If ODO is inside and group item is receiving field then max
length of group value used provided there are no non-
subordinate to the group item
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.
OCCURS - Example
01 REC-1.
05 A1 PIC 99.
05 P1 PIC XX.
05 P2 PIC 99 OCCURS 1 TO 90 TIMES
DEPENDING ON A1.
P2 can have upto 90 elements based on the value A1 has.
PICTURE
[ PICTURE IS string
PIC ]
Specifies the characteristics and editing requirements
Must be specified for every elementary item except an
index data item or the subject of the RENAMES
clause. In these cases, use of this clause is prohibited.
SIGN
[SIGN IS {LEADING
TRAILING} ]
[ SEPARATE CHARACTER ]
Specifies the position and mode of representation of
the operational sign for a numeric entry.
SIGN Clause Examples
77 l-V1 PIC S9(3) SIGN LEADING VALUE -250
l-V1
K 5 0
77 l-V2 PIC S9(3) SIGN LEADING SEPARATE
VALUE -250
l-V2
- 2 5 0
SYNCHRONIZED
[ {SYNCHRONIZED { LEFT
SYNC } RIGHT } ]
Specifies the alignment of an elementary item on a
natural boundary in storage.
It is never required, but may improve performance on
some systems for binary items used in arithmetic.
USAGE
Specifies the format in which data is represented in
storage.
The USAGE clause can be specified for a data
description entry with a level-number other than 66 or
88.
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.
USAGE
USAGE IS {BINARY
COMP COMPUTATIONAL
COMP-1 COMPUTATIONAL-1
COMP-2 COMPUTATIONAL-2
COMP-3 COMPUTATIONAL-3
COMP-4 COMPUTATIONAL-4
DISPLAY
DISPLAY-1
INDEX
PACKED-DECIMAL
POINTER }
USAGE
COMP
Maintained in Binary Form
COMP-1
One Word Floating Point Form
COMP-2
Two Word Floating Point Form
COMP-3
Packed Decimal (N+1)/2 bytes
USAGE ...
INDEX
4-byte elementary data item
Used to save index-name values for future reference
Assign using a SET statement
Direct reference can be made in SET, SEARCH, USING
and relational condition
Whereas an Index Name can be used only in conjunction
with the array to which it points Index Data Item can be
used to point to any array
USAGE ...
POINTER
4-byte elementary item
Used to accomplish limited base addressing
Pointer data items can be compared for equality or moved
to other pointer items.
Direct reference can be made in SET, USING and relational
condition
VALUE clause can contain only NULL(S)
RENAMES
66 data-name-1 RENAMES
data-name-2
[THRU data-name-3]
Allows Re-grouping of Data Items
Cannot Rename 77 88 66 or 01 levels
Data Names must be in proper sequence
Not Used in Good Programs
77 Level
Elementary Data Item not belonging to any group
Must begin in Area A
Example
WORKING-STORAGE SECTION.
*
77 l-TEMP-VAR PIC 99.
77 l-SAVE-DATE PIC x(8).
*
Data Division
File Section
FILE SECTION
Contains an FD entry for each SELECT file Clause
(except sort/merge) in the program
Followed by Record Description
Record Description begins with Record Name
FILE SECTION
FD File Description entry specifies
Size of Logical and Physical Records
Value of File Attributes
FILE SECTION
Blocking
Size of Physical Record
Specified if Physical Record contains more than one
Logical Record
Record Sizes
Specified by the RECORD CONTAINS Clause
FD SYNTAX
FD file-name-1
[ IS EXTERNAL ]
[ IS GLOBAL ]
[ BLOCK CONTAINS [ int1 TO ]
int2 { CHARACTERS
RECORDS } ]
[ RECORDING MODE IS
{F V S U}]
Contd...
FD SYNTAX (Contd)
[ RECORD
{ CONTAINS int3 [TO int4]
CHARACTERS
IS VARYING IN SIZE FROM
int3 TO int4
CHARACTERS
[DEPENDING ON
data-name ]
}] Contd...
FD SYNTAX
[ LABEL { RECORD { IS
RECORDS } ARE }
{STANDARD
OMITTED} ]
[ DATA { RECORD IS
RECORDS ARE }
( data-name-2 ) ... ] .
SORT/MERGE FILE
Has SD Entry instead of FD for each Sort or Merge file
defined in SELECT Clause
Syntax same as FD entry for Sequential File
SAMPLE FD ENTRY
FD ASSOC-FILE.
*
01 ASSOC-REC.
05 ASSOC-NO PIC 9(9).
05 ASSOC-NAME PIC X(30).
*
SD SORT-FILE.
01 SORT-REC.
05 SORT-KEY PIC 9(9).
05 FILLER PIC X(72).
Recommended Guidelines for File Section
Order of FDs same as order of SELECT
Blank line before each FD & 01 Lvl
Each File clause starts in Col 16
Have only 01 level entry for file and code details in
working storage
Contd...
Recommended Guidelines for File Section
(Contd.)
If details are also required in FD:
Filler items in Column 30
Picture abbreviated to PIC
PIC clause in Column 48
Increment Levels by 5
Each level is indented by 4 columns
Record Format
Fixed
Specify RECORDING MODE F
Max length of 01 level entry is less than BLOCK contains
clause size AND either
Record contains clause has single size (Not a range)
All 01 level entry is same and no depending on option
Unblocked
B L O C K E D
Record Format
Variable
Specify RECORDING MODE V
Max length of 01 level entry is less than BLOCK contains
clause size AND either
Record contains clause has range
01 level entry is different or has depending on option
BDW RDW Data Record
BDW / RDW = 2 byte length + 2 byte
System info
Record Format
Spanned Records
Specify RECORDING MODE S
Max length of 01 level entry + 4 is greater than BLOCK
contains clause size
Can be Fixed or variable
Can be Blocked or Unblocked
BDF SDF Rec segment SDF
BDF - Block descriptor field
SDF - Segment descriptor field
Record Format
Undefined Records
Unspecified characteristics
Compiler does not derive
Specify RECORDING MODE U
Each block on external storage is treated as a logical record;
Record Format
Undefined Records (contd.)
Max record length is
As specified in Record Contains or varying
clause
If omitted max 01 level entry size
BLOCK contains clause is treated as comment
Linkage Section
Describes data made available from another program
Storage within the program is not reserved because the
data area exists elsewhere
EXTERNAL and GLOBAL clause not allowed
VALUE clause, if used, will be treated as
documentation
Recommended Guidelines for Working
Storage Section
Prefix Data Names by l-
Code all 77 Level Items in the beginning
Try to Group related data items
Use Value Clause only for Constant Data Items
Do Not Use 66 Level
Procedure Division
PROCEDURE DIVISION
[USING data-name-1 ... ]
The Using clause specifies the parameters passed to
the program
Each Data Name in the Using clause is defined in the
LINKAGE SECTION
Contains the Actual Code
File Input - Output Verbs
Are for processing datasets
Displaying information to and Capturing information
from the user
OPEN
OPEN { INPUT file-name1 ...
OUTPUT file-name2 ...
I-O file-name3 ...
EXTEND file-name4 ... } ...
Opens the file for processing
EXTEND is allowed only for sequential files (not for
VSE)
OUTPUT clears the file of its existing records
Open - File position indicator
The successful execution of OPEN INPUT or OPEN I-
O statement sets the file position indicator to
1 for non-empty QSAM file
For VSAM sequential and indexed files, to the characters
with the lowest ordinal position in the collating sequence
associated with the file.
For VSAM relative files, to 1.
OPEN - Extend Rules
When the EXTEND is specified the file positioned
immediately after the last record written in the file
For ESDS or RRDS file the added records are placed after
the last existing records
For KSDS your add must have a record key higher than the
highest record in the file
CLOSE
CLOSE file-name1 ...
Closes the open file
Terminates the file processing
COBOL performs automatic closing if not closed
At termination of run-unit
CANCEL command
Return from pgm with INITIAL attrib
READ
Format-1 - Sequential Read
READ file-name-1 NEXT RECORD
[ INTO identifier-1 ]
[ AT END imperative-stmt-1]
[ NOT AT END imperative-stmt-2 ]
[ END-READ ]
NEXT phrase is optional for SEQUENTIAL access mode
& a must for DYNAMIC
READ
Format-2 - Random read
READ file-name-1 RECORD
[ INTO identifier-1 ]
[ KEY IS data-name-1]
[ INVALID KEY imperative-stmt-3 ]
[ NOT INVALID KEY imperative-stmt-4 ]
[ END-READ ]
Data-name-1 is either a RECORD KEY or
ALTERNATE RECORD KEY of the Indexed file
READ Random - Indexed file
Key of reference :
Data name specified in KEY phrase
The prime RECORD KEY data name if KEY phrase not
specified
When dynamic access is specified, this key of
reference is used for subsequent executions of
sequential READ
READ Random - Relative file
Execution of a Format 2 READ statement reads the
record whose relative record number is contained in
the RELATIVE KEY data item,
The KEY phrase must not be specified
More on File Position Indicators
Indicates the next record to be accessed for sequential
COBOL requests
You do not specify them anywhere in your program
It is set by successful:
OPEN, START, READ, and READ NEXT statements
More on File Position Indicators ...
Subsequent READ or READ NEXT requests then uses
& updates it
It is not used or affected by the output statements :
WRITE, REWRITE, or DELETE.
The file position indicator has no meaning for random
processing
READ - Example
File- Indexed, Dynamic Access
Record Description:
01 ASSOC-REC
05 ASSOC-NO-KEYPIC 9(4).
05 ASSOC-NAME PIC X(10).
Assoc # Assoc Name
0004 RAJESH
0010 RAMESH
0015 GOPAL
0016 RAGHAVAN
0100 SARITA
0401 RANI
READ - Example
Operation File Record
Position area
Pointer
OPEN input 0004 Not defined
READ next 0010 0004Rajesh
READ Key 0401 0100Sarita
0100
READ next end of file 0401Rani
READ Key 0016 0015Gopal
0015
READ key Undefined Undefined
0090 (Invalid key)
READ Undefined Undefined
NEXT
WRITE
WRITE rec-name [FROM id-1]
[ { BEFORE ADVANCING
AFTER }
{ int-1 { LINE
id-2 LINES }
mnemonic-name
PAGE } ]
[AT { END-OF-PAGE stmt-1
EOP }
[NOT AT { END-OF-PAGE stmt-2
EOP } [END-WRITE]
WRITE for Seq. Files
From its Record Area defined at 01 Level
WRITE ASSOC-REC
First Copy into File Area and then Write
WRITE ASSOC-REC FROM COPY-REC
Note that File Name is not mentioned in the Write
Statement
WRITE for Printer Files
Facilities for Paper Movement are provided
Print and Advance
Advance and Print
Position to New Page
Advance by given number of lines
End of Page Logic ( FD entry for this file must contain a
LINAGE clause)
WRITE for Printer Files ...
When ADVANCING option is used
First char of record reserved for printer control
If compile has ADV the LRECL of file should be one more
than FD entry record area length
If compile option is NOADV then LRECL of file is same as
FD entry record area length
leave the 1st char for printer control
WRITE for Disk Files
WRITE record-name
[ FROM id-1 ]
[ INVALID KEY imperative-stmt-1 ]
[ NOT INVALID KEY
imperative-stmt-2 ]
[ END-WRITE ]
WRITE - Invalid key
Not Allowed for ESDS
Attempt to write beyond file boundary
Record with specified key already present (KSDS,
RRDS)
WRITE - Rules for VSAM
When access is sequential
For KSDS, records must be released in ascending order of
RECORD KEY values
Else INVALID KEY condition will be raised
For RRDS system returns the RELATIVE KEY if clause is
specified in SELECT stmt
WRITE - Rules for VSAM
When access is random or dynamic
For KSDS populate RECORD key data item and
ALTERNATE key data item (if any)
For RRDS populate the RELATIVE key data item
REWRITE
REWRITE record-name
[ FROM id-1]
[ INVALID KEY imperative-stmt-1]
[ NOT INVALID KEY
imperative-stmt-2 ]
[ END-REWRITE ]
Updates an existing record in a file
File should be opened in I-O mode
REWRITE - Invalid Key
When access mode is sequential, and the value of
RECORD KEY of the record to be replaced not =
RECORD KEY data item of the last-retrieved record
Value contained in RECORD KEY not = any record in
file
Duplicate ALTERNATE RECORD KEY when
duplicates are not allowed
REWRITE - Rules
File should be opened in I-O
After REWRITE record is not available in the rec area
File position ind not affected
For Sequential files
INVALID KEY not allowed
Record length can’t change
For random or dynamic access the record to be
rewritten need not be read first
DELETE
DELETE file-name-1 RECORD
[ INVALID KEY imperative-stmt-1]
[ NOT INVALID KEY imperative-stmt-2]
[ END-DELETE ]
DELETE ...
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.
DELETE - Rules
File should opened for I-O
In sequential access mode, the last input/output
statement must have been a successfully executed
READ
INVALID key not allowed
For Random or Dynamic access system removes
record pointed by the RECORD key(KSDS) or
RELATIVE key(RRDS)
File Status Codes and Meaning
2 char code
Status key 1
Status key 2
Status key 1 tells the type of error
Status key 2 gives the detail
File Status Codes and Meaning
Status key 1
0 - Successful Completion
1 - At end condition
2 - Invalid key condition
3 - Permanent error condition
4 - Logic error
9 - Implementor defined (VSAM)
File Status Codes and Meaning ...
Successful Completion-0
0 - No further info
1 - Duplicate - Read, (Re)Write
2 - Length error for Fixed files
5 - Optional file not present
At end condition-1
0 - End of file
4 - Relative key > max possible
File Status Codes and Meaning ...
Invalid Key-2
1 - Ascending key violation / Rewrite change primary Key
2 - Duplicate key when not allowed (Primary, Alternate or
relative key)
3 - Record not found
4 - Write beyond boundary
File Status Codes and Meaning ...
Permanent error-3
0 - no further info
4 - Due to boundary violation
5 - File not available (ddname not found/defined)
7 - Invalid open mode on open
8 - Open of file closed with lock
9 - DCB conflict during open
File Status Codes and Meaning ...
Logic error-4
1 - Open of file in open status
2 - Close of file not in open stat
3 - Rewrite or Delete after unsuccessful Read
4 - Rewrite changed record len or Write record len > max
5 - No position for Read next
7 - Read on file not opened for Input or I-O
8 - Write on file not opened for Output or I-O or Extend
9 - Rewrite on file not opened for I-O
File Status Codes and Meaning ...
Implementor def- 9(VSAM)
0 - No further info
1 - Password failure
2 - Logic error
3 - Resource not available
4 - No file position for cmpr2 opt
5 - Invalid/Incomplete file info
6 - No DDname found
7 - Open successful; File verified
Sub-Program
CALL
Transfers control from one object program to another
within the run unit.
Called program starts executing from:
Top of program
ENTRY label (not good programming practice)
Transfer control methods
Call nested program
Static call
Dynamic call
CALL
Parameters to called program:
By reference
By content
Use RETURN-CODE special register to pass return
codes
Return of control depends on the termination stmt
issued by the called program
Stop run unit
Return to called program
CALL
CALL { id-1 lit-1} [ USING
{ [BY REFERENCE ]
{ id-2 file-name-1
ADDRESS OF id-3} ...
BY CONTENT
{ [LENGTH OF] id-2
ADDRESS OF id-3
lit-1} ... } ... ]
[ON {OVERFLOW imperative stmt-1]
EXCEPTION }
[ NOT ON EXCEPTION imperative stmt-2]
[END-CALL]
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
CALL - Calling pgm
WORKING-STORAGE SECTION.
77 L-SUBPGM-1 PIC X(8) VALUE ‘SUBPGM1’.
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.
CALL - Calling pgm
PROCEDURE DIVISION.
....
CALL l-SUBPGM1 USING
BY CONTENT l-PARM1 l-PARM2
BY REFERENCE l-PARM3
CALL - Called pgm
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.
05 L-LEAVE PIC S9(2)V9 COMP-3.
PROCEDURE DIVISION USING
L-PARM1 L-PARM2 L-PARM3.
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 cond occurs when the called
pgm cannot be made available.
CALL - Rules
Called program must not execute a CALL statement
that directly or indirectly calls the calling program
(Recursion not allowed)
EXIT PROGRAM
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
EXIT PROGRAM
When there is no next executable stmt in a called
program, an implicit EXIT PROGRAM stmt is
executed
EXIT PROGRAM stmt in a called program with
INITIAL attribute is equivalent to executing a
CANCEL
An EXIT PROGRAM executed in a main program has
no effect.
STOP
STOP {RUN
lit-1}
Halts execution of the program :
Permanently (RUN option)
Temporarily (Lit-1 option)
literal communicated to operator and execution suspended
Program execution is resumed only after operator intervention
STOP (Contd.)
STOP RUN statement closes all files defined in any of
the programs comprising the run unit.
GOBACK
GOBACK
Functions like:
EXIT PROGRAM statement when coded in a called
program
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.
END PROGRAM
An END PROGRAM is optional for the last program
in a sequence only if that program does not contain any
nested source programs.
Sort & Merge
SORT
Accepts records from one or more files or INPUT
PROCEDURE
Sorts them according to the specified key(s)
Makes the sorted records available through an
OUTPUT PROCEDURE or in a file
SORT
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 - Examples
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
SORT - Examples
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.
SORT - Examples
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-NMPIC X(20).
SORT - Examples
SD SORTED-EMP-FILE
LABEL RECORDS ARE OMITTED.
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).
SORT - Examples
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.
SORT - Rules
When USING / GIVING option is specified the input /
output file(s) to sort must not be open
The key used in the SORT statement cannot be
variably located.
When control passes the last statement in the INPUT
PROCEDURE, the records that have been released to
the file referenced by filename-1 are sorted.
SORT - Rules
When the file referenced by filename-1 is sorted
control passes to first statement in the OUTPUT
PROCEDURE.
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
RELEASE sort-rec-name-1
[FROM id-1]
If INPUT PROCEDURE is used, at-least one
RELEASE stmt must be executed
RELEASE - Examples
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 sort-file-name-1
[RECORD INTO id-1]
[AT END imperative stmt1 ]
[NOT AT END imperative stmt2]
[END-RETURN]
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.
RETURN - Examples
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 THRU read-sorted-rec-exit
END-PERFORM
.
WRITE-EMP-LIST-EXIT.
EXIT.
MERGE
Combines two or more identically sorted files and
makes records available in merged order
MERGE
MERGE file-1 { ON
{ASCENDING
DESCENDING} KEY id-1... } ...
[COLLATING SEQUENCE IS
alphabet-name-1]
USING file-2 [file-3 ...]
{GIVING file-4
OUTPUT PROCEDURE IS
proc-nm-1 [THRU proc-nm-2]}
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.
MERGE - Rules (Contd.)
Collating Sequences
COLLATING SEQUENCE option of MERGE statement
that is defined in SPECIAL-NAMES paragraph
PROGRAM COLLATING SEQUENCE specified in the
Configuration Section
Default is EBCDIC
COMPILER DIRECTIVES
Compiler Directive
Causes the compiler to take a specific action during
compilation:
BASIS CBL (PROCESS)
*CONTROL (*CBL)
COPY DELETE
EJECT ENTER
INSERT
READY or RESET TRACE
REPLACE SERVICE LABEL
SERVICE RELOAD
SKIP1/2/3 TITLE USE
Compiler Directive - COPY
COPY { text-name
lit-1 }
[ { OF { lib-name
IN } lit-2 } ]
[ SUPPRESS ] [ REPLACING
( op-1 BY op-2 ) ... ] .
op-1 and op-2 can be either pseudo-text, an identifier, a
literal, or a COBOL word (except COPY).
Compiler Directive
COPY - Example
01 :TAG:.
02 :TAG:-WEEK PIC S99.
02 :TAG:-GROSS-PAY PIC 9(5)V99.
02 :TAG:-HOURS PIC S999 OCCURS 1 TO
52 TIMES
DEPENDING ON :TAG:-WEEK
OF :TAG:.
COPY PAYLIB REPLACING ==:TAG:==
BY ==Payroll==.
Compiler Directive
COPY - Example
01 PAYROLL.
02 PAYROLL-WEEK PIC S99.
02 PAYROLL-GROSS-PAY PIC S9(5)V99.
02 PAYROLL-HOURS PIC S999
OCCURS 1 TO 52 TIMES
DEPENDING ON PAYROLL-WEEK
OF PAYROLL.
Compiler Directive
COPY - Rules
Copy statement can be nested but
Can’t contain REPLACING option
Should not cause recursion
If SUPPRESS
Specified then listing will not contain the statement within
the COPY member
If not then listing will contain the statements with a C after
the source pgm line number
COMPILER OPTIONS
Compiler Options
DYNAM / NODYNAM
All CALLs by literal ALSO to be loaded dynamically
DYNAM forced RESIDENT option
FDUMP / NOFDUMP
FDUMP produces formatted dump when execution ends
abnormally
SYSDBOUT ddname must be allocated at run time
For CICS FDUMP output is written to CEBRxxxx queue.
(xxxx is terminal id)
Compiler Options
LIB / NOLIB
Use LIB if COPY or BASIS stmt used
Allocate SYSLIB and SYSUT5 ddnames
LIST / NOLIST
LIST produces assembler expansion
LIST and OFFSET are mutually exclusive and if both given
LIST ignored
MAP / NOMAP
Use MAP to produce a listing of the items you defined in
the Data Division
Compiler Options
SSRANGE / NOSSRANGE
Checks if subscripts or indexes attempt to reference an area
outside the region of the table
Reference modification expressions will be checked
Variable-length items will also be checked
Use it while testing