Professional Documents
Culture Documents
Cobol Certification Guide For Developers
Cobol Certification Guide For Developers
Version - 1
COBOL
Table of Contents
1.INTRODUCTION..........................................................................................................5
2. WORKING WITH DATA...........................................................................................10
3. ACCEPT/DISPLAY VERBS.......................................................................................20
4. MOVE STATEMENTS...............................................................................................22
5. ARITHMETIC VERBS...............................................................................................27
6. DECISION MAKING.................................................................................................32
7. ITERATIONS...............................................................................................................35
8.FILE HANDLING........................................................................................................38
9.SORTING AND MERGING FILES...........................................................................44
10.TRAPPING RUNTIME ERRORS...........................................................................47
11.CONTROL BREAK PROCESSING........................................................................48
12.INDEXED FILES.......................................................................................................49
13.TABLE HANDLING..................................................................................................54
14.CALL STATEMENT..................................................................................................58
15.STRING HANDLING................................................................................................61
APPENDIX A (ASSIGNMENTS)................................................................................64
APPENDIX B (STANDARDS).....................................................................................87
APPENDIX C (BIBLIOGRAPHY/REFERENCES)..................................................88
APPENDIX D (FILE STATUS CODES).....................................................................89
APPENDIX F (SYNTAX).............................................................................................90
COBOL
Day-Wise Schedule
Day 1
Introduction
Programming Structure, Coding Formats
Constants, Identifiers, Figurative Constants
Data Division
Level numbers
Elementary and group data names
Picture clauses [Edit and computation]
Value clause, Usage clause, Redefines clause, Renames clause
Procedure Division
Input and Output verbs
Simple Programs
Day 2
Arithmetic verbs
Move
Numeric, Non numeric, Group
Control verbs
If, Condition names, Goto, Perform
Sample Programs
Day 3
File Organization Concepts
Sequential Files
Creation
Access
Query
Sort and Merge sequential files
Copy verb
Day 4
Trapping Runtime errors
Simple reports
Reports with page totals and net totals
Day 5
Single level control break
Double level control break
Index files
Creation [Record key and alternate keys]
Conversion of sequential to indexed files
Random and sequential access
COBOL
Day 6
Start verb
Edit and deleted records in indexed files
File maintenance
Report generation with index files
Day 7
Master, Transaction files
File update
Update existing master
Create new master
Day 8
Table Handling
One and two dimensional arrays
Redefines clause
Files and tables
Search a table
Day 9
Subprograms
Call verb
Linkage section
String Handling verbs
COBOL
1.Introduction
COBOL was developed in 1959 by a group called the CODASYL
Committee. CODASYL is an abbreviation for Conference on Data Systems Languages.
This committee included representatives from academia, user groups, and computer
manufacturers. The ultimate objective of this committee was to develop a standard
business-oriented language for which all major manufacturers would provide compilers.
The Department of Defense convened this conference since it, as well as other
government agencies, was particularly dissatisfied with the lack of standards in the
computing field.
Features of COBOL
1. Business-Oriented Language
As a business-oriented language COBOL is designed specifically for commercial
applications, such as payroll and inventory, that typically operate on a large volume of
data.
2. A Standard Language
COBOL compilers are available for most computers. The same COBOL program
may be compiled and run on a variety of different machines.
The universality of COBOL allows computer uses greater flexibility than they
would have with many other languages. A company is free to acquire different brands of
computers while using a single programming language. Similarly, conversion from one
model computer to a more advanced or newer one presents no great problem as long as
there is a COBOL compiler for each model.
3. An English-like Language
COBOL is an English-like language. All instructions can be coded using English
words rather than complex codes. To add two numbers together, for example, we use the
word ADD. Similarly, the rules for programming in COBOL conform to many of the
rules for writing in English, making it a relatively simple language to learn.
4. Self Documenting
One advantage of COBOL computer programs is that they can be substantially selfdocumenting. Self-documentation is a characteristic of a language that allows a reader of
a program to understand its function and follow its processing steps. The language
instructions are very English-like, but the programmer has substantial choice as to
whether to make a program self-documenting or obscure.
COBOL
Structure of COBOL programs
COBOL programs are written according to a special structure which is organized
into a hierarchy of parts.
A character is the lowest form in the program structure
A word is made up of one or more characters.
A clause consists of characters and words and is used to specify an attribute of an
entry.
A statement is a syntactically valid combination of words and characters written
in the PROCEDURE DIVISION of a COBOL program and beginning with a verb.
A sentence is a sequence of one or more statements, the last of which is
terminated by a period followed by a space.
A paragraph consists of one or more sentences.
A section consists of one or more paragraphs.
A division consists of one or more paragraphs or sections. Every COBOL
program consists of four divisions in the following order : IDENTIFICATION
DIVISION, ENVIRONMENT DIVISION, DATA DIVISION and PROCEDURE
DIVISION.
COBOL Words
A sequence of continuous characters from the character set can form a word.
There are two types of COBOL words, reserved words and user-defined words.
COBOL words are formed by using the following character set :
Digits
Letters
Space
Special characters
0-9
A-Z
(blank)
().+-* /=$,;<>
Reserved words are words that are defined both syntactically and semantically by
the COBOL language. The programmer cannot use any of these words except in the form
specified by the language.
User-defined words (data names) are words supplied by the programmer in order
to satisfy the format of a clause or statement in the language.
COBOL
Rules for forming user-defined words
1 to 30 characters.
Letters, digits, and hyphens (-) only.
No embedded blanks.
At least one alphabetic character.
May not begin or end with a hyphen.
No COBOL reserved words such as DATA, DIVISION, etc.
Valid datanames
HOURS
SALES-TOTAL
SUBJECT1
AMOUNT-OF-TRANSACTION-OUT
Invalid datanames
DISCOUNTAUTHOR
BASIC+HRA
123
Divisions
IDENTIFICATION DIVISION
The IDENTIFICATION DIVISION is the first division of a COBOL program. It
supplies the information about the program to others who may read or use the program.
The IDENTIFICATION DIVISION is divided into the following paragraphs :
PROGRAM-ID. Program-name.
Used to specify the program name. Use names of eight characters or less, letter
and digits only, because such names are accepted on all systems.
AUTHOR. author-name.
Used to specify the programmers name.
DATE-WRITTEN. Date.
Specify the date the program was coded.
DATE-COMPILED. Date.
Can be coded with an actual date. But if it is coded without a date entry, the
compiler itself will automatically fill in the actual date of compilation.
ENVIRONMENT DIVISION
The ENVIRONMENT DIVISION is the only machine-dependent division of a
COBOL program. It is composed of two sections :
CONFIGURATION SECTION.
SOURCE-COMPUTER. Computer.
Computer used for compiling the program.
OBJECT-COMPUTER. Computer.
COBOL
Computer used for executing the program.
INPUT-OUTPUT SECTION.
Supplies information concerning the input and output devices used. This section is
required only if the program uses files or prints reports.
FILE-CONTROL.
DATA DIVISION
The DATA DIVISION defines and describes fields, records, and files in storage.
Commonly, it consists of the following sections :
FILE SECTION.
Defines all input and output files.
WORKING-STORAGE SECTION.
Reserves storage for fields not part of input or output but nonetheless required for
processing. These include constants, end-of-file indicators, and work areas.
LINKAGE SECTION.
Used to identify items that will be passed to the called program from the calling
program and vice-versa.
PROCEDURE DIVISION
The PROCEDURE DIVISION is divided into paragraphs. Each paragraph is an
independent module or routine that includes a series of instructions designed to perform
specific set of operations. Paragraph names are coined by the programmer following the
rules for forming data-names.
A PROCEDURE DIVISION may also consist of several sections. A section may
contain several paragraphs.
COBOL
Note : Division, Section, Paragraph Names and Sentences must end with a period
followed by at least one space.
A Sample COBOL Program Eg. 1.1
IDENTIFICATION DIVISION.
PROGRAM-ID. SAMPLE1.
AUTHOR. XYZ.
DATE-WRITTEN. 1-JUN-2000.
DATE-COMPILED.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
SOURCE-COMPUTER. IBM-PC.
OBJECT-COMPUTER. IBM-PC.
DATA DIVISION.
PROCEDURE DIVISION.
0000-MAIN.
STOP RUN.
COBOL
PICTURE Clauses
Group items are defined by a level number and a name, which is followed by a
period. Elementary items must be described with a PICTURE (or PIC, for short) clause.
Functions of the PICTURE Clause
1. Specifies the type of data contained within an elementary item.
2. Indicates the size of the field.
10
COBOL
Types of data fields
Type
Alphabetic
Picture clause
A
Alphanumeric
Numeric
Explanation
A field that may contain only letters or blanks. E.g. a
name or item description field.
A field that may contain any character i.e. letters,
digits, blanks and/or special characters. E.g. an
address field.
Any signed or unsigned field that will contain only
digits is considered numeric.
AMT
PIC 99999.
AMT
PIC 9(5).
At least one space must follow the word PIC. All As, Xs, or 9s should appear
consecutively with no spaces between the characters. Similarly, if parentheses are used to
denote the size of a field, no spaces should appear within the parentheses.
Eg 2.4:
01 CUSTOMER-ADDRESS.
02 NAME.
03 FIRST-NAME PIC X(10).
03 LAST-NAME PIC X(15).
02 STREET.
03 S-NUMBER PIC 9(3).
03 STREET-NAME
PIC X(20).
02 ZIP-CODE
PIC 9(6).
WORKING-STORAGE SECTION
Defines and describes all data storage fields required for Processing (Including
constants).
These fields are not part of any input/output file.
11
COBOL
Types of data
Variable
Data entered by the user at run-time.
Constant
Data required for processing that is not dependent on the input to the system.
There are 3 types of literals.
1. Numeric Literals
A numeric literal is a constant used primarily for arithmetic operations.
Rules for forming numeric literals
a) 1 to 18 digits
b) A + or sign may be used, but it must appear to the left of the number.
c) A decimal point is permitted within the literal. The decimal point,
however may not be the rightmost character of the literal.
Eg 2.5:
+34
-8.6
.008
2. Nonnumeric Literals
A nonnumeric literal is a constant that is used in the PROCEDURE
DIVISION for all operations except arithmetic.
Rules for forming nonnumeric literals
a) The literal must be enclosed in quotation marks.
b) A maximum of 120 characters are permitted.
c) Any character permitted in the COBOL character set may be used
except the quotation mark.
Eg 2.6:
CODE
$ 123
12
COBOL
3. Figurative Constants
A figurative constant is a COBOL reserved word that has special significance
to the compiler.
The figurative constants are
ZERO, ZEROS, ZEROES
SPACE, SPACES
QUOTE, QUOTES
LOW-VALUE , LOW-VALUES
HIGH-VALUE, HIGH_VALUES
ALL
AMOUNT
Eg 2.8:
PIC Description
99V9
9(4)V99
999
PIC 999V99.
Value
38.50
452.39
550
Stored as
385
045239
550
Signed numbers
If a numeric field can have negative contents, then it must have an S in its PIC
clause. It must be the leftmost character. It does not take any storage space.
Eg 2.9:
13
COBOL
02
BALANCE
PIC S999.
Edited fields
The purpose of editing is to make data more suitable for human reading. Thus
editing in its most common use is associated with printing data on the printer. For
example, we may suppress leading zeros, we may use commas to make long numeric
values more legible, we may insert a dollar sign in front of a value, etc.
The editing characters are Z * $ - + CR DB . , B 0 /
Value
25
25
0.10
0.052
0.00
Printed as
b25
b2500
bbb10
bbb05
bbbbb
* - Check Protection
The * character is referred to as a check-protect character and is normally used to
protect dollar amounts written on checks or other negotiable documents. Asterisks are
zero-suppression characters that replace each non-significant zero and comma with *
instead of a space.
Eg 2.11:
PIC Description
**999
***99
Value
04678
00052
Printed as
*4678
***52
$ - Dollar Sign
By use of the $ PICTURE character the dollar sign is written in the position in
which it is to appear in the output. Since the $ sign is counted in the size of the field, the
field should be assigned at least one more position than the maximum number of
significant digits expected. The $ may also be floated, by which we mean that it will be
14
COBOL
entered to the left of the first significant digit in the field and be preceded by blanks. The
$ float stops when wither the first nonzero digit or the . or V is encountered. When the $
sign appears in all positions and the value is zero, the effect is to blank the entire field
(including any . and ,).
Eg 2.12:
PIC Description
$999V99
$9(5)V99
$$99V99
$$$$9V99
$$$$V99
$$$$V$$
Value
125.13
100.00
12.49
150.10
0.15
0.0
Printed as
$12513
$0010000
b$1249
$15010
bbb$15
bbbbb
. - (Decimal Point)
The . (decimal) PICTURE character indicates the position of the decimal point and
serves to align the actual decimal values in the field, only one such character may appear
in a field. Further, a field cannot contain both a V and a . PICTURE character. It cannot
be the rightmost character. If all the digits before and after the decimal point are zero, the
resulting field will be blank.
Eg 2.13:
PIC Description
$9,999.99
$9,999.99
$$,999.99
$$,$$$.99
$$,$$$.999
$$$$$.$$$
Value
2,350.22
150.31
150.31
24.40
0.019
0.0
Printed as
$2,350.22
$0,150.31
bb$150.31
bbb$25.40
bbbbb$.019
bbbbbbbbb
, - (Comma)
The comma is placed in the positions in which it is desired. A field may include more
than one , (comma) PICTURE character if the size of the field warrants it. A comma will
be appropriately suppressed if no significant digit precedes it. It cannot appear as the
leftmost or rightmost character.
Eg 2.14:
PIC Description
$9,999.99
$9,999.99
$$,999.99
$$,$$$.99
Value
2,350.22
150.31
150.31
24.40
Printed as
$2,350.22
$0,150.31
bb$150.31
bbb$25.40
15
COBOL
$$,$$$.999
0.019
bbbbb$.019
$$,$$$.$$$
$$,$$$.$$$
$$,$$9.999
$$,999.9
$$,999.9
$9,999.9999
0.009
0.0
2,210.2
2,210.2
2,210.256
23
bbbbb$.009
bbbbbbbbbb
$2,210.200
$2,210.2
$2,210.2
$0,023.0000
Value
35.2
35.2
-35.2
-001.3
.05
-.05
.01
Printed as
+035.2
035.2+
035.2b-1.3
bb+0.05
bb-0.05
bbb+.01
----.---99.99
--999.99
999.9-
0.0
-10.25
100.25
-10.2
bbbbbbb
b-10.25
b100.25
010.2-
DB/CR
16
COBOL
In accounting applications there is often need to identify values that represent
debits or credits. The COBOL language facilitates such differentiation by means of the
DB (debit) and CR (CR) editing characters. The DB or CR symbol is written only to the
right of a field in the PICTURE clause, and in both cases it is represented in storage for
the purpose of subsequent output only when the value is negative.
Storage when
data negative
+
Blank
Blank
Blank
Value
135.26
-135.26
-10.50
DB
CR
Printed as
$135.26bb
$135.26DB
bb$10.50CR
B (blank)
The B insertion editing character results in blanks being entered in the designated
positions.
Eg 2.17:
05 NAME PIC ABABA(10) VALUE RBSMITH.
NAME = RbBbSMITHbbbbb
0 - (Zero)
The zero insertion character causes zeros to be inserted in the positions in which it
appears.
Eg 2.18:
05 AMOUNT PIC 9(4)000 VALUE 1365.
AMOUNT = 1365000
/ - (stroke)
Each / (stroke) in the PICTURE character string represents a character position into
which the stroke character will be inserted.
Eg 2.19:
17
COBOL
05 PRINT-DATE PIC 99/99/99 VALUE 040798.
PRINT-DATE = 04/07/98
VALUE Clause
In addition to defining storage fields using the PICTURE clause it is often
desirable to assign initial values to elementary items in the WORKING-STORAGE
SECTION. Such a value may remain unchanged throughout the program, or it may
change in the course of program execution. Such initial values are generally not assigned
to FILE SECTION items, since such fields either receive their data from the external
medium or from other storage location as the result of program execution.
Eg 2.20:
02 PAGE-TITLE PIC A(14) VALUE SAMPLE PROGRAM.
02 TAX-RATE
PIC V99 VALUE IS 0.03.
USAGE clause
Numeric data in a computer may be represented in one of two basic modes. They
may be represented as character data or as numeric data. The arithmetic registers of
computers perform arithmetic with numeric data that is in numeric, not character mode. If
numeric data is represented in character mode, it must first
be converted to numeric mode before arithmetic computations can be performed.
In COBOL, data in character mode is described in DISPLAY mode, while data in
numeric mode is described as being COMPUTATIONAL MODE. All data items are
assumed to be in DISPLAY mode unless they are declared to be COMPUTATIONAL.
The declaration is done in the DATA DIVISION with the USAGE clause.
Eg 2.22:
02 AMOUNT-1
PIC 99.
18
COBOL
02
02
02
AMOUNT-2
AMOUNT-3
AMOUNT-4
REDEFINES Clause
The REDEFINES clause can be used to allow the same storage location to be
referenced by different data-names or to allow a regrouping or different description of the
data in a particular storage location.
Restrictions
The REDEFINES clause cannot be used
- at the 01 level in the FILE SECTION.
- when the levels of data-name-1 and data-name-2 are different.
- When the level number is 66 or 88.
Eg 2.23:
1
SAMPLE.
02 RECEIVABLE.
03 CUSTOMER-NUMBER
PIC 9(8).
03 CUSTOMER-NAME
PIC X(11).
03 AMOUNT
PIC 9(4)V99.
02
PAYABLE REDEFINES RECEIVABLE.
03 VENDOR-NUMBER
PIC 9(6).
03 VENDOR-NAME
PIC X(12).
03 VENDOR-OWED-AMT
PIC 9(5)V99.
RENAMES Clause
The RENAMES clause provides the programmer with the capability of
regrouping elementary data items. It resembles the REDEFINES clause, except that it can
form a new grouping of data items which combines several items. Use of the RENAMES
clause is always signaled by the special 66 level number.
Eg 2.24:
01
66
TAX-RECORD.
02
SOC-SEC-NUMBER
PIC X(9).
02
NAME.
03
FIRST-NAME
PIC X(10).
03
LAST-NAME
PIC X(15).
02
TOTAL-YTD.
03
GROSS-PAY
PIC 9(8)V99.
03
NET-PAY
PIC 9(8)V99.
03
TAX
PIC 9(5)V99.
LAST-GROSS RENAMES LAST-NAME THRU NET-PAY.
Qualification of names
A data name that is not unique must be qualified in COBOL verbs.
19
COBOL
Eg 2.25:
01 IN-REC
05 NAME PIC X(10).
05 AGE PIC 99.
01 OUT-REC.
05 NAME PIC X(10).
05 B-DATE PIC 9(6).
MOVE NAME OF IN-REC TO NAME OF OUT-REC.
20
COBOL
3. ACCEPT/DISPLAY verbs
The PROCEDURE DIVISION contains all the instructions required for
processing. It is divided into various paragraphs or modules. Each module consists of
sentences.
The ACCEPT and DISPLAY verbs are used for input and output in conjunction
with storage fields that are not part of any files.
ACCEPT
The instruction ACCEPT identifier enable the user to enter input data directly
from a keyboard.
Eg 3.1:
ACCEPT MY-NAME.
DISPLAY
DISPLAY can reference a series of identifiers or literals.
Eg 3.2:
DISPLAY MY-NAME.
DISPLAY HELLO.
STOP RUN
The verb STOP RUN terminates program execution. A program may contain more than
one STOP RUN statement, depending on the logic of the program. STOP RUN signifies
the logical end of the program.
A program using DISPLAY and ACCEPT.
Eg 3.3:
IDENTIFICATION DIVISION.
PROGRAM-ID. SAMPLE2.
*This program accepts the users name and displays a message.
AUTHOR. XYZ.
DATE-WRITTEN. 1-JUN-2000.
DATE-COMPILED.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
SOURCE-COMPUTER. IBM-PC.
OBJECT-COMPUTER. IBM-PC.
DATA DIVISION.
WORKING-STORAGE SECTION.
01
USER-NAME
PIC X(15).
PROCEDURE DIVISION.
21
COBOL
0000-MAIN.
DISPLAY Enter your name : .
ACCEPT USER-NAME.
DISPLAY HELLO USER-NAME.
STOP RUN.
22
COBOL
4. MOVE statements
A value can be moved from one storage location to another by the move
statement. Contents of receiving field are changed after the operation.
Verb
SENDING
RECEIVING
Types of MOVE :
The MOVE statement can be categorized based on the receiving field : numeric
MOVEs and non-numeric MOVEs.
Numeric MOVE
A numeric move is one in which a numeric field or literal is moved to a numeric
receiving field.
When Sending and Receiving fields have the same PIC clauses
If the PIC clauses of both fields are identical, the contents of identifier-2 will be
replaced with the contents of identifier-1 and the sending field will be unchanged.
23
COBOL
Result :
AMT-OUT = 0123
Avoiding truncation
In a numeric move, if the receiving field has fewer integer positions than the
sending the field, the most significant digits will be truncated.
Eg 4.3:
05 AMT-IN
05 AMT-OUT
Result :
AMT-OUT = 23
Rule 2: Moving decimal portions of numeric fields
When moving a decimal portion of a numeric sending field to the decimal portion
of a numeric receiving field, movement is from left to right, beginning at the implied
decimal point. Low-order (rightmost) non-filled decimal portions of the receiving field
are replaced with zeros.
Eg 4.4:
a. When receiving field has more decimal positions than the sending field
05 AMT-IN
05 AMT-OUT
Result :
AMT-OUT = 12.340
b. When receiving field has fewer decimal positions than the sending field
05 AMT-IN
05 AMT-OUT
Result :
AMT-OUT = .3
Note : The same rules apply to numeric literals moved to numeric fields
Non-numeric MOVE
A non-numeric MOVE operation occurs in the following cases :
24
COBOL
1. Moving an alphanumeric or alphabetic field, defined by a PICTURE of Xs or
As, to another alphanumeric or alphabetic field.
2. Moving a non-numeric literal to an alphanumeric or alphabetic field.
3. Moving a numeric field or numeric literal to an alphanumeric field or to any
group item.
Rule :
In a non-numeric move, data is transmitted from the sending field to the receiving
field from left to right. Low-order or rightmost positions of the receiving field that are not
replaced with sending field characters are filled with spaces.
Eg 4.4:
a. When receiving field is larger than the sending field
05 NAME-IN
05 NAME-OUT
Result :
NAME-OUT = ABCbb
b. When receiving field is smaller than the sending field
05 NAME-IN
05 NAME-OUT
Result :
NAME-OUT = AB
c. When the sending field is numeric integer and the receiving field is non-numeric
05 NAME-IN PIC 999 VALUE 321
05 NAME-OUT
PIC X(5) VALUE DEFGH.
MOVE NAME-IN TO NAME-OUT.
Result :
NAME-OUT = 321bb
d. When the sending field is a non-numeric literal
05 NAME-OUT
25
COBOL
MOVE XYZ TO NAME-OUT.
Result :
NAME-OUT = XYZbb
e. When the sending field is a figurative constant
05 NAME-OUT
Result :
NAME-OUT = bbbbb
A group move is considered a non-numeric move
All group items, even those with numeric subfields, are treated as alphanumeric
fields.
Eg 4.5:
05 DATE-OUT.
10 MONTH-OUT
10 YEAR-OUT
PIC 99 .
PIC 99.
Result :
DATE-OUT = 0194
b. MOVE 194 TO DATE-OUT.
Result :
DATE-OUT = 194b
Permissible MOVE operations
Sending Field
Numeric
Alphabetic
Alphanumeric
ZEROS
SPACES
Group item
Numeric
X
x
x
x
Receiving Field
Alphabetic
Alphanumeric
x
*
Group item
* Numeric integer fields can be moved to alphanumeric fields but numeric fields with a V in the PIC clause cannot be
moved to alphanumeric fields.
26
COBOL
The MOVE CORRESPONDING statement
In the MOVE CORRESPONDING statement, all elementary items within the
sending group-item that have the same names as corresponding elementary items in the
receiving group-item will be moved. The same-named fields in the receiving group-item
need not be in any specific order. Any fields of the sending record, that are not matched
by the same-named fields in the receiving record are ignored.
27
COBOL
5. Arithmetic verbs
All the basic arithmetic operations of ADD, SUBTRACT, MULTIPLY, and
DIVIDE require that the fields operated on (1) have numeric PIC clauses and (2) actually
have numeric data when the program is executed.
In all cases, the resultant field must be an identifier or data-name, not a literal.
ADD statement
The result, or sum, of an ADD operation is always placed in the last field
mentioned. The only field that is altered as a result of the ADD operation is this last field,
which is the one directly following the word TO.
When using the TO format in an ADD statement, all the data-names and literals
are added together, and the result placed in the last field specified.
When using the GIVING format, all fields and literals preceding the word
GIVING are added together and the sum is placed in the field following the word
GIVING.
Eg 5.1:
05
05
05
EMP-BASIC
EMP-HRA
EMP-TOTAL
a.
Result :
EMP-TOTAL = 4100
b.
Result :
EMP-TOTAL = 4650
SUBTRACT statement
All fields and literals preceding the word FROM will be added together and the
sum subtracted from the field following the word FROM. The result, or difference, will
be placed in this same field if no GIVING option is used. All other fields will remain
unchanged.
Eg 5.2:
05
05
05
05
EMP-GROSS
EMP-PF
EMP-ITAX
EMP-NET
a.
28
COBOL
Result :
EMP-BASIC = 4000
b.
Result :
EMP-GROSS = 3900
c.
Result :
EMP-GROSS = 4250
EMP-NET = 3900
a.
MULTIPLY 12 BY EMP-GROSS.
Result :
EMP-GROSS = 48000
b.
Result :
EMP-GROSS = 4000
EMP-ANN-SAL=48000
c.
Result :
EMP-GROSS = 1000
d.
Result :
EMP-GROSS = 4000
EMP-NEW-SAL = 1000
29
COBOL
e.
Result :
EMP-NEW-SAL = 1000
ROUNDED Option
A frequent need exists for rounding numeric values.
Eg 5.5:
05 AMT1
05 AMT2
05 AMT3
PIC 99V999
PIC 99V999
PIC 99V99
VALUE 12.857.
VALUE 25.142.
VALUE 37.99.
In the code given above, the result 37.999 is placed in an accumulator. When this
value is move to the field AMT3 , the low-order decimal position is truncated and 37.99
is stored in the field. A more desirable result would be 38.00 since 38 is closer to the sum
of 37.999. We consider results more accurate if they are rounded to the nearest decimal
position.
To obtain rounded results, the ROUNDED option may be specified with any
arithmetic statement. In all case, it directly follows the resultant data-name.
Eg 5.6:
ADD AMT1 AMT2 GIVING AMT3 ROUNDED.
30
COBOL
ON SIZE ERROR
Consider the following :
Eg 5.7:
05 AMT1
05 AMT2
05 AMT3
PIC 999
PIC 999
PIC 999
VALUE 800.
VALUE 150.
VALUE 050.
The effect of the above statement would be the same as coding MOVE 1000 TO
AMT3. In this case, the resultant field is not large enough to store the accumulated sum.
In other words , an overflow or size error condition has occurred. This will produce
erroneous results.
Eg 5.8:
ADD AMT1 AMT2 TO AMT3
ON SIZE ERROR MOVE ZERO TO TOTAL-OUT.
COMPUTE statement
If complex or extensive arithmetic operations are required in a program, the use of
the four arithmetic verbs may prove cumbersome. The COMPUTE verb provides another
method of performing arithmetic. The COMPUTE statement uses the following
arithmetic symbols :
+
Add
Subtract
*
Multiply
/
Divide
**
exponentiation
Eg 5.9:
COMPUTE TOTAL = AMT1 + AMT2 AMT3.
COBOL
**
* or / (whichever appears first from left to right)
+ or - (whichever appears first from left to right)
The use of parentheses overrides rules 1-3. That is, operations with parentheses
are performed first.
32
COBOL
6. Decision Making
A conditional statement is one that performs operations depending on the
existence of some condition. In COBOL, such statements generally begin with the word
IF and are called IF-THEN-ELSE or selection structures.
An imperative statement , as opposed to a conditional statement, is one that
performs an operation regardless of any existing condition.
A condition may test for a specific relation. A simple condition may be a single
relational test of the following form :
Eg 6.1:
IF AMT1 IS EQUAL TO AMT2
DIVIDE QTY INTO TOTAL
ELSE
ADD UNIT-PRICE TO FINAL-TOTAL.
The following symbols for simple relational conditions are valid within a COBOL
statement :
<
IS LESS THAN
>
IS GREATER THAN
=
IS EQUAL TO
Compound conditional
The compound conditional offers even greater flexibility for selection and enables
the IF statement to be used for more complex problems. The compound conditionals are
as follows :
OR
Performs an operation or a series of operations if any one of several conditions
exists.
33
COBOL
AND
If a statement or statements are to be executed only when all of several conditions
are met.
Negating conditionals
NOT
All simple relation, class or sign tests may be coded using a negated conditional
(NOT).
Eg 6.3:
IF AMT1 IS NOT EQUAL TO AMT2
PERFORM 200-NOT-EQUAL-RTN.
Sign test
We can test whether a field is POSITIVE, NEGATIVE, or ZERO with a sign test.
If a numeric field contains an amount less than zero, it is considered negative. If it has an
amount greater than zero, then it is considered positive.
Eg 6.4:
IF AMT IS POSITIVE
PERFORM 200-CALC-RTN.
Class test
We can test for the type of data (ALPHABETIC or NUMERIC) using the class
test.
Eg 6.5:
IF AMT-IN IS NUMERIC
PERFORM 300-CALC-RTN.
34
COBOL
Condition names
A condition-name is a user-defined word established in the DATA DIVISION that
gives a name to a specific value that an identifier can assume. An 88-level coded in the
DATA DIVISION is a condition-name that denotes a possible value for an identifier. A
condition-name is always coded on the 88 level and has only a VALUE clause associated
with it. Since a condition-name is not the name of a field, it will not contain a PICTURE
clause.
Eg 6.6:
05
MARITAL-STATUS
88 SINGLE
PIC X.
VALUE S.
or
Eg 6.6b:
IF SINGLE
PERFORM 1000-SINGLE-ROUTINE.
35
COBOL
7. Iterations
PERFORM statement
The simple PERFORM statement, is used to execute a specified routine from one
or more points in a program.
The PERFORM statement will :
1. Execute all instructions in the named paragraph.
2. Transfer control to the next instruction in sequence, after the PERFORM.
Eg 7.1:
PROCEDURE DIVISION.
100-MAIN-MODULE.
:
PERFORM 400-HEADING-RTN.
:
200-CALC-RTN.
:
:
400-HEADING-RTN.
:
:
PERFORM..THRU
The PERFORM executes all statement beginning at pargraph-name-1 until the
end of paragraph-name-2 is reached. Control is then transferred to the statement directly
following the PERFORM.
Eg 7.2:
100-MAIN.
PERFORM 300-PARA THRU 500-PARA.
:
200-PARA.
:
300-PARA.
:
400-PARA.
:
500-PARA.
EXIT.
600-PARA.
:
36
COBOL
following the original PERFORM. It is used, when necessary, as an end point in a
paragraph.
PERFORM..UNTIL
Iteration may be performed in COBOL using a PERFORM..UNTIL statement. The
contents of the identifiers used in the UNTIL clause should be changed within the
paragraph(s) being performed. The condition in a PERFORM .. UNTIL is tested before
the named paragraph is executed even once. If the condition indicated in the UNTIL
clause is met at the time of execution, then the name paragraph(s) will not be executed.
PERFORM..TIMES
The PERFORM..TIMES construct is used to execute a sequence of steps a fixed
number of times. It is not necessary to establish a counter that must be incremented each
time through the loop. When using the TIMES format (PERFORM paragraph-name-1
identifier-1 TIMES) : (1) the identifier must be specified in the DATA DIVISION; (2) it
must have a numeric PICTURE clause; and (3) it must contain only integers or zeros.
Eg 7.4:
* This program displays the Hello 3 times.
MOVE 3 TO COUNTER1.
PERFORM 200-DISP-RTN COUNTER1 TIMES.
:
STOP RUN.
200-DISP-RTN.
DISPLAY HELLO.
37
COBOL
GO TO
A GO TO permanently transfers control to another paragraph. It does not return
control to the paragraph from where it was issued.
38
COBOL
8.File Handling
File Organization methods
It is important that file be so organized that efficient processing can be
accomplished by matching the file data characteristics, processing method, and file
organization. Basically, three methods of file organization are available on disk systems :
sequential, indexed sequential, and relative file organization.
INPUT-OUTPUT SECTION
The INPUT-OUTPUT SECTION of the ENVIRONMENT DIVISION follows the
CONFIGURATION SECTION and supplies information concerning the input and output
devices used in the program. In the FILE-CONTROL paragraph, a file-name is selected
for each file to be used in the program; in addition, each file-name selected is assigned to
a device. The SELECT statement is coded in Area B.
Eg 8.1:
ENVIRONMENT DIVISION.
:
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT EMPLOYEE-FILE
ASSIGN TO EMP.DAT
ORGANIZATION IS LINE SEQUENTIAL.
39
COBOL
FILE SECTION.
Each file is described in the FILE SECTION with an FD sentence that may
consist of a series of clauses. After the clauses are specified, the FD sentence ends with a
period. FD is an abbreviation for File Description. Each FD entry will describe a file
defined in a SELECT statement in the ENVIRONMENT DIVISION.
The two entries, DATA DIVISION and FILE SECTION, are coded in Area A. FD
is also coded in Area A. The file-name, however, is typically coded in Area B.
Eg 8.2:
DATA DIVISION.
FILE SECTION.
FD EMPLOYEE-FILE
LABEL RECORDS ARE STANDARD
RECORD CONTAINS 70 CHARACTERS
BLOCK CONTAINS 10 RECORDS.
Label Records
Label records are usually created as the first and last records of a disk or tape to
provide identifying information about the file on disk or tape. Labels are created on
output files so that, when the same file is later read as input, the labels may be checked to
ensure that the file being accessed is the correct one. Labels are created on output files
and checked on input files. The COBOL compiler will supply the routine for writing
labels on output files or for checking labels on input file if the entry LABEL RECORDS
ARE STANDARD is included.
This LABEL RECORDS clause will result in the following :
1. For output files, the first record on disk or tape file will be created as a standard
80-position header label identifying the file to the system; similarly, the last
record on the disk or tape will be created as a trailer label.
2. For input files, these labels will be computer-checked to ensure that the file being
processed is the correct one.
The clause LABEL RECORDS ARE STANDARD is permitted for disk and tape files
only. Devices such as printers do not use label records, since identifying information is
unnecessary where data is visible to the human eye. The clause LABEL RECORDS ARE
OMITTED is used for such files.
40
COBOL
BLOCK CONTAINS clause
The BLOCK CONTAINS clause is included in the File Description entry only for
files in which disk or tape records have been blocked. Blocking is a technique that
increases the speed of input/output operations and makes more effective use of storage
space on disk and tape. A group of logical records is included within one block to
maximize the efficient use of a disk or tape area. For example, reading in a block of 10
disk records, is more efficient than reading in each disk record separately. Even if
blocking is used, the program processes records in the standard way, that is, one logical
record at a time.
EMPLOYEE-REC.
05 EMP-NAME.
10 EMP-FIRST-NAME PIC X(10).
10 EMP-LAST-NAME PIC X(15).
05 EMP-DEPT
PIC X(4).
05 EMP-SALARY
PIC 9(5)V99.
05 EMP-DOJ
PIC 9(6).
Input/output verbs
There are 4 input/output verbs : OPEN, READ, WRITE, CLOSE.
OPEN statement
Before an input or an output file can be used by the program it must be opened.
An OPEN statement, designates files as either input or output. It also accesses the
specific devices, and makes the files available for processing. It performs header label
routines if label records are STANDARD. The OPEN statement checks the header label
to determine if the correct file has been accessed.
Eg 8.4:
OPEN INPUT EMPLOYEE-FILE.
OPEN OUTPUT REPORT-FILE.
The order in which files are opened is not significant. The only restriction is that a
file must be opened before it may be read or written; a file must be accessed before it
may be processed. Since the OPEN statement accesses the files, it is generally on of the
first instructions coded in the PROCEDURE DIVISION.
41
COBOL
READ statement
After an input file has been opened, it may be read. A READ statement transmits
data from the input device, assigned in the ENVIRONMENT DIVISION, to the input
storage area, defined in the FILE SECTION of the DATA DIVISION.
The primary function of the READ statement is to transmit one data record to the
input area reserved for that file. That is, each time a READ statement is executed, one
record is read into primary storage.
The READ statement has, however, several other functions. Like the OPEN
statement, it performs certain checks. It checks the length of each input record to ensure
that it corresponds to the length specified in a RECORD CONTAINS clause in the data
DIVISION. If a discrepancy exists, an error message prints, and a program interrupt
occurs.
The READ statement will also use the BLOCK CONTAINS clause, if specified,
to perform a check on the blocking factor.
The AT END clause in the READ statement tests to determine if there is any more
input. An AT END clause of the READ statement tells the computer what to do if there is
no more data to be read.
Eg 8.5:
READ EMPLOYEE-FILE
AT END
MOVE YES TO END-OF-FILE.
WRITE statement
The WRITE instruction takes data in the output area defined in the DATA
DIVISION and transmits it to the device specified in the ENVIRONMENT DIVISION.
Note that although files are read, we write records. The record-name appear on the
01 level and is generally subdivided into fields. The record description specifies the
format of the output.
Eg 8.6:
WRITE EMPLOYEE-REC.
CLOSE statement
A CLOSE statement is coded at the end of the job after all records have been
processed to release these files and deactivate the devices. All files that have been opened
at the beginning of the program are closed at the end of a program. The CLOSE
statement, like the OPEN, will perform additional functions. When creating disk or tape
records, for example, the CLOSE will create trailer labels; it will also rewind a tape.
Eg 8.7:
CLOSE EMPLOYEE-FILE.
42
COBOL
COPY statement
A COPY statement is used to bring into a program a series of prewritten COBOL
entries that have been stored in a library. Copying entries from a library, rather than
coding them, has the following benefits : (1) it could save a programmer a considerable
amount of coding and debugging time; (2) it promotes program standardization since all
programs that copy entries from a library will be using common data-names and/or
procedures; (3) it reduces the time it takes to make modifications and reduces duplication
of effort; if a change needs to be made to a data entry, it can be made just once in the
library without the need to alter individual programs; and (4) library entries are
extensively annotated so that they are meaningful to all users; this annotation results in
better-documented programs and systems.
Most often, the COPY statement is used to copy FD and 01 entries that define and
describe files and records. In addition, standard modules to be used in the PROCEDURE
DIVISION of several programs may also be stored in a library and copied as needed.
Contents of EMP.REC
Eg 8.8a:
01
EMPLOYEE-REC.
05 EMP-NAME.
10 EMP-FIRST-NAME PIC X(10).
10 EMP-LAST-NAME PIC X(15).
05 EMP-DEPT
PIC X(4).
05 EMP-SALARY
PIC 9(5)V99.
05 EMP-DOJ
PIC 9(6).
43
COBOL
DATA DIVISION.
FILE SECTION.
FD EMPLOYEE-FILE
LABEL RECORDS STANDARD.
01 EMPLOYEE-REC.
05 EMP-NO
PIC 9(4).
05 EMP-NAME.
10 EMP-FIRST-NAME PIC X(10).
10 EMP-LAST-NAME PIC X(15).
05 EMP-DEPT
PIC X(4).
05 EMP-SALARY
PIC 9(5)V99.
05 EMP-DOJ
PIC 9(6).
WORKING-STORAGE SECTION.
01 WS-ANS
PIC X(01) VALUE "Y".
88 ANS-NO VALUE "N" "n".
PROCEDURE DIVISION.
0000-MAIN.
OPEN OUTPUT EMPLOYEE-FILE.
PERFORM 1000-ACPT-PARA UNTIL ANS-NO.
CLOSE EMPLOYEE-FILE.
STOP RUN.
1000-ACPT-PARA.
DISPLAY "ENTER YOUR EMP CODE : " WITH NO ADVANCING.
ACCEPT EMP-NO.
DISPLAY "ENTER YOUR FIRST NAME : " WITH NO ADVANCING.
ACCEPT EMP-FIRST-NAME.
DISPLAY "ENTER YOUR LAST NAME : " WITH NO ADVANCING.
ACCEPT EMP-LAST-NAME.
DISPLAY "ENTER YOUR DEPARTMENT : " WITH NO ADVANCING.
ACCEPT EMP-DEPT.
DISPLAY "ENTER YOUR SALARY : " WITH NO ADVANCING.
ACCEPT EMP-SALARY.
DISPLAY "ENTER YOUR DATE OF JOINING : " WITH NO ADVANCING.
ACCEPT EMP-DOJ.
WRITE EMPLOYEE-REC.
DISPLAY "DO YOU WANT TO ADD MORE RECORDS : "
WITH NO ADVANCING.
ACCEPT WS-ANS.
44
COBOL
45
COBOL
SELECT SORT-FILE
ASSIGN TO DISK.
:
DATA DIVISION.
FILE SECTION.
SD SORT-FILE.
01
SORT-REC.
05 S-EMP-NAME.
10 S-EMP-FIRST-NAME PIC X(10).
10 S-EMP-LAST-NAME PIC X(15).
05 S-EMP-DEPT
PIC X(4).
05 FILLER
PIC 9(13).
The SORT statement can, however, be used in conjunction with procedures that
process records just before they are sorted and/or process records after they are sorted.
INPUT PROCEDURE
The INPUT PROCEDURE processes data from the incoming file prior to sorting.
An INPUT PROCEDURE may be used to perform the following operations prior to
sorting : (1) validate data in the input records, (2) eliminate records with blank fields, (3)
count input records.
With COBOL 74, the procedure-name of an INPUT PROCEDURE must be a
section-name and not a paragraph-name. A section is a series of PROCEDURE
DIVISION paragraphs that is treated as a single entry or unit. Rule for forming sectionnames are the same as rules for forming paragraph-names. The word SECTION,
however, follows a section-name (e.g., A000-ERROR SECTION). The end of a section is
recognized when another section-name is encountered, or when the end of the program is
reached.
Code for an INPUT PROCEDURE
Eg 9.3:
SORT SORT-FILE
ON ASCENDING KEY S-EMP-DEPT
ON ASCENDING KEY S-EMP-NAME
INPUT PROCEDURE A000-TEST-IT
GIVING SORT-EMPLOYEE-FILE.
STOP RUN
A000-TEST-IT SECTION.
A100-PARA-1.
OPEN INPUT IN-FILE.
READ IN-FILE
AT END MOVE NO TO ARE-THERE-MORE RECORDS.
PERFORM A200-TEST-RTN
UNTIL THERE-ARE-NO-MORE-RECORDS.
CLOSE IN-FILE.
GO TO A300-TEST-IT-EXIT.
A200-TEST-RTN.
IF QTY = ZEROS
NEXT SENTENCE
46
COBOL
ELSE
MOVE IN-REC TO SORT-REC
RELEASE SORT-REC.
READ IN-FILE
AT END MOVE NO TO ARE-THERE-MORE RECORDS.
A300-TEST-IT-EXIT.
EXIT.
Explanation
1. The first section in the PROCEDURE DIVISION contains the SORT instruction,
any processing to be performed before or after the SORT verb is executed, and a
STOP RUN.
2. The second section begins with the main module of the INPUT PROCEDURE. It
opens the input file, reads the first record, and then performs a process routine (in
a separate paragraph within this second section) until there is no more data.
3. After the separate paragraph is executed until ARE-THER-MORE-RECORDS =
NO, control returns to the main module of the second section to be terminated,
control must pass to the last statement within the section. This means that a GO
TO is required. We code GO TO A300-TEST-IT-EXIT as the last sentence. Since
no operations are required in this last paragraph, EXIT is coded, which passes
control back to the SORT statement, where the file is then sorted.
OUTPUT PROCEDURE
The OUTPUT PROCEDURE is used to process the sorted records prior to, or
perhaps even instead of, placing them in the output file. The OUTPUT PROCEDURE
can be used instead of the GIVING option. The OUTPUT PROCEDURE is similar to the
INPUT PROCEDURE. When the INPUT PROCEDURE is complete, the file is then
sorted. An OUTPUT PROCEDURE processes all sorted records in the sort file and
handles the transfer of these records to the output file.
In an INPUT PROCEDURE we RELEASE records to a sort file rather than
writing them. In an INPUT PROCEDURE we RETURN records from the sort file rather
than reading them.
Merging
The MERGE statement combines two or more files into a single file. Its format is
similar to the SORT. The file to be merged is a work file designated as an SD. At least
two file-names must be included for a merge, but more than two are permitted. Unlike,
the SORT, however, an INPUT PROCEDURE may not be specified with the MERGE
statement. That is, using the MERGE statement, you may only process records after they
have been merged, not before. The OUTPUT PROCEDURE has the same format as with
the SORT.
Eg 9.4:
MERGE MERGE-FILE
ON ASCENDING KEY M-EMP-DEPT
USING OLD-PAYROLL
NEW-PAYROLL
47
COBOL
GIVING EMPLOYEE-FILE.
The possible values that may be placed in the FILE STATUS field when an input
or output operation is performed are listed in Appendix E.
OPEN INPUT EMPLOYEE-FILE.
IF WS-STATUS NOT = 00
DISPLAY ERROR OPENING EMPLOYEE FILE
STOP RUN.
READ EMPLOYEE-FILE .
:
:
48
COBOL
49
COBOL
12.Indexed Files
An indexed file is really two files the data file, which is created in sequence but
can be accessed randomly, and the index file, which contains the value of each key field
and the disk address of the record with that corresponding key field. To access an indexed
record randomly, the key field is looked up in the index file to find the disk address of the
record; then the record is accessed in the indexed data file directly.
The index on a disk is similar to a books index, which has unique subjects (keys)
and their corresponding page numbers (addresses). There would be two ways to find a
topic in the book. You can read the book sequentially, from the beginning, until that topic
is found, but this would be very time consuming and inefficient. The best method would
be to look up the topic in the index, find the corresponding page number, and go directly
to that page. This is precisely how records can be accessed on a disk file that has an
index.
With an indexed file, records can be accessed either sequentially or randomly,
depending on the users needs. The term random access implies that records are to be
processed or accessed in some order other than the one in which they were physically
written on the disk.
50
COBOL
Eg 12.1:
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT IND-EMP-FILE
ASSIGN TO INDEMP.DAT
ORGANIZATION IS INDEXED
ACCESS IS SEQUENTIAL
RECORD KEY IS I-EMP-NO.
DATA DIVISION.
FILE SECTION.
FD IND-EMP-FILE
LABEL RECORDS STANDARD.
01
IND-EMP-REC.
05 I-EMP-NO
PIC 9(4).
05 I-EMP-NAME
PIC X(25).
05 I-EMP-DEPT
PIC X(4).
05 I-EMP-SAL
PIC 9(5)V99.
With READ
When reading a disk file randomly, we do not test for an AT END condition
because we are not reading the file in sequence; instead, we include an INVALID KEY
test. If there is no record in the INDEXED-FILE with a RECORD KEY equal to T-EMPNO, the INVALID KEY clause will be executed.
Eg 12.3:
DISPLAY ENTER EMPLOYEE CODE :
ACCEPT T-EMP-EMP-NO.
MOVE T-EMP-NO TO I-EMP-NO.
READ IND-EMP-FILE
INVALID KEY
PERFORM 600-ERR-RTN.
51
COBOL
DELETE verb
The DELETE verb can be used to delete records from indexed files. Note that we
use the file-name with the DELETE verb, but the word RECORD can be specified as
well. That is, both the statements DELETE INDEXED-FILE and DELETE INDEXEDFILE RECORD can be used to delete the record in the INDEXED-FILE storage area.
To delete a record from an indexed file, you should first read the record into
storage and then instruct the computer to delete it.
Eg 12.4:
MOVE Y TO WS-FOUND.
MOVE 1001 TO I-EMP-NO.
READ IND-EMP-FILE
INVALID KEY
MOVE N TO WS-FOUND.
IF WS-FOUND = Y
DELETE IND-EMP-FILE
INVALID KEY
DISPLAY ERROR DELETING RECORD.
52
COBOL
DIVISION , we can access records by either I-EMP-NO , the record key, or I-EMPDEPT, the alternate key.
The KEY clause is used with the READ statement when an indexed file has
ALTERNATE RECORD KEYs that we want to use to randomly access a record. If the
KEY clause is omitted when accessing a file randomly, the RECORD KEY is assumed to
be the KEY used for finding the record.
Suppose ALTERNATE RECORD KEY WITH DUPLICATES was specified in
the ENVIRONMENT DIVISION and there is more than one record with the same
ALTERNATE RECORD KEY. The first one that was actually placed on the disk will be
the one retrieved by the READ.
COBOL
ALTERNATE RECORD KEY. Also, when records ate to be accessed by both RECORD
KEY and ALTERNATE RECORD KEY, use ACCESS IS DYNAMIC.
54
COBOL
13.Table Handling
Use of OCCURS clause
1. An OCCURS clause is used in COBOL to indicate the repeated occurrence of
fields with the same format.
2. Defining a series of totals in WORKING-STORAGE to which amounts are
added; after all data is accumulated, the total can be printed.
3. Defining a table in WORKING-STORAGE to be accessed by each input record.
For example, using the contents of some input field to look up the required data
in the table.
Eg 13.1:
01
TEMP-REC.
05 TEMPERATURE OCCURS 24 TIMES
PIC S9(3).
Subscript
A subscript is used in the PROCEDURE DIVISION to indicate which specific
item within the array we wish to access.
The subscript is used along with the identifier that is defined with an OCCURS, to
refer to an item within an array.
Eg 13.2:
MOVE TEMPERATURE (2) TO TEMP-OUT.
55
COBOL
Eg 13.3:
01 MONTH-NAMES.
05 STRING-1
PIC X(36) VALUE
JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC.
05 MONTH REDEFINES STRING-1 OCCURS 12 TIMES PIC XXX.
However, unlike a subscript, an index is not defined separately in WORKINGSTORAGE. The compiler automatically provides an appropriate PICTURE clause. An
index is processed more efficiently than a subscript, because the index contains the
displacement from the start of the table.
A SEARCH statement does not automatically initialize the index at 1 because
sometimes we may want to begin searching a table at some point other than the
beginning. Initializing an index at 1 must be performed by a SET statement prior to the
SEARCH.
Eg 13.5:
SET X1 TO 1.
SEARCH TABLE-ENTRIES
AT END MOVE 0 TO WS-SALES-TAX
WHEN ZIP-IN = WS-ZIPCODE (X1)
COMPUTE ........
An index can be used to reference an element only in the table or array for which it
was defined.
With 2 WHEN clauses, the computer begins by performing the first comparison. Only
if the condition in the first WHEN is not met does it test the second WHEN.
56
COBOL
To search for multiple matches in a table, it is better to use a PERFORM rather than a
SEARCH statement for processing the entire table.
If you have parallel table with CUST-NO-TABLE storing 25 customer numbers and
CUST-ARRAY storing the corresponding BAL-DUE for each. In such a case the
SEARCH... VARYING can be used.
Eg 13.6:
SET X1, X2 TO 1.
SEARCH EACH-CUST-NO VARYING X2
AT END PERFORM 300-ERR-RTN
WHEN CUST-NO-IN = EACH-CUST-NO (X1)
ADD AMT-IN TO BAL-DUE (X2).
Binary search
When table entries are arranged in sequence by some field, such as T-CUSTOMERNO, the most efficient type of look-up is a binary search. The SEARCH ALL verb is
used to perform a binary search. A SET statement is not necessary with the SEARCH
ALL, since the computer sets the index to the appropriate point initially when each binary
search begins.
To use the SEARCH ALL statement, we must indicate which table entry will serve as
the key field. The identifier used in the ASCENDING KEY clause must be an entry
within the table and it must appear before the INDEXED BY clause.
Eg 13.8:
01 TABLE-1.
05 DISCOUNT-TABLE OCCURS 50 TIMES
ASCENDING KEY T-CUSTOMER-NO
INDEXED BY X1.
10 T-CUSTOMER-NO PIC 9(4).
10 T-DISCOUNT-PCT PIC V999.
57
COBOL
Eg 13.9:
01 INVENTORY-TABLE.
05 WAREHOUSE OCCURS 50 TIMES INDEXED BY X1.
10 ITEM-X OCCURS 100 TIMES INDEXED BY X2.
15 PART-NO
PIC 9(4).
15 UNIT-PRICE PIC 999V99.
The identifier used with the SEARCH refers to the lowest-level OCCURS entry.
e.g. SEARCH ITEM-X.
Note that SEARCH ITEM-X increments the lowest-level index only. Hence if X1 is set
to 1 initially, the SEARCH will perform a look-up on items in warehouse 1 only, that is
(1,1) to (1,100).
To search all warehouses, the major index X1 must be incremented.
58
COBOL
14.Call statement
Structured programs should consist of a series of independent modules that are
executed from the main module.
When programs are properly structured :
1. Each module may be written, compiled, and perhaps even tested
independently.
2. The modules may be written in different stages, in atop-down manner.
They may even be coded by different programmers.
3. If a specific module needs to be modified, the entire logical flow should
still function properly without the need for extensive revision to other
parts of the program.
Modules within a program can be viewed as subroutines that are called or
executed from the main module. But a program may also CALL or reference independent
subprograms stored in a library that are entirely separate from the main program itself.
The main program that references or calls a subprogram is referred to as the calling
program. The subprogram that is linked and executed within the main program is referred
to as the called program.
The called program would need to be compiled so that it may be called when
needed.
When the CALL is performed, data is passed from the calling to the called program (if
the calling program has assigned values to fields used in the called program). The
entire called program is executed, data is passed from the called program back to the
calling program, and control return to the calling program.
LINKAGE SECTION
A LINKAGE SECTION must be defined in the called program for identifying those
items that (1) will be passed to the called program from the calling program and (2)
passed back from the called program to the calling program. The LINKAGE SECTION
of the called program, then, describes all items to be passed between the two programs.
The LINKAGE SECTION, if used, is coded after the FILE and WORKING-STORAGE
SECTIONs of the called program. This section is similar to WORKING-STORAGE
except that VALUE clauses from initializing fields are not permitted in the LINKAGE
SECTION.
59
COBOL
EXIT PROGRAM
The last executed statement in the called program must be the EXIT PROGRAM. It
signals the computer to return control back to the calling program. With COBOL 74,
EXIT PROGRAM must be the only statement in the last paragraph.
60
COBOL
15.String Handling
The STRING Statement
A STRING statement may be used to combine several fields to form once concise
field. This process is called concatenation.
05 NAME.
10 LAST-NAME
PIC X(10) VALUE EDISON.
10 FIRST-NAME PIC X(10) VALUE THOMAS.
10 MIDDLE-NAME PIC X(10) VALUE ALVA.
01 NAME-OUT
PIC X(33).
STRING
FIRST-NAME DELIMITED BY
DELIMITED BY SIZE
MIDDLE-NAME DELIMITED BY
DELIMITED BY SIZE
LAST-NAME DELIMITED BY
DELIMITED BY SIZE
INTO NAME-OUT.
Output
NAME-OUT = THOMAS ALVA EDISON
OVERFLOW Option
The OVERFLOW option specifies the operation(s) to be performed if the receiving
field is not large enough to accommodate the result.
POINTER Option
We may count the number of characters actually moved to the receiving field if it is
initialized at zero.
01 WS-COUNT PIC 99 VALUE 0.
MOVE 1 TO WS-COUNT.
STRING FIRST-NAME DELIMITED BY
INTO NAME-OUT
WITH POINTER WS-COUNT.
Output
WS-COUNT = 6
Rules for using the STRING statement
1. The DELIMITED BY clause is required. It can indicate :
SIZE : The entire sending field is transmitted.
61
COBOL
2.
3.
4.
5.
62
COBOL
The INSPECT statement
The INSPECT statement may be used for replacing a specific character in a field with
another character. It can also be used for counting the number of occurrences of a given
character.
01 CTR-1
PIC 9 VALUE 0.
01 WS-NAME PIC X(10).
ACCEPT WS-NAME.
INSPECT WS-NAME TALLYING CTR-1 FOR ALL SPACES.
This code will check for the number of spaces in the field WS-NAME and store the
value in the field CTR-1.
Applications of the INSPECT statement
1. To count the number of occurrences of a given character in a field.
2. To replace specific occurrences of a given character with another
character.
63
COBOL
Appendix A (Assignments)
Each assignments carries 30 marks each.
Breakup up of marks
Flowchart/Logic 5
Standards - 5
Coding 10
Error Handling - 5
Output - 5
64
COBOL
Assignment Set 1
Daywise breakup
Day
Minimum Additional
1
1
2
2
1,2
3a
3
3a
4a
4
3b
4b
5
5,6/7
15
6
8
9/10
7
12
8
13
9
*
*
* as per set 2
Objective: To provide Cobol assignments to training participants in a real word Cobol
application system. This is a basic system without minimum functional
complexities.
Intro:
A company named "ABC Co. Ltd" manufactures computer parts and sells them.
The company's stockyard gets orders collected by marketing department.
Everyday the stockyard receives the material produced or bought out
through manufacturing department. These are received through a document
called "Goods receipt Note" (GRN). The GRN's are updated on to stock
master at the end of the day.
Marketing gets the stock status every day after the updation of GRN. Based
on the stock position, order balance, customer priority etc., marketing sends
delivery instructions to the Stockyard. The delivery instruction contains
which order to process along with the items and quantities. The stockyard
prints the invoice from the DI and this also reduces the stock balance.
At the end of the month a fresh stock master file is created and the last
months file is taken to backup.
Files are created, updated and Reports are generated from these data.
65
COBOL
1.
IT-ITEMNO
Itemno
pic x(6)
IT-DESC
IT-MONOPBAL
IT-RCPTQTY
IT-DESPQTY
IT-RATE
IT-PROCMY
Item desc
Item month op. Bal qty
Item month receipts qty
Item month dispatch qty
Item rate
Processing MMYYYY
Logic :
The data should be of a record structure as above.
Item class can have values as multiples of 10 from 10 90 inclusive only.
Input itemno, Item desc, Item month op.Balqty, Item rate & processing mmyyyy of
the data above. Month receipts & month dispatch should be initialized to zero when
new item is created. Once the data of a record is complete, the program should
display the full group as an item.
The program should then ask the user Do you want to Input More (Y/N). It should
accept the users response.
If the response is Y, the program should accept the details on another item and
repeat the above steps .
If the response in N, the program should stop.
2. Write a program to input the data given below.
Program-Id : COBASS02
CU-CUSTNO
CU-CUSTNAME
CU-ADDLIN1
CU-ADDLIN2
CU-REGION
CU-MAXCR
CU-CURRBAL
Logic :
66
COBOL
Input all items of the data above. Once the data of a record is complete, the program
should display the full group as an item.
The program should then ask the user Do you want to Input More (Y/N). It should
accept the users response.
If the response is Y, the program should accept the details on another customer and
repeat the above steps .
If the response in N, the program should stop.
3. Modify program cobass01 to have three choices as listed below. The program
should function as per the steps of choices listed below.
Program-Id : COBASS03
A . Input Data
B. Print Data
Q. Quit.
Input data :
Open the file itemseq.dat in extend mode.
The data is entered as in prog. 1 but instead of displaying on the screen it is to be
written to a sequential file named itemseq.dat with the same format as the
group.
When the user enters Y to Do you want to enter more (y/n) ?, the program
should once again take input and write to file.
With user input as N, the program should close files and go back and display
the menu once again.
Print Data
The program should open the file itemseq.dat in sequential input mode and the
itemrep.dat in output mode.
It should read the data sequentially until eof.
For every valid record read, it should print as per the format given below.
There should be a max of 66 lines per page. The Run Date is the system date and
the month/ Year is the mmyyyy of the data in itemseq.dats first record.
At the end of the report, a grand total of the value filed field should be printed and
all files closed.
67
COBOL
ABC CO. LTD.
Date : dd/mm/yyyy
List of Items in Stock For <month > / Year
Page : 999.
<------------ Month Details -------------
Itemno Item Description
Op.Bal Receipts Dispatch
Clo-Bal. Rate Clo. Value
xxxxxx xxxxxxxxxxxxxxxxxxxx
:
:
:
:
:
:
:
:
999999
:
:
:
:
999999
:
:
:
:
999999
:
:
:
:
999999
:
:
:
:
999.99
:
:
:
:
9999999.99
:
:
:
:
--------------------99,999,999.99
---------------------
Totals :
Quit :
The program should stop run.
4. Modify program cobass02 to have three choices as listed below. The program
should function as per the steps of choices listed below.
Program-Id : COBASS04
A.
B.
Q.
Input Data
Print Data
Quit.
Input data :
Open the file custseq.dat in extend mode.
The data is entered as in prog. 2 but instead of displaying on the screen it is to be
written to a sequential file named custseq.dat with the same format as the
group.
When the user enters Y to Do you want to enter more (y/n) ?, the program
should once again take input and write to file.
With user input as N , the program should close files and go back and display
the menu once again.
Print Data
The program should open the file custseq.dat in sequential input mode and the
custrep.dat in output mode.
It should read the data sequentially until eof.
For every valid record read, it should print as per the format given below.
There should be a max of 66 lines per page. The Run Date is the system date .
68
COBOL
At the end of the report, a grand total of the value filed field should be printed
and all files closed.
Date : dd/mm/yyyy
Page : 999
Credit-Limit Current Bal.
:
:
:
:
:
:
:
:
:
:
:
:
Totals :
9,99,999.99
:
:
:
:
--------------------99,999,999.99
---------------------
:
:
:
:
Quit :
The program should stop run.
5. Printing Item Class wise Report.
Program-id : COBASS05
This programs takes the itemseq.dat cretaed in assignment 3 and prints a control
break report on the itemclass (1st two bytes of the itemno field) as per the format
given below.
Item's Classes are as follows :10 Internal Components, 20 - Input Devices, 30 - Cards Boards, 40 Storage
Devices, 50 Output Devices, 60 Cables, 70 Storage Media
ABC CO. LTD.
Item Class wise Report
Itemno
Item Description
Item : xxxxxxxxxxxxxxxxxxxx
xxxxxx xxxxxxxxxxxxxxxxxxxx
:
:
:
:
Item Total :
Date : dd/mm/yyyy
Page : 999.
<------------ Month Details -------------
Op.Bal Receipts Dispatch
Clo-Bal. Rate Clo. Value
999999
:
:
999999 999999
999999 999.99
:
:
:
:
:
:
:
:
---------------------------------------9999999
99,999,999.99
----------------------------------------
69
9999999.99
:
:
COBOL
Item : xxxxxxxxxxxxxxxxxxxx
xxxxxx xxxxxxxxxxxxxxxxxxxx
:
:
:
:
Item Total :
Grand Total :
999999
:
:
999999 999999
999999 999.99 9999999.99
:
:
:
:
:
:
:
:
:
:
-------------------------------------9999999
99,999,999.99
----------------------------------------------------------99,999,999.99
-------------------
COBOL
Transactions Created = and
Transactions Rejected =
8. Updation of Index file itemmast.dat from a sequential file GRN.DAT .
Program-Id : COBASS08
A file called Goods receipt note has data of the days receipts of various items which
have been manufactured. The structure of Sequential GRN file is as below;
GR-GRNNO
GR-DATE
GR-ITEMNO
GR-QTYMFD
Grn No.
Date
Itemno
Qty. Mfd
pic x(5)
pic 9(8) format ddmmyyyy
pic x(6)
pic 9(5).
Logic steps :
1. Take processing dd mm yyyy as input.
2. Check if grnddmmyy.dat contains data for the date input. If not, then display suitable
message and stop run , otherwise continue on to step 3.
3. Read a record from the GRN, fetch the corresponding item record from itemmast.dat
using item as the key. If the record is not found, display a suitable message Item not
found in the item master.. Skipping + itemno.
4. If found then add the qty. mfd to receipts qty.
5. Read the next GRN record and reapeat 2 thru 5 until end of file of GRN data.
9. Order booking by Marketing for a customer ( Existing ).
Program-Id : COBASS09
Layout of ORDERS.DAT.
ORD-ORDNO
ORD-DATE
ORD-CUSTNO
ORD-TOTVALUE
ORD-TX1-PER
ORD-TX2-PER
ORD-TX3-PER
ORD-TOTSUPVAL
ORD-CUSTREFNO
ORD-STATUS-TAG
Layout of
Order Number
Order date
Order Customer no.
Order Total Value
Tax Percentage Tax 1
Tax Percentage Tax 2
Tax Percentage Tax 3
Order Total Supplied Value
Customer Order Ref. No.
Order Status Tag
ORDITEM.DAT
71
x(5)
Record Key
9(8)
yyyymmdd
x(6)
9(7)v99
99v99
99v99
99v99
9(7)v99
x(10).
9 0 New, 1-Partly Supplied
2 Fully Supplied.
COBOL
OIT-ORDNO
Order No.
OIT-ITEMNO
OIT-ITEMNO1
Item Number
Item Number
x(5)
OIT-KEY
Record Key
x(6).
x(6).
OIT-ALTKEY-1
Alternate Key with duplicates
OIT-DATE
Order date
9(8) yyyymmdd
OIT-QTY
Item Order Quantity
9(6)
OIT-UOQ
Item UOQ
X(3)
OIT-RATE
Item Negotiated Rate
9(5)v99.
OIT-QTYSUPP
Item Qty. Already Supp
9(6).
OIT-AMTBILL
Item Value already Billed
9(7)v99.
OIT-STATUS-TAG
Order-Item Status Tag
9
0 New,
1-Partly Supplied
2 Fully Supplied.
This program is available to you as cobass08. The program takes input from
keyboard of a customers order and creates the order on an index file called Orders.dat
with order header information. The details of the items of the order are kept in a order
child table called ORDITEM.DAT.
You may use this program to enter data of orders or to view existing data. The
program takes care of proper input with validation before accepting the order.
You can change the order only if the status tag is 0, viz. New.
Note : This can also be done using one file with two formats, i.e two level 01 record
description having some common fields and rest depending on the data. One
record describing the contents of order.dat and the other describing the
contents of orditem.dat.
10. Delivery Instruction preparation by marketing for items shipment from
Stockyard (Existing).
Program-Id : COBASS10
Layout of "DELVINST.DAT"
DI-DINO
DI-ITEMNO
DI-DATE
DI-ORDNO
DI-INVOICE NO.
DI-QTY
Order no.
Corres. Invoice No.
Quantity
72
9(6).
Record Key
9(8) yyyymmdd
ALTKEY-1
x(6).
x(6).
9(6).
COBOL
DI-FREIGHTPER
DI-DELMODE
DI-PACKMODE
DI-STATUS
Freight Percentage
Deliery Mode
Packing Mode
DI Status
99v99.
xx.
xx.
9
( Sequential File )
Invoice No.
9(6).
Customer No.
x(6).
Invoice Date
9(8). yyyymmdd
Order no.
x(6).
Delv. Inst No.
9(6).
Itemno
x(6).
Quantity
9(6)
Rate
9(5)v99
Item Value (Qty*Rate)
9(7)v99
Bill Amount (Item Value + taxes)
9(7)v99
Tax1 Amount
9(5)v99.
Tax2 Amount
9(5)v99.
Tax3 Amount
9(5)v99.
Freight Amount
9(5)v99.
Customer Region Code
xxx.
Customer Order Ref. No.
x(6).
Paymode mode for Customer 9
Delivery Mode
xx.
Packing Mode
xx.
The Program accepts the date of run and prints the invoices from the
Delv.Instruction file for the date which is input and not already processed. It
bypasses all other dates.
Logic :
73
COBOL
Step 1 : Input the processing date as ddmmyyyy .
Step 2 : Start the Difile.dat from key = input date +" " +" " as ordno, and itemno
as blanks. Handle error if not found.
Step 3 : Read the Difile.dat sequentially. Check if the Printed Tag is 1, if so
bypass the record. and read the next record.
Step 4 : For the first valid Delv.Inst record, fetch the corresponding order record
from orders.dat by order no and the customer record from custmast.dat by custno.
Print the Invoce heading as per the sample below.
Step 5 : For the item of the invoice fetch the corresponding item record item from
itemmast, print the item details, take sum of required fields. Viz. Values. Update
the tag of DI to processed and invoice number. In itemord.dat update status tag
and quantity supplied.
Step 6. Read the next DI record. If it is for the same Date & order, Repeat step 5.
Repeat step 6 till all items of the order are over, of the end of file has reached.
Step 7. At Change of order print the various Tax amounts and update the
orditem.dat with the remaining qty. for each item. If all the ordered qty. is supplied
then make the order tag as complete in orders.dat.
dd/mm/yyyy
Date :
Page : 999.
Ord-Qty.
Rate
UOQ
xxx
dd/mm/yyyy
999999
xxx
999.99
999999
999.99
9999999.99
dd/mm/yyyy
xxx
999999
999.99
9999999.99
:
74
COBOL
:
:
-----------9999999
------------
Item Totals :
xxxxxx xxxxxxxxxxxxxxxxxxxx
9999999.99
dd/mm/yyyy
--------------------99,999,999.99
-------------------xxx
dd/mm/yyyy
999999
xxx
999.99
999999
999.99
9999999.99
dd/mm/yyyy
xxx
999999
999.99
9999999.99
:
:
:
Item Totals :
-----------9999999
------------
Grand Total :
--------------------99,999,999.99
-------------------99,999,999.99
The program asks for input of start date and end date. It should do a date check of the
two dates.
It then starts the orditem.dat file to the start date using the alternate keys ito-altkey-1
(Itemno + Date ). It should also handle error in case of error in start.
The program should then access the data sequentially. Verify that the data is for the
dates in the range, if not then skip the records.
For a valid record, If it is the 1st record of the item, then print the ItemNo and the Item
description (which you get from "itemmast.dat" ). Otherwise, for other records, print
the details without the Itemno and description.
Take totals of the order-value and quantity. At the change of item print the Order total
as per the report on top.
At the end of the report print the last order total and the grand total of the value only.
The reading of the file continues until eof.
13. Region wise Item wise Sales Report
Program-id : COBASS13
This program prints the Region wise Actual Sales Report for a given period. The
report takes data from invoice.dat and prints in the format given below.
ABC CO. LTD.
Date : dd/mm/yyyy
Region wise Item Sales Report From dd/mm/yyyy to dd/mm/yyyy
Page : 999.
75
COBOL
Itemno Item Description
Bill-Amount
Qty.
Rate
Item-Value
Tax-Amt
999999
999.99
9999999.99
99999.99
999999
999.99
9999999.99
99999.99
Region : xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxx xxxxxxxxxxxxxxxxxxxx
9999999.99
xxxxxx xxxxxxxxxxxxxxxxxxxx
9999999.99
:
:
Item Totals :
9999999.99
999999
9999999.99
99999.99
Region : xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxx xxxxxxxxxxxxxxxxxxxx
9999999.99
xxxxxx xxxxxxxxxxxxxxxxxxxx
9999999.99
999999
999.99
9999999.99
99999.99
999999
999.99
9999999.99
99999.99
:
:
Item Totals :
999999
9999999.99
99999.99
Grand Totals :
999999
9999999.99
99999.99
9999999.99
9999999.99
The program takes a sorted file called invsort.dat which is sorted on region and
item from the invoice.dat. file. It should asks for input of start date and end date
and do a date check of the two dates.
The program should access the data in invsort.dat sequentially. Verify that the data
is for the dates in the range, if not, skip the records.
For a valid record, If it is the 1 st record of a new Area it should print the Area Header
Line . Also the Area header line is to be printed on each page as part of the header.
The program should print the item totals at the break of each Item for an area. Also it
should print the Area total for the break in Area.
Take totals of the item quantity, item value ( Qty * Rate ), Tax amount and Bill
amount. At the change of item print the Item total as per the report on top.
76
COBOL
At the end of the report print the last item total and the last Area total before the
grand total of all values. The reading of the file continues until eof.
14. Item wise Region wise Summary Sales Matrix Report
Program-id : COBASS14
This program prints a matrix report of items and their region wise values in the format
given below, where there are a maximum of 7 regions and 20 item nos. This takes data
from "invoice.dat". The output should be in the order of Item number.
ABC CO. LTD.
dd/mm/yyyy
Item Wise Region wise Sales Summary From dd/mm/yyyy to dd/mm/yyyy
999.
Item No.
Item Description
Page :
xxxxxx
9,999.99 9,999.99 9,999.99 9,999.99 9,999.99
xxxxxxxxxxxxxxx
xxxxxxx
9,999.99 9,999.99 9,999.99 9,999.99 9,999.99
xxxxxxxxxxxxxxx
:
:
:
:
:
:
:
:
:
:
:
:
:
:
:
:
:
:
:
:
:
:
:
:
Total
Date :
Logic : Write the logic statements yourself. Draw the flow chart before coding.
15. Write a program to print the following report using the file created in program
COBASS2.
ABC CO. LTD.
Date : dd/mm/yyyy
Region wise report
Region : XXX
Customer Name
xxxxxxxxxxxxxxxx
Address
xxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxx
:
:
Total customers in XXX : 999
77
COBOL
Region : XXX
Customer Name
xxxxxxxxxxxxxxxx
Address
xxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxx
:
:
Total customers in XXX : 999
-*-
78
COBOL
Assignment Set 2
Daywise breakup
Day
Minimum
1
1
2
3
3
4.1
4
4.2
5
6,7
6
8,9
7
10
8
12
9
13,14
1.
Additional
2
5
11
15
Program-Id : STUASS01
ST-ROLLNO
ST-NAME
ST-CLASS
Student rollno
Student name
Student class
ST-SUB1-MARKS
ST-SUB2-MARKS
ST-SUB3-MARKS
ST-FEES-PAID
Marks of subject 1
Marks of subject 2
Marks of subject 3
Fees paid
pic 9(4)
pic x(15)
pic x(3)
First 2 digits Std
3rd character division.
pic 9(3).
pic 9(3).
pic 9(3).
pic 9(4)
Logic :
79
COBOL
2. Write a program to input the data given below.
Program-Id : STUASS02
MNT-ROLLNO
MNT-FLAG
UPDATION FLAG
MNT-NAME
STUDENT NAME
pic 9(4)
pic x
A-Add
M-Modify (only name can be modified)
D-Delete
PIC X(15)
Logic :
3.
Program-Id : STUASS03
Grades are awarded on the following basis :
Percentage
Grade
>= 70
DIST
60.70
CRDT
50.60
PASS
<50
FAIL
If a student scores below 40 in any subject, award a FAIL grade.
At the end display the no. of students passed and failed.
80
COBOL
4.
Modify program STUASS01 to have three choices as listed below. The
program should function as per the steps of choices listed below.
Program-Id : STUASS04
A . Input Data
B. Print Data
C. Quit.
Input data :
Open the file studseq.dat in extend mode.
The data is entered as in STUASS01 but instead of displaying on the screen it is to be
written to a sequential file named studseq.dat with the same format as the group.
When the user enters Y to Do you want to enter more (y/n) ?,
the program
should once again take input and write to file.
With user input as N , the program should close files and go back and display the
menu once again.
Print Data
The program should open the file studseq.dat in sequential input mode and the
studseq.dat in output mode.
Accept the class from the user & print a report for all students in the class.
For every valid record read, it should print as per the format given below.
There should be a max of 5 lines per page.
The report should be printed in sequence of Rollno.
At the end of the report, a grand total of the value filed field should be printed and all
files closed.
Date : dd/mm/yyyy
Scholars Academy
Marksheet for Standard : 99 Division :X
-----------------------------------------------------------------------------------------------------Rollno
Student Name
Subject
Subject
Subject
Grade
1
2
3
-----------------------------------------------------------------------------------------------------9999
XXXXXXXXXXXXXXX
999 999
999 XXXX
:
:
:
:
:
:
:
:
:
:
:
:
:
:
:
:
:
:
-------81
COBOL
Total no. of students :
999
--------
Quit :
The program should stop run.
5.
Program-Id : STUASS05
6.
Program-Id : STUASS06
Scholars Academy
List of students
--------------------------------------------------------------------------------------------------------STD : 99
--------------------------------------------------------------------------------------------------------RollNo
Name
--------------------------------------------------------------------------------------------------------9999
XXXXXXXXXXXXXXX
:
:
:
:
-----Total No. of students in Std 99 :
99
---------------------------------------------------------------------------------------------------------------STD : 99
----------------------------------------------------------------------------------------------------------RollNo
Name
----------------------------------------------------------------------------------------------------------9999
XXXXXXXXXXXXXXX
:
:
82
COBOL
:
-----99
---------------------------------------------------------------------------------------------------------------Total No. of students in Std 99 :
:
:
:
:
:
:
:
:
:
---------------------------------------------------------------------------------------------------------Total no. of students in the school : 999
---------------------------------------------------------------------------------------------------------7.
Program-Id : STUASS07
Scholars Academy
Consolidated Marksheet
--------------------------------------------------------------------------------------------------------STD : 99
----------------------------------------------------------------------------------------------------------Div : A
RollNo
Name
Grade
Name
XXXXXXXXXXXXXXX
:
:
:
Grade
XXXX
:
:
:
------Total No. of students in Div B :
999
--------------------------------------------------------------------------------------------------------Total No. of students in Std 99 :
999
---------------------------------------------------------------------------------------------------:
:
:
:
:
:
83
COBOL
:
:
:
:
:
:
------------------------------------------------------------------------------------------------------Distinction : 99
Credit
: 99
Pass
: 99
Fail
: 99
8.
Indexed files
Program-Id : STUASS08
Note : Take the format for studseq.dat from program STUASS01 and create the
studmast.dat in the same format, except that the field name prefix ST- should be
replaced with STM-.
Read the sequential file studseq.dat and create an indexed file studmast.dat
with the same format as the input file, and having index keys as ;
STM-ROLLNO as the record Key.
STM-CLASS as the alternate record key.
The program should take care of erroneous transaction like, invalid class and
duplicates or junk transactions (Blank records ) etc. write the errorneous records to
the file studerr.dat . This file will have an additional field
Remark
Pic X(15)
The values for remark can be any of the following
Duplicated
Out of sequence
The access mode of the file should be sequential.
At the end of program it should display the following
Student Details Entered
=,
Student Records Created = and
Student Records Rejected =
9.
Program-Id : STUASS09
Accept a the CLASS from the user.
Print a report for the given CLASS.
84
COBOL
10. Using the files created in program STUASS05 (mntseq.dat) and STUASS08
(studmast.dat).
Program-Id : STUASS10
Read a record from the maintenance file (mntseq.dat).
For each record read, add/modify/delete the record in the master file (studmast.dat).
Repeat this till the end of the maintenance file.
11. Using the file created in program STUASS04 (studseq.dat). This program will
have 3 options, as mentioned below :
Program-Id : STUASS11
A. Create transaction
B. Update Master
C. Exit
Create transaction
Write a program to create the following file (studtran.dat)
Rollno
PIC 9(4)
Fees_paid
Pic 9999
Note : Enter some invalid rollnos. i.e. which do not exist in the studseq.dat.
There can be multiple transaction records for a student.
Update Master
Write a program to update the studseq.dat file using the studtran.dat.
12.
For each Class(irrespective of division) find the highest scorer in each
subject.
Program-Id : STUASS11
Print the details in the following format
Class
Subject 1
Subject 2
Subject 3
Max
Name
Max
Name
Max
Name
------------------------------------------------------------------------------------------------99
99
XXXXX
99
XXXXX
99
XXXXX
:
:
:
:
:
:
:
:
:
:
:
:
:
:
------------------------------------------------------------------------------------------------Assumption : There is only 1 highest scorer in each class.
85
COBOL
13. Write a program to accept a company name and display it in the center of the
screen.
Note : The user may enter leading/trailing spaces.
14. Modify the second option (Print Data) of the program STUASS04 to receive the
class from the main program and print the report.
15. Accept details from the user in the following format :
StreetNo
StreetName
City
Pincode
pic 9(3)
pic x(15)
pic x(10)
pic 9(6)
86
COBOL
Appendix B (Standards)
For the COBOL standards refer to PKMS
QMS
QMS-Manual
Standards
COBOL Standards
87
COBOL
Appendix C (Bibliography/References)
1. M. K. Roy and D Ghosh Dastidar, COBOL Programming including MS-COBOL
and COBOL-85 2nd edition
2. Andreas S. Philippakis and Leonard J. Kazmier, Information Systems through
COBOL 2nd edition
3. Nancy Stern and Robert A. Stern, Structured COBOL Programming - 7th edition
88
COBOL
89
COBOL
Appendix F (Syntax)
RULES FOR INTERPRETING INSTRUCTION FORMATS
Uppercase words are COBOL reserved words that have special meaning to the compiler.
Underlined words are required in the paragraph.
Lowercase words represent user-defined entries.
Braces { } denote that one of the enclosed items is required.
Brackets [ ] mean the clause or paragraph is optional.
If punctuation is specified in the format, it is required.
The use of dots or ellipses (...) means that additional entries of the same type may be included if desired.
IDENTIFICATION DIVISION.
PROGRAM-ID. Program-name.
[AUTHOR. [Comment-entry]....].
[INSTALLATION. [Comment-entry]....].
[DATE-WRITTEN. [Comment-entry]....].
[DATE-COMPILED. [Comment-entry]....].
[ SECURITY. [Comment-entry]....].
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
SOURCE-COMPUTER. computer-name.
OBJECT-COMPUTER. computer-name.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT file-name-1
ASSIGN TO implementor-name-1
[ ORGANIZATION IS ] SEQUENTIAL
INDEXED
ACCESS MODE IS
SEQUENTIAL
RANDOM
DYNAMIC
RECORD KEY IS data-name-1
[ ALTERNATE RECORD KEY IS data-name-2
[ WITH DUPLICATES ] ] ...
[ FILE STATUS IS data-name ] .
DATA DIVISION.
FILE SECTION.
FD file-name-1
LABEL RECORD IS
RECORD ARE
OMITTED
STANDARD
record-name-1.
90
COBOL
WORKING-STORAGE SECTION.
(level-number 02-49) identifier-1 OCCURS integer-1 TIMES
ASCENDING KEY IS data-name-2
DESCENDING
INDEXED BY index-name-1
LINKAGE SECTION.
PROCEDURE DIVISION.
OPEN
INPUT
OUTPUT
I-O
EXTEND
file-name-1 ...
READ file-name-1
[ AT END statement-1...] .
READ file-name-1 NEXT RECORD
[ AT END statement-1...] .
READ file-name-1
[ INVALID KEY statement-1...] .
READ file-name-1
KEY IS alternate-record-keyname
[ INVALID KEY statement-1...] .
WRITE record-name-1 [ FROM identifier-1 ]
AFTER
ADVANCING PAGE
LINE
BEFORE
integer-1LINES
identifier-2
WRITE record-name-1 [ FROM identifier-1 ]
[ INVALID KEY imperative-statement-1] .
REWRITE record-name-1 [ FROM identifier-1 ]
[ INVALID KEY imperative-statement-1 ] .
DELETE indexed-file-name-1 RECORD
[ INVALID KEY imperative-statement-1 ] .
START file-name-1 KEY
IS EQUAL TO
IS =
IS GREATER THAN
IS >
IS NOT LESS THAN
IS NOT <
[ INVALID KEY imperative-statement-1 ]
91
data-name-1
COBOL
CLOSE file-name-1... .
DISPLAY
identifier
literal-1
[ WITH NO ADVANCING ]
ACCEPT identifier-1
[ FROM mnemonic-name-1]
GO TO paragraph-name-1.
PERFORM procedure-name-1 .
PERFORM procedure-name-1
UNTIL condition-1.
PERFORM paragraph-name-1
THROUGH
THRU
paragraph-name-2
PERFORM paragraph-name-1
THROUGH
THRU
paragraph-name-2
THROUGH
THRU
paragraph-name-2
THROUGH
THRU
identifier-2
FROM
index-name-1
paragraph-name-2
UNTIL condition-1.
PERFORM paragraph-name-1
integer-1
TIMES .
identifier-1
PERFORM paragraph-name-1
VARYING
identifier-3
literal-1
index-name-2
BY
identifier-4
literal-2
UNTIL condition-1
AFTER identifier-5
FROM
index-name-3
identifier-6
literal-3
index-name-4
UNTIL condition-2
STOP RUN.
MOVE
identifier-1
literal-1
TO identifier-2
MOVE
CORRESPONDING
CORR
group-item-1 TO group-item-2
ADD
identifier-1
literal-1
ADD
identifier-1
92
BY
identifier-7
literal-4
COBOL
literal-1
SUBTRACT identifier-1
literal-1
SUBTRACT
MULTIPLY
identifier-1
literal-1
identifier-2
literal-2
BY identifier-2 ...
MULTIPLY
identifier-1 BY identifier-2
literal-1
literal-2
GIVING identifier-3 ...
DIVIDE
identifier-1
literal-1
DIVIDE
identifier-1
INTO identifier-2
literal-1
literal-2
GIVING identifier-3 ...
[ REMAINDER identifier-4 ]
DIVIDE
identifier-1
BY identifier-2
literal-1
literal-2
GIVING identifier-3 ...
[ REMAINDER identifier-4 ]
NUMERIC
ALPHABETIC
POSITIVE
NEGATIVE
ZERO
identifier-2
index-name-1
[ AT END imperative-statement-1 ]
WHEN condition-1 imperative-statement-2
NEXT SENTENCE
93
...
COBOL
SET index-name-1
TO
UP BY
DOWN BY
integer-1
identifier-2
literal-1
arithmetic-expression-1
condition-name-1
data-name-2
IS EQUAL TO
IS =
identifier-3
literal-2
arithmetic-expression-2
condition-name-2
imperative-statement-2
NEXT SENTENCE
COPY text-name
REPLACING
OF library-name-1
IN
==pseudo-text-1==
identifier-1
literal-1
word-1
BY
==pseudo-text-2==
identifier-2
literal-2
word-2
...
INITIAL
identifier-4
literal-2
identifier-3
literal-1
...
identifier-3
literal-2
SORT file-name-1
ON
BEFORE
AFTER
INITIAL
94
...
identifier-4
literal-3
...
COBOL
ASCENDING
USING file-name-2
INPUT PROCEDURE IS procedure-name-1
GIVING file-name-3
OUTPUT PROCEDURE IS procedure-name-1
THRU
THROUGH
procedure-name-2
THRU
THROUGH
procedure-name-2
RELEASE sort-record-name-1
[ FROM identifier-1 ]
RETURN sort-file-name-1
AT END imperative-statement-1
STRING
identifier-1
literal-1
DELIMITED BY
identifier-2
literal-2
SIZE
...
INTO identifier-3
[ WITH POINTER identifier-3 ]
UNSTRING
OR [ALL]
identifier-3
literal-2
...
INTO identifier-4
[ WITH POINTER identifier-3 ]
95
identifier-2
literal-1