Cobol Programming
Cobol Programming
com
Introduction to COBOL
Divisions of COBOL
Picture clause characteristics
Editing
Level Structure
PAGE NO
1
9
16
20
26
UNIT 2
Lesson-6
Lesson-7
Lesson-8
Lesson-9
Lesson-10
30
34
41
48
54
UNIT 3
Lesson-11
Lesson-12
Lesson-13
Lesson-14
Lesson-15
Conditions
Conditionals Statements
PERFORM statements
RENAMES & REDEFINES Clauses
Programs
60
70
77
82
86
UNIT 4
Lesson-16
Lesson-17
Lesson-18
Lesson-19
Lesson-20
Sequential Files
Direct Access Files
Indexed Sequential Files
Sorting and Merging of Files
Programs
92
98
102
107
114
UNIT 5
Lesson-21
Lesson-22
Lesson-23
Lesson-24
Lesson-25
Table Handling
Indexed Tables & Index Names
Search & Start Verbs
Programs using OCCURS & Screen Section
List of Programs
123
128
132
136
142
UNIT I
History of COBOL
1.2
1.3
1.4
CHARACTER SET
1.5
COBOL WORDS
1.6
1.7
LITERALS
1.8
1.9
Let us Sum up
1.10
Lesson-end Activities
1.11
1.12
References
source program into the machine language object program. This object program is really
executed.
COBOL programs are written in coding sheets. There are 80 columns in a line of the
coding sheet. The page number is coded in columns 1-3 and the line numbers are coded in
columns 4-6. The page and line numbers together is called the sequence number. Depending
on the type, the entries are coded both from column 8 or column 12 and in both cases it can
be continued up to column 72. Columns 73-80 can be used to write some identification. The
compiler ignores anything that is given in columns 73-80 except when a printed copy of the
program is provided by the compiler in which case the entries in columns 73-80 are also
listed. The use of the sequence number is also optional and can be omitted. However, when
sequence numbers are provided they must appear in ascending order.
Column
1-3
4-6
7
8-11
12-72
73-80
Field
Page Number
Line Number (1-6 Sequence Number)
Continuation / Comment
A Margin / Area A
B- Margin /Area B
Identification
In COBOL there are two types of entries known as margin A and margin B entries.
Margin A entries start from column 8, 9, 10 or 11 and margin B entries start from column 12
or anywhere after 12.
An asterisk (*) in column 7 indicates a comment line and the entry is not compiled to
produce object code. Comment lines are actually some notes revealing the intentions of the
programmer. Since the compiler ignores them, anything can be included as comments.
Comment lines can appear anywhere after the first line of the COBOL program. A comment
line can also be indicated by using the character slash ( / ) in column 7. But in this case the
comment line will be printed after causing a page ejection (i.e., after skipping to the top of the
next page).
1.3 STRUCTURE OF A COBOL PROGRAM
Every COBOL program must have the following 4 divisions in the order in which they
are specified below.
1.
2.
3.
4.
Identification division
Environment Division
Data Division
Procedure Division
In the Identification division the details about the author, date of writing the program etc
will be specified.
In the Environment division, the details about the computer environment under which
the program was written and compiled etc will be notified.
In the Data division, the variables that are used by the program will be defined and it is
an important division for the program.
(Quotation mark)
(
(Left Parenthesis )
)
(Right Parenthesis)
>
(Greater than symbol)
<
(Less than symbol)
The characters 0-9 are called numeric characters o r digits. The characters A-Z are
called letters and the remaining characters are called special characters. The space or blank
character in certain cases is treated as a letter.
1.5 COBOL WORDS
A COBOL word can be formed using the following characters:
0-9
A-Z
-
(a-z)
(hyphen)
Examples
Valid Word
emp-sal
There are 2 types of words in COBOL. A COBOL word can be either a user-defined
word or reserved word. The reserved words are used in COBOL statements and entries for
specific purposes by the COBOL compiler.
Some reserved words are given below:
ADD, SUBTRACT, DIVIDE, MULTIPLY, IF, PERFORM etc.
To know the complete set of reserved words of COBOL one can refer to the manual
supplied with the compiler. Any attempt by the programmer to declare the reserved word
will be indicated as an error during the compilation stage of the program.
1.6 DATA NAMES AND IDENTIFIERS
A data name gives reference to the storage space in the memory where the actual value
is stored. This value takes part in the operation when that particular data name is used in the
PROCEDURE DIVISION.
Identifier is a general term which means the single data name or a data name qualified,
indexed or subscripted. Data names are only one form of identifiers. A data name must be a
user-defined word and it cannot be a reserved word.
Examples
Valid Data Names
NET-SALARY
TOT-MARK
N100
1.7 LITERALS
The actual values can also appear in a program. Such values are known as literals.
For Example, the statement MOVE 0 TO TOTAL indicates that the value zero will be
moved to the variable TOTAL. This constant 0 which used in the body of the statement is a
literal.
A data name may have different values at different points of time whereas a literal
means the specific value which remains unchanged throughout the execution of the program.
For this reason a literal is often called a constant. Moreover the literal is not given a name;
it represents itself and does not require to be defined in the DATA DIVISION.
There are 3 types of literals
a) numeric
b) nonnumeric.
c) figurative constants
(a) Numeric
A numeric literal can be formed with the help of digits only. It can have a sign (+ or -)
and can have a decimal point also. If no sign is specified the literal will be taken as positive.
Negative literals are indicated by sign at the leftmost end. If no decimal point is used then
the literal is obviously an Integer. If a decimal point is used, it must come in between the
digits. The maximum number of digits allowed in a numeric literal is compiler dependent.
Examples
(i) Valid Numeric Literal
.123
12.5
(b) Nonnumeric
A nonnumeric literal is used in general to output messages or headings. Characters that
are enclosed between constitute nonnumeric literal. The maximum number of characters
that are allowed within two quotation marks is compiler dependent.
(iii) Valid Nonnumeric Literal
BHARATHIAR
DATA DIVISION
100.50
HOUR/RATE
(iv) Invalid Nonnumeric Literal
7
nine
12.5
c) Figurative Constants
Figurative constants have some fixed names and the compiler recognizes these names
and it sets up corresponding values in the object program.
Consider the statement given below :
MOVE ZERO TO COUNTER
Here value 0 will be moved to COUNTER by the compiler, as it recognizes ZERO and
sets COUNTER with 0. Given below is the list of figurative constants.
Figurative Constant
Meaning
ZERO
ZEROS
ZEROES
value 0
SPACE
SPACES
HIGH-VALUE
HIGH-VALUES
LOW-VALUE
LOW-VALUES
QUOTE
QUOTES
one or more of
ALL literal
4. { entries}
5. , ;
6.
7. Space character
used as a separator
2.1
2.2
2.3
Environment Division
2.4
Configuration Section
2.4.1. Source-Computer
2.4.2 Object-Computer
2.4.3
Special Names
2.5
Input-Output Section
2.6
2.5.1 File-Control
Data Division.
2.7
Let us Sum up
2.8
Lesson-end Activities
2.9
2.10
10
11
The division headings, section headings and the paragraph headings should be coded as
Margin A entries. The paragraph headings must be followed by a period and then a space.
The entries in the paragraphs are Margin B entries and can start in the same line with the
paragraph heading.
2.4 CONFIGURATION SECTION
This section contains an overall specification of the computer used for the purpose of
compilation and execution of the program. There are in all three paragraphs in this section,
namely, source-computer, object-computer and special names.
2.4.1 SOURCE-COMPUTER
This paragraph specifies the name of the computer used to compile the COBOL
program. The following is the form of this paragraph.
SOURCE-COMPUTER. computer-name.
For example, if ICL 1901 is to be used for compiling the COBOL source program, this
paragraph should be as follows:
SOURCE-COMPUTER. ICL-1901
2.4.2 OBJECT-COMPUTER
The OBJECT-COMPUTER paragraph describes the computer on which the program is
to be executed. The following shows the syntax for this paragraph.
OBJECT-COMPUTER. computer-name
CHARACTERS
[, MEMORY SIZE interger-1]
WORDS
[, PROGRAM COLLATING SEQUENCE IS alphabet-name]
[, SEGMENT-LIMIT IS interger-2].
The computer name specifies a particular computer on which the object program is to be
executed.
The MEMORY SIZE is used to indicate the amount of storage available to the object
program. This clause is also used in conjunction with the SORT verb.
The PROGRAM COLLATING SEQUENCE clause specifies the collating sequence that
is to be used to compare nonnumeric data items. The alphabet name in this clause should be
defined in the SPECIAL-NAMES paragraph to specify a collating sequence. If this clause is
absent, the machines own collating sequence called NATIVE, is assumed.
The SEGMENT- LIMIT clause is used in most of the compilers to indicate that the
sections having segment number less that the number specified in
integer-2 should be held in the permanent area of storage and should not be transferred to and
from the virtual memory.
12
All the entries in this paragraph are terminated using period ( a dot). The following is
an example of the OBJECT-COMPUTER paragraph.
OBJECT-COMPUTER.
MEMORY SIZE 8000 WORDS.
2.4.3 SPECIAL-NAMES
This paragraph is used to relate some hardware names to user-specified mnemonic
names. This paragraph is optional in all compilers. The following is the format of this
paragraph.
SPECIAL-NAMES, [, CURRENCY SIGN IS literal-1]
[, DECIMAL-POINT IS COMMA]
[, CHANNEL integer IS mnemonic-names]
[, ALPHABET alphabet-name IS
STANDARD-1
NATIVE
implementor-name
[, implementor-name IS mnemonic-name].
The CHANNEL clause is used to control the line spacing of line printers. This clause is
used to associate a user-defined name called the mnemonic name with a channel in the printer
carriage control. The range of integer depends on the particular line printer to be used. This
mnemonic name can only be used in a WRITE statement.
The ALPHABET clause specifies a user-defined alphabet name that can be used to
indicate a collating sequence in the PROGRAM COLLATING SEQUENCE clause discussed
above or in the collating sequence clause in the sort verb. The word NATIVE stands for the
computers own collating sequence and STANDARD-1 stands for the ASCII collating
sequence. The alphabet name is also used to define the external character set in which the
data is recorded on a file.
The SPECIAL-NAMES paragraph can have other entries which are implementordependent. These entries are not discussed here as they are not of general interest. In fact, the
CHANNEL entry is also an implementor-defined clause. The entries can appear in the
paragraph in any order.
Consider the example : Let the SPECIAL-NAMES paragraph be as follows:
SPECIAL-NAMES. CHANNEL 1 IS PAGE-TOP.
We know that conventionally channel is associated with the top of the page. While
instructing the computer to write a line on the line printer the programmer may like to specify
that the line must be printed as the first line on a new page. This may be done by including
the ADVANCE TO CHANNEL 1 clause in the write statement. The purpose of the special
name clause illustrated above is to enable the programmer to replace CHANNEL 1 by
PAGE-TOP in the ADVANCING clause. The idea is to provide better documentation. If one
prefers to use CHANNEL 1 in the write statement, the special name entry is not required.
13
14
]
[WORKING-STORAGE SECTION.
WORKING-STORAGE ENTRIES.
]
All the section names as well as the division name must be coded as margin A entries,
Each section of the DATA DIVISION is optional which means that a section may be omitted
if there is no data that may be described in a particular section. It is important to note that the
sections to be included must appear in the order shown above.
2.7 LET US SUM UP
The above lesson gives the learner clear ideas about the Identification, Environment
and Data division. Having learnt this, the learner will be in a position to use them in the
programs for better documentation.
2.8 LESSON-END ACTIVITIES
Try to find the answers for the following exercises on your own.
1.
2.
3.
4.
5.
15
16
Meaning
[Digit]
Each occurrence of this code represents a digit
17
In the case of an alphabetic item the picture may contain only the symbol A.
In the case of a numeric item the picture may contain only the symbols 9, V,
P and S. These are called operational characters. It must contain at least one 9.
The symbols V and S can appear only once and S, if it is included, must be the leftmost
character of the picture string. The symbol P can be repeated on the right or on left (but not
on the left of S) as many times as is required to indicate the position of the assumed decimal
point.
(iii)
In the case of an alphanumeric item, the picture may contain all Xs or a
combination of 9, A and X (except all 9 or all A). In the latter case the item is considered as if
the string consists of all Xs.
The picture clause is only to be specified for elementary items; it cannot be used for a
group item.
The size of a group item is equal to the total of the sizes of all subordinate elementary
items. The class of a group item is alphanumeric.
The following examples illustrate the PICTURE specification.
Example 1:
PICTURE IS S999V99
represents a signed data item with a size of 5 characters and the positions of the assumed
point is before 2 places from the rightmost end. Note that S and V are not counted.
Example 2:
PIC IS PPP9999
means that the numeric data is of 4 characters in size and there are 7 positions after the
assumed decimal point. Thus if the data in the memory is 123, the value will be taken as
.0000123. If, on the other hand, the picture were defined as 999PP, the value would have
been 12300.
Example 3:
PIC XXXXXX
represents the alphanumeric item with size of 6 characters.
Instead of repeating 9, X, A or P in the picture string, it is possible to write the number
of occurrences of a character enclosed within parenthesis immediately after the said
character.
Thus
S9(3)V9(2)
X(7)
P(4)9(3)
is equivalent to S999V99.
is equivalent to XXXXXX.
is equivalent to PPPP999.
18
19
LESSON 4: EDITING
CONTENTS
4.0
4.1
4.2
Editing
Edit characters for numeric data
4.3
Let us Sum up
4.4
Lesson-end Activities
4.5
4.5
+ CR DB . , B O /
20
Edited Value
ZZ999
01234
b1234
ZZ999
00052
bb052
ZZ999
1^68
bb001
ZZZV99
0^65
bbb65
ZZZZVZZ
0^05
bbbb05
ZZZZVZZ
0
bbbbbb
* (Asterisk)
The edit character * (asterisk) is identical to Z except that the leading zeros are replaced
by asterisks instead of space characters.
Examples
Picture of the Field
**999
**999
**999
Edited Value
*1234
**012
**001
$ (Currency Sign)
A single currency sign can appear at the leftmost position of a picture. In that case the $
character is inserted.
Examples:
Picture of the Field
Edited Value
-0123
b0382
0123-
21
9999382
0382b
-ZZZV99
-46^52
-b4652
-ZZZV99
46^52
bb4652
+ (Plus Sign)
A plus sign is similar to minus sign except that when the item is positive, +sign will be
inserted instead of the space character. If the item happens to be negative, a minus sign will
be inserted although there is a plus sign in the picture.
Examples:
Picture of the Field
Edited Value
Edited Value
9999CR
1234CR
9999CR
1234bb
ZZZCR
b12CR
ZZZ9V99DB
b12345DB
ZZZ9V99DB
b12345bb
. (Period or Decimal Point)
A period may be used to insert a decimal point and may not appear more than once.
Both the period and V cannot appear in the same picture. A period must not also appear
as the rightmost character in the picture.
Examples:
Picture of the Field
9999.99
0324.52
ZZ99.99
bb12.34
, (Comma)
A comma, when used in a picture, is treated as an insertion character and inserted
wherever it appears. There can be more than one comma in a picture.
22
Examples:
Picture of the Field
99,999
99,999
ZZ, Z99
1234
37
1234
Edited Value
01,234
00,037
b1,234
B (Blank Insertion)
The appearance of a B anywhere in the picture will insert a space character in the edited
data. There can be more than one B in a picture.
Examples:
Picture of the Field
99B99B99
99B99B99
Edited Value
17b10b62
00b00b12
0 (Zero Insertion)
A zero appearing in a picture will be treated in the same way as a B except that 0 will be
inserted instead of a space character.
Examples:
Picture of the Field
Edited Value
Edited Value
9900
1200
09990
04560
/ (Slash Insertion)
The edit character slash (/) also called virgule or stroke, may appear anywhere in the
picture. If used, it will be inserted. There can be more than one slash in the picture.
Examples:
Picture of the Field
99/99/99
15/06/81
999/999/99
000/032/45
BLANK WHEN ZERO
BLANK WHEN ZERO is an editing clause which may be used along with a picture.
This will set the entire data item to blanks of its value is equal to zero. However, the edit
character asterisk (*) may not be used if BLANK WHEN ZERO is specified. When this
clause is used to describe a field whose picture contains an asterisk, it is ignored by the
compiler. The syntax of this clause is as follows:
BLANK
WHEN
ZERO
23
Examples
Picture of the Field
ZZZ.99 BLANK WHEN ZERO
ZZZ.99 BLANK WHEN ZERO
999.99 BLANK WHEN ZERO
Edited Value
bb2.50
0
0
bbbbbb
bbbbbb
Floating Insertion
The currency symbol ($) can appear in multiples on the left-hand side of a picture. In
this case the character will be treated in the same way as the Z character and only one
currency symbol will be inserted immediately to the left of the first non-zero digit of the data.
Such a floating insertion is also possible in the case of minus (-) and plus (+) signs. In the
case of the minus character, no sign will be inserted unless the data is negative. The
appearance of a period halts the floating insertion.
Examples
Picture of the Field
$$$$9.99
++++.99
----.99
Edited Value
b$235.25
-475.25
bb-3.50
24
5.2
5.3
Value clause
Sample Program
5.4
Filler clause
5.5
Let us Sum up
5.6
5.7
Lesson-end Activities
Points for Discussion
5.7
References
MONTH
YEAR
It may be noted that the memory space referred to by DATE is the combined memory
space for DAY, MONTH and YEAR. The advantage of such a grouping is obvious. The
programmer can now refer to the individual elementary items DAY, MONTH, YEAR or to
the group item DATE. An elementary data item is thus the one which the programmer would
always like to refer to as a whole and not in parts.
25
To describe the hierarchical structure introduced above, the concept of level number is
employed in COBOL.
The most inclusive group must have the level number 01. The first subdivisions can
have any level number between 02 and 49. Further subdivisions should follow the same range
with the restriction that an item cannot have a level number less than or equal to the level
numbers of the group that may include it. Thus a group includes all elementary data or
smaller groups beneath it until a level number equal to or less than the level number of the
said group is encountered. The following examples reveal the concept of the level numbers.
Example 1
01
DATE
05
DAY
05
MONTH
05
YEAR
Example 2
01
PAY
02
GROSS-PAY
03
BASIC
03
DEARNESS
03
HOUSE-RENT
02
DEDUCTIONS
03
PF-DEDUCT
03
IT-DEDUCT
02
NET-PAY
The group DATE which was shown earlier in the pictorial form is illustrated in the first
example. In the second example PAY is the most inclusive group which has three
subdivisions, namely, GROSS-PAY, DEDUCTIONS and NET-PAY. GROSS-PAY is again
subdivided into BASIC, DEARNESS and HOUSE-RENT. In a similar way deductions are
further subdivided into PF-DEDUCT and IT-DEDUCT. It may also be noted that the
elementary data items are BASIC, DEARNESS, HOUSE-RENT, PF-DEDUCT, ITDEDUCT and NET-PAY. The structure can be pictorially shown as follows:
PAY
GROSS PAY
BASIC
DEARNESS
HOUSE - RENT
DEDUCTIONS
PF DEDUCT
NET - PAY
IT DEDUCT
Sometimes, in a hierarchical data structure such as this, the programmer may not require
a data item to be referred to in the PROCEDURE DIVISION. Such a situation usually arises
when a group and only some of its subdivisions are to be used in the program. The remaining
subdivisions need not be used explicitly. In such situations the word FILLER may be used to
26
name data to which the programmer does not wish to assign a specific name. FILLER can be
used as many times as required.
5.2 VALUE CLAUSE
The value clause defines the initial value of the data item.
Generally initialization will be done just before the first statement in the procedure
division is executed.
The syntax is
VALUE is literal
The literal can be any numeric value, a nonnumeric string of characters included within
quote() or any figurative constant.
Examples :
1)
2)
3)
4)
5)
6)
27
In the program, the user is at liberty to change the initial values by using statements like
MOVE, ACCEPT etc.
5.4 FILLER CLAUSE:
Consider the statements given below:
1)
01 f pic x(80) value all - .
This statement causes a line of 80 characters filled with -
2)
01 f
pic x(60) value all *.
This statement causes a line of 60 characters filled with *
3)
01 filler pic x(10) value TESTING.
Note that we can either use simply f or filler in the statements.
Generally fillers are used to improve the clarity of the output and form designs utilize
the potential of filler clauses to the maximum.
5.5 LET US SUM UP
In the above lesson the concept of level numbers, value clause and Filler clause are
discussed with syntaxes and examples and a sample program is written to emphasize these
concepts.
5.6 LESSON-END ACTIVITIES
Try to find the answers for the following exercises on your own.
1.
2.
3.
4.
5.
28
UNIT II
LESSON 6: DATA MOVEMENT VERB: MOVE
CONTENTS
6.0 Aims and objectives
6.1 Syntax of Move Verb
6.2 Rules of Move Verb
6.3 Examples of Move usage
6.4 Let us Sum Up
6.5 Lesson-end Activities
6.6 Point s for Discussion
6.7 Points for Discussion
6.8 References
6.0 AIMS AND OBJECTIVES
The aim of this lesson is to introduce the learner how to move data from one place to
another place in memory. This is done with the help of MOVE verb. The syntax, rules and
the examples given will make the learner to understand the said verb.
6.1 SYNTAX OF MOVE VERB
The general form of the MOVE verb is as follows:
identifier - 1
MOVE
TO identifier 2 [ ,
identifier 3]
literal - 1
6.2 RULES OF MOVE VERB
Data movement is governed by the following rules.
(a) The contents of identifier 1 or the value of literal 1 is moved to identifier 2,
identifier 3, etc. Note that there may be more than one receiving field whereas
there must be only one sending field, the contents of all the receiving fields will
be replaced by the value of the sending field. The contents of identifier 1
remain unaltered.
(b) When the sending field is numeric and the receiving field is numeric or numeric
edited (i.e., picture contains edit symbols) the data movement is called numeric
data transfer. In such cases the dominant factor in the movement is the
alignment of the decimal points of the two fields. For the purpose of this
alignment, the numeric fields for which the position of the decimal point is not
explicitly indicated, the decimal point is assumed to be at the right of the
rightmost digit. If the receiving field is not large enough to hold the data
received, truncation can take place at either and depending on whether the
integral part, fractional part or both can or cannot be accommodated (see
examples given in this section for further clarification). However, if significant
integral positions are likely to be lost, a warning to that effect is issued by the
compiler. On the other hand, if the receiving field is larger than the sending
29
field, zero- fill will take place in the unused positions to keep the numeric value
unaltered.
(c) When both the sending and receiving fields are alphabetic, alphanumeric or
alphanumeric edited, the data movement is called alphanumeric data transfer. In
such cases the receiving area is filled from left to right and space fill occurs to
the right if the receiving area is larger than the sending field. When the receiving
area is smaller, truncation occurs from the right and the compiler gives a warning
to that effect.
Ideally, both the sending and receiving fields should belong to the same category.
However, quite often it becomes necessary to transfer a data to a field having a different
category. Identifier 1, identifier 2, identifier 3, etc., can be group items. In such cases,
the move is very frequently used. This is when we wish to initialize a record area by spaces.
For example, the statement MOVE SPACES TO REC-AREA will space- fill the entire area
denoted by the group name REC-AREA.
6.3 EXAMPLES OF MOVE USAGE
(a) MOVE A TO B.
Contents of A
After
execution
Before
execution
(i) PIC 9999
5
PIC 9999
7
Contents of B
After
execution
Before
execution
PIC 9999
7
3
^
Before
execution
PIC 999V99
1
3
^
Contents of A
After
execution
7 8 2
^
Before
execution
0 1 2
^
Zero fill on left
and right
Contents of B
After
execution
30
PIC 999V9
4
(v)
2 3
^
Zero fill on
Left and
truncation on
right
PIC 99V9
4
8
^
PIC 999V9
1
^
Truncation
on left
PIC X(6)
U
R A J U
C H E T A N
R A
J U b
Space fill
on right
(vii) PIC X(5)
S O M A N
PIC X(4)
S O M A N
R A M
S O M U
Truncation
on right
2 3 4
^
PIC ZZ9.99
0 1
2 3
^
5 6 7 . 8 9
b 1 2 . 3 4
Decimal point
alignment and
editing
(b)
MOVE 15 TO A.
In this case the number 15 will be moved to A and if the PICTURE of A is 999, then
after the execution of the above statement A will contain 015.
(c)
31
(d)
MOVE A TO B, C, D.
If the contents of A is 22 and the contents of B, C and D are 452, 3892 and 46
respectively, then after the execution of the above instruction the contents of B, C and D will
be 022, 0022 and 22 respectively.
The above mentioned rules for data movement are also used elsewhere in COBOL. For
example, when the value of a data item is initialized by using the VALUE clause, the same
rules apply. In this case the data name should be considered as the receiving field and the
value of the literal should be taken as that of the sending field. Thus
77 NEW-DATA PIC X(10) VALUE NEWDATA
will initialize NEW-DATA by the value NEWDATA bbb.
6.4 LET US SUM UP
In this lesson clear ideas about the MOVE verb are highlighted. One gets strong
background of the concept by understanding the how the values are placed while moving
takes place from one variable to other. This verb will be used in majority of the programs.
6.5 LESSON-END ACTIVITIES
Try to find the answers for the following exercises on your own.
1.
2.
3.
32
identifier-2
ADD
literal - 1
TO
ADD
identifier-1
literal-1
, literal-2
identifier-3
[, identifier-4]
identifier-2
literal-2
identifier-3
, literal-3
GIVING
identifier-4
[, identifier-5]
Examples
(a)
ADD A TO B.
This example shows that the value of A will be added to the value of B and the result
will be stored in B. The alignment of the decimal point is done automatically.
33
(b)
ADD A B C TO D.
In this case the values of A, B and C will be added to the old value of D and the resultant
sum will be the new value of D.
(c)
ADD 30 A TO B.
This example shows that the number 30, the value of A and the value of B will be added
and the resultant sum will be stored in B.
(d)
ADD A, B GIVING C.
Here only the values of A and B will be added and the sum will be stored in C. The old
value of C will be lost and that value will not take part in the summation.
(e)
ADD A, B GIVING C, D, E.
In this case the value of A, B will be added and the sum will be stored in C, D and E.
Hence after the execution of this statement, C, D and E will have the same value.
The above examples indicate that in the case of the TO option the previous value of the
last named operand takes part in the summation and then this value is replaced by the result.
However, this is not the case when the GIVING option is used. It should be mentioned here
that the last named operand in both the cases can never be a literal as the resultant sum is
always stored there.
It is important to note that TO and GIVING cannot be used simultaneously. Thus ADD
A TO B GIVING C would be wrong. The purpose is served by specifying as ADD A B
GIVING C. With GIVING option identifier-2/numeric- literal-2 is a must.
7.2 SUBTRACT VERB
This verb is used to subtract one, or the sum of two or more numbers from one or more
numbers and to store the result.
The form of the SUBTRACT verb is as follows:
identifier-1
indentifier-2
SUBTRACT
numericliteral-1
, numericliteral-2
identifier-3
[, identifier-6]
, GIVING identifier-5
, identifier-6
FROM
Examples
(a)
SUBTRACT A FROM B.
This statement means that the value of A will be subtracted from the value of B and the
subtracted result will be stored in B. The decimal point alignment will be done
automatically.
(b)
SUBTRACT A, B FROM C.
This one shows that the value of B and A will be added and the resultant sum will be
subtracted from the value of C. After subtraction, the final result will be stored in C. The old
value of C will be lost.
34
(c)
SUBTRACT 15 FROM A B.
Here the number 15 will be subtracted from the values of A and B. A and B will
receive these new values.
As in the case of the ADD statement, here also the last- named operand must not be a
literal as the final result will be stored there. If the GIVING option is used, identifier-3,
identifier-4 etc. can also be numeric literals. For example, SUBTRACT A B FROM 50
GIVING C.
7.3 MULTIPLY VERB
This statement causes one or more multiplicands to be multiplied by a multiplier and to
store the products. The form of the MULTIPLY verb is as follows:
identifier-1
MULTIPLY
BY identifier-2
, identifier-3
numeric-literal-1
,
GIVING identifier-4
, identifier-5
Examples
(a)
MULTIPLY A BY B.
In this case the value of A and B will be multiplied and the product will be stored in B.
The decimal point position will automatically be taken care of. The old value of B will be
lost.
(b)
MULTIPLY A BY B GIVING C.
Here the value of A and B will be multiplied and the product will be stored in C. The
old value of C will be lost but B will contain its old value.
(c)
MULTIPLY A BY B C D.
Here B will be multiplied by A and the result will be stored in B. similarly, C will be
multiplied by A and the product will be stored in C and the result of the multiplication of D
and A will be stored in D.
(d)
MULTIPLY A BY B C GIVING D E.
In this case the product of B and A will be stored in D, whereas the product of C and A
will be stored in E.
In the case of the MULTIPLY statement also, literals cannot be used for identifier-2,
identifier-3, etc. However, if the GIVING option is used, numeric literals are also permitted
in place of identifier-2, identifier-3, etc. For example,
MULTIPLY TAX BY .05 GIVING TAX-BASE.
35
INTO
identifier-2
, identifier-3
numeric-literal-1
, GIVING identifier-4
, identifier-5
Examples
(a)
DIVIDE 5 INTO A.
If the value of A is 20, then after the execution of this statement the value of A will be 4.
The old value of A will be lost.
(b)
(d)
identifier-2
BY
numeric-literal-1
GIVING identifier-3
numeric- literal-2
, identifier-4
In this case identifier-1 or numeric- literal-1 will be divided by identifier-2 or numericliteral-2, whatever may be the case. The result is stored in identifier-3, identifier-4, etc.
Examples
DIVIDE A BY 3 GIVING C.
If the value of A is 21 then after the execution of this statement C will contain 7.
There is another form of DIVIDE verb where there is a provision to store the
remainder. Its form is
36
identifier-1
INTO
identifier-2
BY
numeric- literal-2
DIVIDE
numeric-literal-1
GIVING identifier-3
REMAINDER identifier-4.
Example
DIVIDE A INTO B GIVING C REMAINDER D.
If the identifier A, B, C and D are all two-digited numbers and if they contain 05, 37, 18
and 20 respectively before the execution of the statement, then after the execution of the
statement, they will contain 05, 37, 07 and 02 respectively.
7.5 COMPUTE VERB
COMPUTE verb is so powerful. All the computations performed by the other four verbs
can also be done easily by using the COMPUTE verb. Its general format is
COMPUTE
identifier-1
= arithmetic-expression
; ON SIZE ERROR imperative-statement
The COMPUTE statement has the following meaning. During execution the arithmetic
expression on the right of the equal sign is evaluated and the value is then moved to the
identifiers(s) on the left-hand side. If any identifier on the left of the equal sign is a numericedited item, editing takes place when the value of the expression is moved to the said
identifier. The identifiers on the left of the equal sign (=) must be numeric or numeric-edited
elementary items. The right- hand side must be an arithmetic expression. An arithmetic
expression can be an identifier (numeric elementary items only), a numeric literal or can
specify a computation involving two or more such identifiers and/or literals. An arithmetic
expression has always a numeric value. The following are the rules for constructing
arithmetic expression.
(i)
When an arithmetic expression specifies a computation, it may consist of two or more
numeric literals and/or data names joined by arithmetic operators. The following
table lists the operations and their meaning.
Operator
Meaning
**
Exponentiation
/
Division
*
Multiplication
Subtraction
+
Addition
There must be at least one space preceding and following the operator in an arithmetic
expression. No two arithmetic operators can appear together in an expression. In this respect
** is considered to be a single operator.
(i)
37
When parentheses are used, the portion of the expression enclosed within parentheses
is evaluated first.
(ii)
I
*
QUANTITY -
DISCOUNT
Note that when the right-hand side of a COMPUTE verbs is a single identifier or literal,
the effect is that of a MOVE statement.
Example 1
COMPUTE A = B + C
has the same effect as that as that of ADD B C GIVING A
Example 2
COMPUTE F = 1.8 * C + 32
The value of the expression on the right-hand side is evaluated and this value is then
moved to F. Suppose C and F are defined with pictures 99 and ZZ9.9 respectively and the
current value of C is 3. Then after the execution of the statement, F will have the value 37.4.
7.6 LET US SUM UP
This lesson has taught the learner to understand the arithmetic verbs like Add, Subtract,
Multiply, Divide and Compute. All these verbs have been presented with syntaxes and
adequate examples are also provided.
7.7 LESSON-END ACTIVITIES
Try to find the answers for the following exercises on your own.
1.
2.
3.
4.
5.
REFERENCES
1. COBOL Programming , M.K.Roy & Ghosh Dastidar , Tata McGraw Hill,
2nd Edition,1998
2. COBOL Programming , V. RAJARAMAN, PHI Pub
3. Introduction to COBOL programming Dr. R.Krishnamoorthy, JJ Publ
4. Structured COBOL , Welburn, TataMcGraw Hill , 4th Edition.
38
8.1
8.2
Open Statement
Read Statement
8.3
Write Statement
8.4
Close Statement
8.5
8.6
Accept
Display
8.7
8.8
8.9
Let us Sum Up
Lesson-end Activities
8.10
8.11
References
file- name-1
, file- name-2
, file- name-4
OPEN
Example 1
OPEN INPUT TRANSACTION, OLD-MASTER OUTPUT NEW-MASTER.
The example shows that there are two input files named TRANSACTION and OLDMASTER and one output file called NEW-MASTER. All these files are opened and these
are ready for reading or writing.
39
Example 2
OPEN INPUT MARK-FILE.
OPEN OUTPUT RESULT-FILE.
The first OPEN statement opens the MARK-FILE in input mode and the file is ready for
reading. The next statement makes the RESULT-FILE ready for writing. There may be
several OPEN statements in a program.
8.2 READ
The purpose of this verb is to make available the next logical record from an input file.
It is important to note the meaning of "next" logical record in the above statement. The first
time the READ statement is executed, the first record of the file will be read into the record
area described in the FILE SECTION of the DATA DIVISION. The next time the READ
statement is executed, the second record will be read in the same area. In this way each time
a READ statement is executed the successive records will be read in the same area. Thus a
time will come when there will be no more records in the file. In that case the statements
following the AT END clause will be executed. The format of the READ statement is
READ file-name RECORD [INTO identifier-1]
AT END imperative-statement
Example 1
READ OLD-MASTER AT END MOVE ZERO TO END-OF-RECORDS.
As a result of this statement, normally the next record from the OLD-MASTER file will
be read. If there is no more record in OLD-MASTER, the value zero will be moved to the
field named END-OF-RECORDS.
Example 2
READ TRANSACTION RECORD AT END GO TO PARA-END.
This example is similar to the earlier example. The next record from the
TRANSACTION file will be read if it is available. If the file does not contain any more
records, the control will be transferred to the paragraph named PARA-END.
Example 3
READ KARD-FILE INTO IN-REC AT END
GO TO JOB-END.
This statement not only reads the next record into the record area of KARD-FILE but
also moves the record into the area name IN-REC. When there is no more record in the
KARD-FILE, the control is transferred to the paragraph named JOB-END. If the record area
of the KARD-FILE has been named KARD-REC, the above statement is equivalent to
READ KARD-FILE AT END GO TO JOB-END.
MOVE KARD-REC TO IN-REC.
It may be noted that if the record has been successfully read, it is now available in
KARD-REC as well as IN-REC.
8.3 WRITE
The WRITE verb releases a record onto an output file. The syntax of the WRITE
statement can be different depending on the output device and medium used. The verb as
40
described here can be used only to print results on a continuous stationery through a line
printer. The form of the WRITE statement in such a case is
WRITE record-name
[ FROM identifier-1]
BEFORE
ADVANCING
AFTER
integer-1
LINES
identifier-2
LINES
mnemonic- name
hardware-name
The first point to be noted is that in the case of the READ statement the file name is to
be specified, whereas in the case of the WRITE statement it is required to mention the record
name an not the file name. The ADVANCING phrase is used to control the vertical
positioning of each record at the time of printing on the stationery placed on the printer.
When the BEFORE phrase is used, the record is printed before the stationary is advanced,
whereas the AFTER phrase may be used when the intention is to advance the stationary first
and then to print the record. If integer-1 or identifier-1 is mentioned, the stationary is
advanced by the number of lines equal to the value of integers-1 or to the current value of
identifier-1.
If the mnemonic- name is specified, the printer will be advanced to the carriage control
channel declared for the mnemonic- name in the SPECIAL-NAMES paragraph. This option
is provided so that the hardware names which may be peculiar to a particular computer need
not appear in the PROCEDURE DIVISION.
If the FROM option is used, the operation is identical to that of MOVE identifier-1 TO
record-name followed by a WRITE record-name without the FROM clause. It is illegal to
use the same storage area for both record-name and identifier-1.
It should be noted that after WRITE is executed the record is no longer available.
Examples
(i)
WRITE TRANS-RECORD AFTER ADVANCING 3 LINES.
This WRITE statement indicated that TRANS-RECORD is a record name of a file that
has been assigned to PRINTER. The current position of the stationery will be advanced by 3
lines, i.e., there will be 2 blank lines and the present record will be written on the third line.
(ii)
8.4 CLOSE
When the processing of a file is over, the file may be closed. This is done with the help
of the CLOSE-verb. The form of the CLOSE statement is
CLOSE file-name-1
[, file-name-2]
The file must be open when a close statement can be executed. Once a file is closed, it
is no longer available to the program. It should be opened again if the file is required
subsequently. It may be noted that unlike the OPEN statement, the nature of the use of the
file (input and output) should not be mentioned in the CLOSE statement.
41
Example
CLOSE TRANSACTION, OLD-MASTER, NEW-MASTER, PRINT-FILE.
This statement will close all the four files TRANSACTION, OLD-MASTER, NEWMASTER and PRINT-FILE.
8.5 ACCEPT
The ACCEPT statement is used to read low-volume data from the operators console,
some other hardware device or from the operating system. The general format of the
ACCEPT statement is as follows:
mnemonic-name
DATE
ACCEPT
identifier
FROM
DAY
TIME
When the FROM option is omitted, the data is read into the identifier from the
operators console. At the time of execution, a message is displayed on the console (e.g.,
AWAITING COBOL INPUT) and the program is suspended until the operator enters the
data through the console keyboard. Data entered by the operator will be left justified in the
identifier. For example,
ACCEPT FLAG-A
can be specified to read the value of FLAG_A fro the console. It may be noted that no file
defi0nition is necessary.
The mnemonic-name option is implementer-dependent. The hardware device from
which the data is to be read is to be equated to a mnemonic name in the SPECIAL-NAME
APARAGRAPH. For example, the following entry in the SPECIAL-NAMES paragraph
TYPEWRITER-1 IS CONTROL-DATA
may equate the mnemonic name CONTROL-DATA with the assumed implementor- name
TYPEWRITER-1. The
ACCEPT FLAG-1 FROM CONTROL-DATA
will read the value of FLAG-A fro the hardware device indicated by TYPEWRITER-1.
The DATE, DAY and TIME options are new features introduced in ANSI 74 COBOL.
The DAY option returns the six-digit current date in the form YYMMDD where YY, MM
and DD stand for year, month and day respectively. The DAY option returns a five-digit
current date in the form YYDDD where YY stands for the year and DDD stands for the day
of the year(001 to 365). The TIME option returns an eight-digit time in the form
HHMMSSTT where HH, MM, SS, TT represent hour, minute, second and hundreds of a
second respectively. For all the three options, the returned value is transferred to the
identifier ( in the ACCEPT statement) according to the rules of the MOVE statement. For
example,
42
, identifier-2
UPON mnemonic-name
literal-1
, literal-2
If the UPON option is omitted, the values of the identifier-1/literal-1, identifier-2/literal2, etc. are displayed on the console. The UPON option with the mnemonic-name is
implementor-dependent. The mnemonic name, as in the case of the ACCEPT verb, should be
defined in the SPECIAL-NAMES paragraph. When more than one operand is specified, the
values of the operands are displayed in the sequence they are specified. There will be no
space between these values. The operands must be of the usage DISPLAY. The literals may
be any literal or figurative constant except the ALL literal. If a figurative constant is
specified, only one occurrence of the constant is displayed.
Example
Consider the following statement.
DISPLAY SUM IS, THE-SUM
and suppose that the picture and current value of THE-SUM are 9(3) and 15 respectively.
Upon execution of the statement, the following will be displayed on the console
SUM IS 015
8.7 GO TO , STOP RUN
GO TO
GO TO verb is used to unconditionally transfer the control to elsewhere in the program.
Its form is as follows:
GO TO procedure- name
As a result of the execution of this statement, the control is transferred to the first
statement of the paragraph or section mentioned in the procedure name.
Example
GO TO ERROR-ROUTINE
Suppose ERROR-ROUTINE is a paragraph name. The execution of this statement will
transfer the control to the first statement in ERROR-ROUTINE. On the other hand, suppose
ERROR-ROUTINE is a section name and FIRST-PARA is the name of the first paragraph in
this section. In the case control will be transferred to the first statement in FIRST-PARA. It
may be noted that GO TO FIRST-PARA is identical to GO TO ERROR-ROUTINE.
STOP RUN
This verb causes the termination of the execution of the object program. Its form is
STOP RUN
43
44
9.1
9.2
Move Corresponding
ADD & SUBTRACT Corresponding
9.3
General Rules
9.4
Rounded Option
9.5
9.6
9.7
Lesson-end Activities
9.8
9.9
References
PRINT-REC.
02
FILLER
02
ID-NUMBER
02
FILLER
02
NAME
02
FILLER
02
DEPARTMENT
02
FILLER
02
BASIC-PAY
PIC
PIC
PIC
PIC
PIC
9[5].
X[25].
X[20].
9999V99.
X[24].
PIC
PIC
PIC
PIC
PIC
PIC
PIC
PIC
X[5].
Z[5].
X[5].
X[25].
X[5].
X[20].
X[5].
ZZZZ .99.
45
02
FILLER
PIC
X[5].
02
DEDUCTIONS
PIC
ZZZZ .99.
02
FILLER
PIC
X[5].
02
ALLOWANCES
PIC
ZZZZ .99.
02
FILLER
PIC
X[5].
02
NET-PAY
PIC
ZZZZ. .99.
Suppose it is required that the data stored in the four fields of PAY_REC should be
moved to those fields of PRINT_REC that are given the same data names. The following
four MOVE statements can serve the purpose.
MOVE ID-NUMBER OF PAY-REC TO ID-NUMBER OF PRINT-REC.
MOVE NAME OF PAY-REC TO NAME OF PRINT-REC.
MOVE DEPARTMENT OF PAY-REC T0 DEPARTMENT OF PRINT-REC.
MOVE BASIC-PAY OF PAY-REC TO BASIC-PAY OF PRINT-REC.
However, since both the records have same names for the concerned data items, the
following statement
MOVE CORRESPODING PAY-REC TO PRINT-REC.
will have the same effect. It is not necessary that the corresponding data names in the two
records should appear in the same order.
The general format of the MOVE
CORRESPONDING statement is
CORRESPONDING
MOVE
identifier-1
TO identifier-2
CORR
where dentifier-1 and identifier-2 should be group names.
Note that MOVE
CORRESPONDING is not a group move, it is merely a means for specifying a number of
elementary moves through a single MOVE statement. As such any editing, if specified, will
be performed. Source and destination groups can include data names that are not common.
Only those fields having identical names in the two records will take part in the data
movement. The remaining data items in the destination group will remain unchanged.
9.2 ADD and SUBTRACT CORRESPONDING
The CORRESPONDING option can also be used with the ADD and SUBTRACT verbs.
The following are the formats of these verbs with the CORRESPONDING option.
CORRESPONDING
ADD
identifier-1
TO identifier-2
identifier-1
TO identifier-2
CORR
CORRESPONDING
SUBTRACT
CORR
46
In the case of the ADD statement numeric elementary items in the group referred to by
identifier-1 are added to and stored in the corresponding elementary items of the group
named in identifier-2. In the case of the SUBTRACT statement, the corresponding numeric
elementary items of the group referred to by identifier-1 are subtracted from and are stored in
the corresponding numeric elementary items of the group referred to by identifier-2.
9.3 GENERAL RULES CONCERNING CORRESPONDING OPTION
The following rules should be observed when the CORRESPONDING option is used.
(i)
(ii)
(iii)
(iv)
(v)
(vi)
Identifier-1 and identifier-2 in all cases must refer to group items i.e., these
identifiers must not be data items with level numbers 66, 77 or 88.
Data items in identifier-1 and identifier-2 take part in the specified operation
(MOVE, ADD or SUBTRACT) only when they have the same data name and
same qualifiers up to but not including identifier-1 and identifier-2.
In the case of ADD or SUBTRACT CORRESPONDING only numeric data
items are considered for addition or subtraction respectively. This means that
data items other than numeric are not considered for the arithmetic operations
even though they may have identical names in the two groups named in
identifier-1 and identifier-2.
All data items subordinate to identifier-1 and identifier-2 with level numbers 66
or 88 or containing a REDEFINES or OCCURS clause, are ignored for the
purpose of the operation. Identifier-1 and identifier-2 may, however, have a
REDEFINES or OCCURS clause or may be subordinate to data items having a
REDEFINES or OCCURS clause.
FILLER data items are ignored.
CORRESPONDING items can have different locations within the group and
the field sizes can also be different.
Examples
Let us consider the following DATA DIVISION entries.
01
OLD-REC.
02
FIRST-PART.
03
ITEM-1
PIC
03
ITEM-2
PIC
03
ITEM-3
PIC
02
02
01
999.
999.
9[5].
SECOND-PART.
03
SEC-1
PIC
03
SEC-2.
04 SEC-21 PIC
X[5].
THIRD-PART.
03
THIRD-1
03
THIRD-2
PIC
PIC
XXX.
999.
PIC
PIC
PIC
PIC
9999.
9[3].
X[5].
X[21].
NEW-REC.
02
FIRST-PART.
03
ITEM-1
03
ITEM-2
03
ITEM-3
03
ITEM-4
9[4].
47
02
SECOND-PART.
03
SEC-1
03
SEC-21
PIC
PIC
X[4].
X[5].
02
FOURTH-PART.
03
THIRD-1
PIC
XXX.
03
THIRD-2
PIC
999.
Now, let us see which data items will be moved if the PROCEDURE DIVISION
contains the statement MOVE CORRESPONDING OLD-REC TO NEW-REC. The said
data items are ITEM-1, ITEM-2, ITEM-3 and SEC-1. Note that SEC-21, THIRD-1 and
THIRD-2 cannot take part in the operation. This is because although those names are
common to both the groups, their qualifiers are different. If, on the other hand, the
PROCEDURE DIVISION statement is ADD CORRESPONDING OLD-REC TO NEWREC, only ITEM-1 and ITEM-2 will take part in the add operation. This is because ITEM-3
and SEC-1 in NEW-REC are not numeric data items.
9.4 ROUNDED OPTION
Let us consider the following DATA DIVISION entries.
77
A
PIC
99V999
VALUE
IS
23.412.
77
B
PIC
99V999
VALUE
IS
35.273.
77
C
PIC
99V9
VALUE
IS
41.5.
Now, after the execution of the statement ADD A B GIVING C, C will contain
58.6 instead of 58.685 as C can retain only one digit after the decimal point. Instead of this
usual truncation, rounding can be specified through the ROUNDED option. The ROUNDED
option can be specified as follows:
ADD
A
B
GIVING
C
Now, the content of C will be 58.7 instead of 58.6.
ROUNDED
It may be noted from the above example that whenever as arithmetic operation is
executed, if the number of places in the fractional part of the result happens to be greater than
the number of placed provided for the fractional part in the receiving field, truncation will
occur. However, if the ROUNDED option is specified, 1 is added to the last digit whenever
the most significant digit being thrown out is greater than or equal to 5. In the example
shown here the most significant digit of the excess is 8 which is greater than 5. Therefore, 1
has been added to 6 which is the last digit of the receiving field. On the other hand, if A and
B contains 23.412 and 35.213 respectively, both the statements
ADD
GIVING
ADD
GIVING
and
ROUNDED
will give the same result and in both the cases C will have the value 58.6.
The ROUNDED option can be specified in the case of any arithmetic verb by writing the
word ROUNDED after the identifier, denoting the field that receives the result of the
48
operation. The ROUNDED phrases cannot be specified for the identifier that receives the
remainder in the DIVIDE operation.
9.5 ON SIZE ERROR OPTION
If after an arithmetic, the result exceeds the largest value that can be accommodated in
the result, the error is called a size error. To take an example, let A and B be two elementary
items with pictures 99 and 999 respectively. Suppose also that the current values of the two
fields are 35 and 980 respectively. Now, the execution of the statement ADD A To B causes
a size error. This is because the result field B is not large enough to hold the result of the
addition, namely, 1015.
When a size error occurs, the contents of the result field after the operation is
unpredictable. However, the processing is not terminated and the computer will proceed with
the execution of the next statement regardless of the fact that a size error occurred.
Therefore, it is the responsibility of the programmer to monitor the arithmetic operation by
specifying the ON SIZE ERROR phrase at the end of the arithmetic statement. It has the
following syntax:
;
ON SIZE ERROR imperative - statement
When this phrase is specified the imperative statement gets executed, if an ON SIZE
ERROR occurs. Thus a statement
ADD A TO B ON SIZE ERROR GO TO ERROR-PARA.
will cause the control to be transferred to ERROR-PARA in the case of a size error.
Otherwise, the effect will be the same as that of ADD A TO B. When the ON SIZE ERROR
phrase is specified, the arithmetic statement must be terminated by a period.
The ON SIZE ERROR phrase enables a programmer to take measures in case a sizeerror condition arises. However, specifying the ON SIZE ERROR phrase with each and
every arithmetic operation can increase the execution time of the program. Thus when the
programmer is sure that there is no possibility of a size error, the phrase may not be specified.
In this connection it is recommended that the programmer should give the result fields
enough room so that size error does not occur.
It may be worthwhile to note the differences between the ROUNDED and SIZE ERROR
options. The ROUNDED option is concerned with the case when a loss of digits occurs at
the right end. This loss merely makes the result approximate, but the result is not altogether
wrong. The ROUNDED option only affects the nature of approximation. If specified, the
result is approximately by rounding. Otherwise, it is approximated be truncation. On the
other hand, SIZE ERROR is concerned with the case when a loss of digits occurs in the most
significant part (left end). The result in such a case is totally wrong.
9.6 LET US SUM UP
In the present lesson the learner is exposed to the corresponding options with MOVE/
ADD/SUBTRACT. Points about the rounded option and size error option are also discussed.
49
50
10.3
10.4
10.5
10.6
10.7
Let us Sum Up
10.8
10.9
Lesson-end Activities
Points for Discussion
10.10
References
S9(3)
S9(3)
S9(4)
+z(4)
V9(2)
V9(2)
V9(2)
Value 0
51
PARA - 1
Explanation : This program gets 2 inputs from user.
It adds them using ADD verb.
c=a+b
The unedited result is available in c.
We move c to e-c, where edit characters are available.
Note that the variable e-c makes use of the + edit character.
Result is displayed with e-c.
10.2 PROGRAM FOR SUBTRACT VERB
Write a simple program to demonstrate SUBTRACT verb. Use edit characters also in
the program.
Identification division.
Program- id. Subverb.
Environment division.
Data division.
Working-storage section.
77 a pic s9(3)v9(2) value 0.
77 b pic s9(3)v9(2) value 0.
77 e-b pic +z(3).z(2).
Procedure division.
Para-1.
Display(1 1) erase.
Display(3 5) Enter first number :.
Accept a.
Display(5 5) Enter second number :.
Accept b.
Subtract a from b.
Move b to e-b.
Display(15 5) b-a = e-b.
Stop run.
Explanation : This program gets 2 inputs from user.
It subtracts them using SUBTRACT verb.
b-a is calculated and stored in b.
After execution : OLD value of a is same
OLD value of b is lost and
b-a is stored in b.
The unedited result is available in b.
We move b to e-b, where edit characters are available.
Note that the variable e-b makes use of the + edit character.
Result is displayed with e-b.
10.3 PROGRAM FOR MULTIPLY VERB
Write a simple program to demonstrate MULTIPLY verb. Use edit characters also in the
program.
Identification division.
Program- id. Mulverb.
Environment division.
52
Data division.
Working-storage section.
77 a pic s9(3)v9(2) value 0.
77 b pic s9(3)v9(2) value 0.
77 c pic s9(4)v9(2) value 0.
77 e-c pic - z(4).z(2).
Procedure division.
Para-1.
Display(1 1) erase.
Display(3 5) Enter first number :.
Accept a.
Display(5 5) Enter second number :.
Accept b.
Multiply a by b giving c.
Move c to e-c.
Display(15 5) Product = e-c.
Stop run.
Explanation : This program gets 2 inputs from user.
It multiplies them using MULTIPLY verb.
a*b is found and stored in c.
The unedited result is available in c.
We move c to e-c, where edit characters are available.
Note that the variable e-c makes use of the - edit character.
Result is displayed with e-c.
10.4 PROGRAM FOR DIVIDE VERB
Write a simple program to demonstrate DIVIDE verb. Use edit characters also in the
program.
Identification division.
Program- id. Divverb.
Environment division.
Data division.
Working-storage section.
77 a pic s9(3)v9(2) value 0.
77 b pic s9(3)v9(2) value 0.
77 c pic s9(4)v9(2) value 0.
77 e-c pic - z(4).z(2).
Procedure division.
Para-1.
Display(1 1) erase.
Display(3 5) Enter first number :.
Accept a.
Display(5 5) Enter second number :.
Accept b.
Divide a by b giving c.
Move c to e-c.
Display(15 5) Answer = e-c.
Stop run.
53
54
Identification division.
Program- id. compverb.
Environment division.
Data division.
Working-storage section.
77 a pic s9(3)v9(2) value 0.
77 b pic s9(3)v9(2) value 0.
77 c pic s9(4)v9(2) value 0.
7 e-c pic +z(4).z(2).
Procedure division.
Para-1.
Display(1 1) erase.
Display(3 5) Enter first number :.
Accept a.
Display(5 5) Enter second number :.
Accept b.
Compute c= a+b.
Move c to e-c.
Display(15 5) Answer = e-c.
Stop run.
10.7 LET US SUM UP
With the help of the above programs one can understand the working nature of
arithmetic verbs like Add, Subtract, Multiply, Divide and Compute. Also one can acquire
knowledge about size error options.
10.8
LESSON-END ACTIVITIES
Try to find the answers for the following exercises on your own.
1. Write a Program to add 4 values using ADD verb.
2. Write a Program to subtract the 4th value from the first 3 values using SUBTRACT
verb.
3. Write a Program to multiply 5 values and store the result in 6th variable..
4. Write a Program to convert the temperature given in Centigrade to Fahrenheit using
COMPUTE verb. ( Hint : F= 1.8C+32)
55
UNIT III
LESSON 11: CONDITIONS
CONTENTS
11.0
11.1
11.2
Condition
Relational condition
11.3
Sign Condition
11.4
Class Condition
11.5
11.6
Condition-name Condition
Negated Simple Condition
11.7
Compound Condition
11.8
Let us Sum Up
References
Relational condition
Sign condition
Class condition
Condition-name condition
Negated simple condition and
Compound condition.
GREATER
>
THAN
THAN
56
IS [NOT] LESS
THAN
IS [NOT]
<
THAN
IS [NOT] EQUAL
TO
IS [NOT]
=
It was stated earlier that the operands can be an identifier or a literal. However, either
operand can also be an arithmetic expression but must contain at least one reference to an
identifier. Sometimes, operand-1 and operand-2 are respectively referred to as the subject and
object of the relational condition.
Comparison of Numeric Operands
We are familiar with the kind of relational condition where both the operands are
numeric. The comparison in this case is algebraic and the two operands can be compared
regardless of the size and USAGE of the fields.
Comparison of Nonnumeric Operands
A nonnumeric operand (identifier/literal other than numeric) can be compared to another
nonnumeric operand according to the following rules.
(i) Fields of Equal Sizes
Characters in the corresponding positions are compared to determine the value of the
relational condition. Comparison starts with the leftmost character in both the fields and
proceeds in a left to right manner. If the two characters being compared are found to be
unequal at any stage, the field containing the greater (according to the collating sequence of
the computer (NATIVE) or that specified by the PROGRAM COLLATING SEQURNCE
clause in the OBJECT-COMPUTER paragraph) characters is considered to be greater. Only
when the characters are found to be identical does the comparison proceed to the next
position on the right. Two fields are taken to be equal only when all such pairs of characters
have been found to be identical and the rightmost end has been reached.
(ii) Fields of Unequal Sizes
If the two operands are not of equal size, the shorter field is considered to be extended
on the right by spaces to make its size equal to the longer field and the rules for comparing
fields of equal sizes are used.
Comparison of a Numeric Operand with a Nonnumeric Operand
A numeric operand can be compared to a nonnumeric operand subject to the following
restrictions.
(i) The numeric operand must be an integer data item or integer literal.
(ii) Both the operands must have the same USAGE (DISPLAY or some
form of DISPLAY).
At the time of comparison, the numeric operand is treated as if its value were moved to
an alphanumeric item were then compared to the nonnumeric field.
Group Item as an Operand in Relational Condition
When an operand of a relational condition is a group item, the said item is considered to
be an alphanumeric field.
The following examples illustrate the results of different comparisons. Usage DISPLAY
is assumed in all cases.
57
________________________________________________________________
A (Operand-1)
B (Operand-2)
__________________________________________________ Result of
Picture
Value
Picture
Value
Comparison
X(3)
001
X(4)
0001
A>B
X(4)
3254
X(3)
325
A>B
X(3)
BOY
X(4)
GIRL
A<B
X(3)
BOY
X(4)
BIRD
A>B
X(3)
BOY
X(4)
BOYb
A=B
9(3)
354
X(2)
46
A<B
-46
X(2)
46
A=B
354
9(2)
46
A>B
S9 (2)
LEADING
SEPARATE
9(3)
POSITIVE
NEGATIVE
ZERO
When arithmetic expression is used, it must contain at least one identifier. The
POSITIVE option determines the value of the condition to be true only if the value of the
operand strictly positive. This means that the value zero is not treated as positive.
The following examples illustrate the use of the sign condition.
Example 1
77
BALANCE
PIC
S9 (6) V99.
.
.
IF
BALANCE IS
ZERO GO TO NIL-BALANCE.
It may be noted that the above IF statement is equivalent to the following statement that
makes use of a relational condition.
IF
BALANCE
GO TO NIL-BALANCE.
58
Example 2
02
02
IF
DEPOSIT
PIC 9(4) V99.
WITHDRAWAL
PIC 9(4) V99.
.
.
.
DEPOSIT -WITHDRAWAL IS POSITIVE
CALCULATION.
GO TO
The control is transferred to the paragraph named CALCULATION if the current value
of DEPOSIT is greater than that of WITHDRAWAL.
In general, any sign condition can be replaced by an equivalent relational condition. The
use of the sign condition may perhaps be convenient in certain cases and its use may also
increase the readability of the statement that uses it.
11.4 CLASS CONDITION
The class condition determines whether or not the value of an operand is numeric or
alphabetic. An operand is numeric if it contains only the digits 0 to 9 with or without an
operational sign. An operand is alphabetic if it contains only the letters A to Z and space. The
format of the class condition is as follows:
Identifier
IS
[NOT]
NUMERIC
ALPHABETIC
The following rules apply in the case of a class condition.
(i)
59
punching mistake in the data card can go and detected unless proper care is taken. One may
avoid some of these blunders (though not all) through the use of class condition.
Let BASIC-PAY be a data name in a card record defined with picture
9(5) V99. Having read the card we can test the value of BASIC-PAY to ensure that the data
on the card is actually numeric. This can be done as follows
IF BASIC-PAY IS NOT NUMERIC GO TO PARA-ERROR.
If the data contains any character other than digits, control will be transferred to PARAERROR. Otherwise, control will go to the next sentence in sequence. It may be noted that the
data must be punched with leading zeros, if any, and not with leading spaces. The space
character is considered to be an alphabetic character.
11.5 CONDITIONS-NAME CONDITION
A condition name is an entity which itself is a condition and as such can have either a
true or false value. However, a condition name cannot be defined independently. It must
always be associated to a data name called the conditional variable. The condition name may
be defined in any section of the DATA DIVISION and must be placed immediately after the
entry that defines the conditional variable. There can be more than one condition names
associated to a conditional variable. In that case all the condition name entries must follow
the entry defining the conditional variable.
A condition name entry specifies either a single value or a set of values and/or a range of
values for the conditional variable. The condition name becomes true whenever the
conditional variable assumes any of these values. Otherwise, the condition name is set to
false. It must be noted that it is not possible to set the value of a condition name explicitly.
The value of a condition name is always set implicitly depending on the current value of the
conditional variable. The format of the condition name entry is given below.
VALUE
IS
88 condition- name
THRU
Literal-1
VALUES
ARE
literal-2
THROUGH
THRU
, literal-3
literal-4
THROUGH
The following rules apply for a condition name.
(i)
(ii)
(iii)
(iv)
Condition names must be described at level 88. The level number begins in
margin A or any position after it. The condition name must begin from margin
B or any position after it. There must be at least one space between the level
number and condition name.
The normal rules for naming a data item also apply in the case of a condition
name.
If the same condition name is used in more than one place, the condition name
must be qualified by the name of its conditional variable.
The name of the conditional variable can be used as a qualifier for any of its
condition names. If the reference to a conditional variable requires
60
61
names. The main advantage of a condition name is that it increases the readability of the
statement that uses it. Certainly, the use of the condition name WIDOWED conveys more
information to a reader of the program than the use of the relational condition MARITALSTATUS =2. Precisely for this reason, it is recommended that whenever possible, meaningful
condition names should be used in a program.
11.6 NEGATED SIMPLE CONDITION
Any of the simple condition described above can be preceded by the logical operator
NOT. The effect of placing the operator NOT before a simple condition is to reverse the
value of the condition. It may be seen that the operator NOT can be used in two ways. In
simple conditions it can be used as a part of the condition. It can also be used to precede a
simple condition to make it a negated simple condition. An example of the first use may be
DEPOSIT NOT LESS THAN 500.00 while an example of the second use is Not DEPOSIT
LESS THAN 500.00. Of course, in this case, both the conditions mean the same thing and
can be used in either form. What matters is the role of the operator NOT. In the former case
NOT is part of a relational operator and in the latter case it is a logical operator. However,
NOT must not precede a simple condition that includes NOT as a part if it.
11.7 COMPOUND CONDITION
Two simple conditions can be connected by the logical operators AND or OR to form a
compound condition (also known as combined condition). When two conditions are combined by
AND, the compound condition becomes true only when both the constituent conditions are true.
In all other cases the compound condition is false. On the other hand, if OR is used to combine
two conditions, the compound condition is true if either or both the constituent conditions are
true. It is false only when both the conditions are false.
For example, the compound condition AMOUNT GREATER THAN 499 AND AMOUNT
LESS THAN 1000 is a compound condition which will be true only when the value of
AMOUNT is in the range 500 to 999(inclusive of both). This is because both the simple
conditions are true for these values of AMOUNT. For other values of AMOUNT, only one of
them is true. Similarly, the compound condition AMOUNT LESS THAN 500 OR AMOUNT
GREATER THAN 999 will be false only when the value of AMOUNT is in the range 500 to
999.
A compound condition can consist of any number of simple or negated simple conditions
joined either by AND or OR. Compound conditions in such cases are resolved as follows.
Negated simple conditions are evaluated first. This is followed by the evaluation of pairs of
resulting conditions around each AND in a left-to-right order. After this the resulting conditions
around each OR are evaluated in a left-to-right manner. If required, parentheses can be used in
compound conditions. In such cases all the conditions within the parentheses are evaluated first in
accordance with the above rules. When parentheses are used within parentheses, evaluation
proceeds from the least inclusive pair of the parentheses to the most inclusive pair.
In general, a compound condition has the following form:
Condition-1
AND
Condition-2
OR
62
When the subjects in the consecutive relational conditions are identical, the
subject May be omitted from the one where it appears first.
(ii)
when the subjects and relational operators in the consecutive relational
conditions are Identical, the subject as well as the relational condition may be
omitted, the subject as well as the except from the one where they appear.
Some examples of abbreviation are given below.
Example 1
The compound condition
AMOUNT GREATER THAN 499 AND AMOUNT LESS THAN 1000
can be abbreviated to
AMOUNT GREATER THAN 499 AND LESS THAN 1000
Here, the second appearance of the common subject AMOUNT has been omitted.
Example 2
The compound condition
CARD-CODE = 3 OR CARD-CODE = 5 OR CARD-CODE = 7
may be abbreviated to
CARD-CODE = 3 OR 5 OR 7
Here, the subjects as well as the relational conditions in the given compound condition
are identical. Consequently, the second and third appearances of the subject and the relational
condition have been omitted.
The consecutives relational conditions that are being considered for abbreviation may
63
also contain the word NOT. In this case the interpretation of the abbreviated condition can
become ambiguous. To resolve the ambiguity the following rule has been recommended in
the ANS I standard. The word NOT preceding a relational operator in an abbreviated
condition is considered part of the relational operator. Otherwise, NOT is considered to be a
logical operator negating the condition preceded by it. The following examples can help to
understand this rule.
Example 3
The condition
AGE LESS THAN 30 AND NOT LESS THAN 20 OR 40
is interpreted to be an abbreviation of the compound condition
AGE LESS THAN 30 AND AGE NOT LESS THAN 20 OR AGE NOT LESS
THAN 40
This is because NOT precedes the relational operator LESS THAN in the abbreviated
condition and as such it is interpreted to be a part of the relational operator NOT LESS
THAN.
Example 4
The condition
NOT AGE LESS THAN 20 AND 30
will be interpreted to be an abbreviation of
NOT AGE LESS THAN 20 AND AGE LESS THA 30.
Here, NOT precedes the data name AGE. It is therefore not considered to be part of the
relational operator LESS THAN which has been abbreviated.
11.8 LET US SUM UP
In the present lesson we have focused our attention in learning what is meant by
condition and the different forms of them with sufficient examples. The learner with this
knowledge will certainly be in a position to include them in programs whenever the need
arises.
11.9 LESSON-END ACTIVITIES
Try to find the answers for the following exercises on your own.
1. What do you mean by conditions?
2. Explain about Relational condition
3. Explain about Sign condition
4. Explain about Condition Names
5. What do you mean by compound conditions? Explain.
11.10 POINTS FOR DISCUSSION
1) Write notes on SIGN condition.
2) What do you mean by condition-Name Condition? Explain.
3) Explain in detail about compound condition
11.11 REFERENCES
1) COBOL Programming , M.K.Roy & Ghosh Dastidar , Tata McGraw Hill, 2nd
Edition,1998
2) COBOL Programming , V. RAJARAMAN, PHI Pub
3) Introduction to COBOL programming Dr. R.Krishnamoorthy, JJ Publ
4) Structured COBOL , Welburn, TataMcGraw Hill , 4th Edition.
64
12.1
12.2
IF statement
IFELSE statement
12.3
Nested IF statement
12.4
Let us Sum Up
12.5
12.6
Lesson-end Activities
Points for Discussion
12.7
References
Identifier-1
Literal -1
Identifier-2
Litreal-2
If the condition-1 becomes true then statement-1 will be executed. Statement-1 can be a
simple statement or a compound statement. If the condition fails then control goes out to the
next statement.
Example :
1)
IF A > B DISPLAY A IS BIG
2)
12.2
IF ELSE STATEMENT
We are already familiar with the simple form of the IF statement. The general form of
the IF statement is as follows:
65
statement-1
IF condition ;
statement-2
;ELSE
NEXT SENTENCE}
NEXT SENTENCE
The condition can be any one of the conditions discussed above. Each of statement-1
and statement-2 represents one or more COBOL statement. When more then one statement is
specified they must be separated by one or more spaces or by an optional semicolon (;) or
comma (,). During execution, if the condition is found to be true, the statements represented
by statement-1 are executed. On the other hand, if the condition is found to be false, the
statements represented by statement-2 are executed. For ease of reference, we shall call the
statements represented by statement-1 and statement-2 as then part and else part respectively.
It may be noted that either the then Part or else part is executed depending on the value of the
specified condition. After that the control implicitly goes to the statement that immediately
follows the IF sentence.
Normally, an If statement should be terminated by a period (.) followed by a blank (see
next section for exception). For this reason an IF statement is often referred to as an IF
sentence. Sometimes, we encounter situations where no action needs to be specified if the
condition is true, but some actions are necessary if the condition is false. In that case, the
NEXT SENTENCE phrase can be used for the then part and the else part can be written to
the indicate the actions required. Similarly, the NEXT SENTENCE phrase can replace the
else part if no action is required when the condition is false. The NEXT SENTENCE phrase
indicates that the control should pass to the statement that follows the IF sentence. Note that
if no action needs to be specified for the else part, the phrase ELSE NEXT SENTENCE,
being optional, can be omitted. It is in this form that we have used the IF statement so for.
However, the phrase ELSE NEXT SENTENCE may not be omitted in certain cases.
The following examples illustrate the use of IF statement.
Example 1
IF QUANTITY IS NUMERIC AND QUANTITY IS POSITIVE
MOVE ZERO TO ERROR-CODE. COMPUTE SALES VALUE=QUANTITY*RATE
ELSE MOVE 1 TO ERROR CODE
MOVE ZERO TO SALES-VALUE
The specified condition tests whether or not the current value of the data name
QUANTITY is numeric as well as positive. If the condition is true ERROR-CODE is set to
zero and SALES-VALUE is computed by multiplying QUANTITY by RATE. On the other
hand, if the condition is FALSE, ERROR CODE is set to 1 and SALES-VALUE is set to
zero. In either case the control goes implicitly to the next statement after this IF sentence. The
above sentence is equivalent to the following flowchart.
66
No
IS
QUANTITY
numeric and
positive?
Yes
ERROR-CODE=0
SALES-VALUE=
QUANTITY X RATE
ERROR-CODE=1
SALES-VALUE=0
Example 2
IF OK-BALANCE NEXT SENTENCE ELSE MOVE 2 BALANCE-CODE
Here, OK-BALANCE is a condition name. No action is specified if this condition is
true. If the condition is false, BALANCE-CODE should be set to 2. The sentence is
equivalent to the following flow chart.
True
OKBALANC
E?
False
BALANCE-CODE=2
It may be noted that any If sentence can be alternatively written by just negating the
condition. In order to retain the meaning of the original sentence, the then and else parts are
to be interchanged. Thus the following sentence has the same meaning as the one illustrated
above.
IF NOT OK-BALANCE MOVE 2 TO BALANCE-CODE ELSE NEXT-SENTENCE
If desired, the ELSE NEXT SENTENCE phrase may be dropped to get the following
equivalent form.
IF NOT OK-BALANCE MOVE -2 TO BALANCE-CODE.
67
68
IS ACCOUNTCODE = OLDACCOUNT
Yes
Add TRANS-VALUE
to TRANS-TOTAL
No
IS TRANSVALUE
>1000?
Add 1 to HIGHCOUNT
Add 1 to LOWCOUNT
Example 2
Consider the following nested sentence:
IF STAFF-CODE =1
k IF DAYS-WORKED IS GREATER THAN 175
j MOVE 1 TO BONUS-CODE
ELSE NEXT SENTENCE
j
ELSE IF DAYS-WORKED IS GREATER THAN 205
k l MOVE 2 BONUS-CODE
ELSE NEXT SENTENCE.
l
The IF-ELSE pairs in this sentence can be detected by applying the rule stated above.
We indicate the IF-ELSE associations by marking each pair with identical numbers within
circle. The sentence can now be easily recognized as an implementation of the following flow
chart.
69
No
IS DAYSWORKED
205?
IS STAFFCODE=1?
Yes
Yes
IS DAYSWORKED
175?
Yes
No
No
BONUS-CODE=2
BONUS-CODE=1
It can also be seen that while the last ELSE NEXT SENTENCE phrase can be dropped,
it is not possible to drop the first ELSE NEXT SENTENCE phrase. If this first phrase is
omitted, the pairing of IFs and ELSEs will be disturbed. It is left as an exercise to verify
that the BONUS-CODE will then remain unchanged if the STAFF-CODE is other than the 1.
Although the same action will be taken when STAFF-CODE is equal to 1, it is worth while to
observe that this is because the condition (DAYS-WORKED IS GREATER THAN 205) in
the last IF statement can never be true.
Therefore, we observe the ELSE NEXT SENTENCE phrase is useful in certain cases.
The phrase also increases the readability. Therefore, the use of NEXT SENTENCE either in
the then or else parts of an IF statement is recommended. The only exception can be when the
ELSE NEXT SENTENCE phrase is immediately followed by the terminating period of the IF
sentence. This is because in this case the said ELSE must apply to the IF of the most
inclusive IF statement of the nesting. Therefore, the control will be transferred to the next
sentence regardless of whether or not the ELSE NEXT SENTENCE phrase is explicitly
included.
12.4 LET US SUM UP
The above lesson has introduced the learner the IF statement and its variants with
examples. With this knowledge the learner can make use of these statements whenever the
need arises to use them. Most of the programs will be making use of IF statement. Nested IF
statement has to be used carefully.
70
REFERENCES
1. COBOL Programming , M.K.Roy & Ghosh Dastidar , Tata McGraw Hill, 2nd
Edition,1998
2. COBOL Programming , V. RAJARAMAN, PHI Pub
3. Introduction to COBOL programming Dr. R.Krishnamoorthy, JJ Publ
4. Structured COBOL , Welburn, TataMcGraw Hill , 4th Edition.
71
13.2
13.3
13.4
13.5
Let us Sum Up
13.6
13.7
Lesson-end Activities
Points for Discussion
13.8
References
procedure-name-1
THRU
procedure-name-2
THROUGH
The statement group beginning with the first statement of the procedure named in
procedure-name-1 and ending with the last statement of the procedure names in procedurename-2, constitutes the range consists of the statements contained in the procedure referred to
by procedure- name-1. when the simple PERFORM statement is executed, this range is
executed only once.
Some examples of the PERFORM statement are given below.
72
Example 1
PERFORM CALCUALTE-TAX.
In this example, CALCULATE-TAX is either a section name or paragraph name. Suppose it
is a section name. All the statements contained in this section will be executed as a result of
the execution of the PERFORM statement and after the execution of these statements, the
control will come back to the statement following the PERFORM statement.
Example 2
PERFORM BEGIN-CALCULATION THRU END-CALCULATION.
Suppose, BEGIN-CALCULATION and END-CALCULTION are paragraph names.
The execution of the above PERFORM statement will cause the execution of the group of the
statements starting with the first statement of BEGIN-CALCULATION and ending with the
last statement of end-calculation. It may be noted that there may be other paragraphs in
between these two paragraphs. All these paragraphs area also included in the range. Upon the
execution of the range, the control returns to the statement following the PERFORM
statement.
It may be noted that the return of control after the execution of the statements in the
specified range takes place implicitly. This means that at the end of the range, the
programmer should not put any statement (such as GO TO) to transfer the control explicitly
to the statement following the PERFORM statement. The compiler establishes a return
mechanism at the end of the range and it is this mechanism which is responsible for the return
of the control.
The following points may be noted in connection with the range of a PERFORM
statement.
(i)
(ii)
(iii)
(iv)
73
normal way. After the execution of the last statement of the range, the control
falls through the next statement following the range.
13.2 PERFORM WITH TIMES OPTION
The format of PERFORM TIMES statement is as follows:
PERFORM
procedure-name-1
THRU
procedure-name-2
THROUGH
Identifier
integer
Example :
1)
TIMES
2)
Perform para-2 thru para-5 n times.
In this case the specified range of all paragraphs from para-2 to para-5 will be
repeatedly executed n times. Note that the value of n should be available before this
statement gets executed.
13.3 PERFORM WITH UNTIL OPTION
The format is as follows:
PERFORM
procedure-name-1
THRU
procedure-name-2
THROUGH
UNTIL condition
Examples :
1)
2)
procedure-name-1
THRU
procedure-name-2
THROUGH
74
VARYING
BY
Examples :
identifier-1
Index- name-1
identifier-3
Literal-2
1)
2)
3)
FROM
identifier-2
index-name-2
Literal-1
UNTIL condition
13.5
LET US SUM UP
The learner has just now been introduced the fascinating forms of PERFORM
statements with their syntaxes and examples. The learner has been completely explained
about Simple PERFORM, PERFROMTHRU, PERFORM TIMES, PERFORM
UNTIL and PERFORM VARYING options. This lesson will make the learner to use the
most appropriate form of PERFORM that suits based on the purpose of work.
13.6 LESSON-END ACTIVITIES
Try to find the answers for the following exercises on your own.
1.
2.
3.
4.
5.
75
14.2
14.3
14.4
REDEFINES CLAUSE
Rules of REDEFINES clause
14.5
Let us Sum Up
14.6
Lesson-end Activities
14.7
14.8
PAY-REC.
03
FIXED PAY.
05
BASIC PAY
PIC
9(6) V99
05
DEARNESS-ALLOWANCE
PIC
9(6) V99
03
ADDITIONAL PAY
05
HOUSE - RENT
PIC
9(4)V99
05
MTHLY - INCENTIVE
PIC
9(3)V99
03
DEDUCTIONS.
05
PF DEDUCT
PIC
9(3)V99
05
IT DEDUCT
PIC
9(4)V99
05
OTHER - DEDUCT
PIC
9(3)V99
66
PAY-OTHER-THAN-BASIC RENAMES DEARNESS-ALLOWANCE THRU
MTHLY-INCENTIVE
66
IT-AND-PF-DEDUCTIONS RENAMES PF-DEDUCT THRU IT-DEDUCT
In the example, PAT-OTHER-THAN-BASIC will become a new group consisting of
DEARNESS-ALLOWANCE, HOUSE-RENT and MTHLY-INCENTIVE. Note that the new
group overlaps on two original groups, namely, part of FIXED-PAY and the entire
ADDITIONAL-PAY. Such overlapping is allowed provided the elementary items are all
contiguous. In a similar way IT-AN-DEDUCTIONS has two elementary items PF-DEDUCT
76
and IT-DEDUCT. This new group is formed out of the original group deductions.
Alternatively, the same thing can also be done in the original description itself by placing the
IT-AND-PF-DEDUCTIONS at level 04 under DEDUCTIONS. The exact syntax of the
RENAMES clause is as follows:
66
14.2
SALES-RECORD
02
SALES-TYPE
PIC
9.
02
SALES-BY-UNTI.
03
QTY
PIC
9(4).
03
UNIT-PRICE PIC
9(8) V99.
02
TOTAL-SALES
REDEFINES SALES-BY-UNIT
03
AMOUNT
PIC
9(10) V99.
03
FILLER
PIC
X (2).
This example describes a sales record which may either contain the total amount of sale
(AMOUNT) or the quantity (QTY) and UNIT-PRICE. The purpose of such description may
be to have two types of records and their types may be determined from the data item named
SALES-TYPE. Depending on some predetermined values of SALES-TYPE the record will
be interpreted in one of the two forms, Note that SALES-BY-UNIT and TOTAL-SALES
refer to the same storage space. They really represent two different mappings of the same
storage area.
77
The REDEFINES clause as illustrated above are quite common in use. However, the
clause may be simply used for the purpose of conservation of storage space possibly in the
working-storage section. In such cases two records having no meaningful connection between
them can also be used to share same storage space provided both of them are not used in the
program simultaneously. The syntax of the REDEFINES clause is as follows:
Level- number daa-name-1 REDEFINES data-name-2
14.4
(i)
(ii)
(iii)
(iv)
(v)
78
REFERENCES
1. COBOL Programming , M.K.Roy & Ghosh Dastidar , Tata McGraw Hill, 2nd
Edition,1998
2. COBOL Programming , V. RAJARAMAN, PHI Pub
3. Introduction to COBOL programming Dr. R.Krishnamoorthy, JJ Publ
4. Structured COBOL , Welburn, TataMcGraw Hill , 4th Edition.
79
15.1
15.2
Program for IF
Program for IF ELSE
15.3
15.4
15.5
15.6
15.7
15.8
15.9
15.10
Let us Sum Up
Lesson-end Activities
15.11
15.12
References
80
ABC
DEF
XYZ
81
Data division.
Procedure division.
Para-1.
Display(1 1) erase.
Display ABC.
Perform para-2 thru para-4.
Display XYZ.
Stop run.
Para-2.
Display DEF.
Para-3.
Display GHI.
Display Gandhi.
Para-4.
Display Bharathiar.
The output of the above program will be
ABC
DEF
GHI
Gandhi
Bharathiar
XYZ
82
Identification division.
Program- id. PerfVary.
Environment division.
Data division.
Working-storage section.
01 n pic 9(2) value 0.
01 i pic 9(2) value 1.
01 sum pic 9(4) value 0.
Procedure division.
Para-1.
Display(1 1) erase.
Display(5 5) Enter a Number .
Accept n.
Perform calc-para varying i from 1 by 1 until i > n.
Display(10 5) Sum = sum.
Stop run.
Calc-para.
Compute sum = sum + i.
15.7 PROGRAMS FOR REDEFINES CLAUSE
Write a simple program to explain REDEFINES clause at 01 level.
identification division.
program- id. Redef.
environment division.
data division.
working-storage section.
01 a pic 9(3) value 125.
01 r pic 9(2) redefines a.
procedure division.
p-1.
display(1 1) erase.
display(5 5) "Value of r = " r.
stop run.
Note : The output of the program will be
Value of r = 12.
This output is arrived using Redefining the variable a.
Another Program for Redefines
Write a program to explain REDEFINES clause at level other than 01.
identification division.
program- id.
environment division.
data division.
working-storage section.
01 emp-details.
83
02 emp-rec.
03 emp-name pic x(20).
03 emp-sal pic 9(2).
02 pay-rec redefines emp-rec.
03 name pic x(20).
03 sal pic 9(2).
procedure division.
p-1.
display(1 1) erase.
display(3 5) "Name : " accept emp-name.
display(5 5) "Salary : " accept emp-sal.
display(7 5) "Name : " name.
display(9 5) "Salary : " sal.
stop run.
15.8 PROGRAM FOR RENAMES CLAUSE
identification division.
program- id.
environment division.
data division.
working-storage section.
01 emp.
02 empdet.
03 name pic x(25).
03 age pic 9(3).
03 sal pic 9(6).
66 paydet renames name thru sal.
procedure division.
p1.
display(1 1) erase.
display(5 5) "Name : ".
accept name.
display(7 5) "Age : ".
accept age.
display(9 5) "Sal : ".
accept sal.
display(1 1) erase.
display(5 5) "Details (Renaming used) : " paydet.
stop run.
15.9 LET US SUM UP
Having tried the above programs the learner gets clear ideas about the working
principles of IF, IF ELSE,PERFORM,REDEFINES and RENAMES clauses.
84
The Learner can make simple modifications in the above programs to see the
consequences on the screen which will make him/her confident to use these important verbs
in his/her programs without any ambiguity.
15.10 LESSON-END ACTIVITIES
Try to find the answers for the following exercises on your own.
1.
2.
3.
4.
85
UNIT IV
LESSON 16: SEQUENTIAL FILES
CONTENTS
16.1
Aims and objectives
16.1
16.2
File Characteristics
File-Control Entries For Sequential Files
16.3
16.4
16.5
16.6
16.7
Lesson-end Activities
16.8
16.9
References
86
The most important of the information stored in the header label is what is known as the
file title. In the case of magnetic-disk files the labels usually do not exist(there are many
exceptions). Since, more than one file is stored on a disk pack, the IOCS also maintains a disk
directory for all the files.
16.2 FILE-CONTROL ENTRIES FOR SEQUENTIAL FILES
The characteristics of each of the files handled in a program are specified in the
ENVIRONMENT DIVISION and DATA DIVISION.
SELECT
[ OPTIONAL ]
file-name
; RESERVE
integer-1
ASSIGN
TO hardware- name
AREA
AREAS
[ ; ORGANIZATION IS SEQUENTIAL ]
[ ; ACCESS MODE IS SEQUENTIAL ]
[ ; FILE STATUS IS data-name-1 ]
RESERVE clause:
This clause specifies the number of buffers to be used for the file.
Integer-1 indicates this number.
ORGANIZATION/ACCESS clause:
These two clauses indicate that the said file is organized as a sequential file and will be
accessed sequentially.
FILE STATUS clause:
This clause has been included in the above syntax for completeness. The REVERSE,
ORGANIZATION, ACCESS and STATUS clause can be specified in any order.
16.3 FILE DESCRIPTION- FIXED-LENGTH RECORDS:
The general characteristics of a file are described in the file description (FD) entry of the
DATA DIVISION.
FD
file-name
; BLOCK CONTAINS
; RECORD
integer-1
CONTAINS
RECORDS
CHARACTERS
integer-2
CHARACTERS
87
; LABEL
RECORD IS
RECORDS ARE
STANDARD
OMITTED
ID
IDENTIFICATION
IS
data-name
literal
88
FIRST-RECORD
PIC
X(130).
INPUT
OUTPUT
EXTEND
I-O
INPUT
OUTPUT
EXTEND
I-O
file-name-1
[ , file-name-2 ]
file-name-3
[ , file-name-4 ]
CLOSE statement:
The following is the syntax (simplified) of the CLOSE statement.
CLOSE
file-name-1 [WITH LOCK ]
[ , file-name-2 [WITH LOCK ] ]
The CLOSE statement terminates the processing of the file.
WRITE statement:
The WRITE statement for tape and sequential-disk files has the following syntax.
WRITE
record-name
[ FROM identifier ]
As a result of the execution of the WRITE statement, the record is released from the
record area and is written onto the file.
REWRITE statement:
The REWRITE statement is used to update an existing record in the disk file.
89
CONTAINS
[ integer-1
CONTAINS [ integer-3
TO
TO
] integer-2
] integer-4
RECORDS
CHARACTERS
CHARACTERS
90
REFERENCES
1. COBOL Programming , M.K.Roy & Ghosh Dastidar , Tata McGraw Hill, 2nd
Edition,1998
2. COBOL Programming , V. RAJARAMAN, PHI Pub
3. Introduction to COBOL programming Dr. R.Krishnamoorthy, JJ Publ
4. Structured COBOL , Welburn, TataMcGraw Hill , 4th Edition.
91
17.2
17.3
17.4
Let us Sum Up
17.5
Lesson-end Activities
17.6
17.7
92
integer-1
AREA
AREAS
; ORGANIZATION IS RELATIVE
; ACCESS MODE IS SEQUENTIAL [, RELATIVE KEY IS data- name-1]
RANDOM
DYNAMIC
, RELATIVE KEY IS data-name-1
[; FILE STATUS IS data-name-2]
Whether the file should be used sequentially or randomly, should specified through the
word SEQUNTIALLY or RANDOMLY in the access mode clause the clause ACCESS
MODE IS DYNAMIC it indicates that the file is accessed sequentially and / or randomly in
the PROCEDURE DIVISION.
17.3 PROCEDURE DIVISION statements for relative files
The statements OPEN,CLOSE,READ,WRITE and REWRITE which are available for
sequential files are available for the relative files. In addition, two other words, namely,
DELETE and START are also available. As regards the OPEN and CLOSE statements,
There is no difference between relative file and sequential disk file.
READ STATEMENTS:
The general format for the read statements are shown bellow.
Format 1:
READ file-name RECORD [ INTO identifier ]
[ ; AT END imperative-statements ]
Format 2:
READ file-name RECORD [ INTO identifier ]
[ ; INVALID KEY imperative-statement ]
Format 3:
READ file-name [ NEXT ] RECORD [ INTO identifier ]
[ ; AT END imperative-statements ]
As usual, a READ statements reads a record of the file. The file must be open in either
the input or I-O mode.
Format 1 is the normal form of the READ statements.
Format 2 is used when the access mode is either random or dynamic. For example,
suppose REL-KEY are the names for the relative file and the relative key data item
respectively. The following statements will read the 50th record from this file.
93
MOVE 50 TO REL-KEY.
READ REL-FILE RECORD INVALID-KEY GO TO PARA-INVALID.
Format 3 of the read statement can be used when the access mode is dynamic and the
records are to be read sequentially. The next record is identified according to the following
rules:
(i)
When the READ NEXT statements is the first statement to be executed after
the open statement on the file, the next record is the first record of the file.
(ii)
When the execution of the READ NEXT statement follows the execution of
another READ statement on the same file (format 2 or format 3 above), the next
record is the record following the one previously read.
(iii) When the execution of the READ NEXT statement follows the execution of the
start statement .
WRITE Statement
The WRITE statement for a relative file has the following format.
WRITE
94
95
18.1
18.2
18.3
18.4
18.5
18.6
Let us Sum Up
Lesson-end Activities
18.7
18.8
References
96
AREA
; RESERVE INTEGER-1
AREA
, ORGANIZATION IS INDEXED
; ACCESS MODE
IS
SEQUENTIAL
RANDOM
DYNAMIC
..
97
(i) when an attempt is made to write a record beyond the externally defined boundaries
of the file.
(ii) When the file is opened in the OUTPUT mode and the value of the record key is not
grater than the value of the record key for the previous record written.
(iii) When the value of the record key is equal to the record key of a record key already
present in the file.
REWRITE STATEMENT
As in the case of a relative file, the REWRITE statement requires that the file must be
opened in the I-O mode, and if the SEQENTIAL access mode is specified, the value of the
record key of the record being replaced must be equal to that of the record last from this file.
The INVALID KEY condition arises in the following cases:
(i)
when the record key does not match that of an existing record in the file.
(ii)
For SEQUENTIAL access, when the value of the record key is not identical to that
of the last record read from the file.
DELETE STATEMENT
The file must be opened in the I-O mode. If the access is SEQUENTIAL, the INVALID
KEY phrase should be specified. Instead, the last input-output statement executed on the file
must be a successful READ statement for the said record.
START STATEMENT
The START statement positions the files to the first logical record whose record key
satisfies the condition specified by the KEY phrase. The access mode must be
SEQUENTIAL or DYNAMIC and the file must be opened in the I-O mode.
18.4 UPDATING OF RELATIVE AND INDEXED FILES
Sequential files are updated by creating a new maser file from an existing old master file
and a transaction file. Such an Updating is known as updating by copy. Direct access files can
be updated by the technique known as Updating by overlay. In this case no new file is
created. instead, the necessary changes are incorporated in the body of the file.
The transaction code (T-CODE) is a one-digit code having the following meaning.
Transaction Code
1
2
Meaning
The transaction record is to be inserted
The corresponding master record is to be
deleted.
Other than
1 or 2
98
accessed using a scheme of converting the of a record into the disk address to which the
record is placed. Thus, no index table as in the case of an indexed file is necessary.
Selection of file Organization
While designing a file, the programmer must select a suitable organization for a file. The
order in which the choice is to be made is as follows:
(i)
Implementation support difficulty.
(ii)
Software support required.
(iii) Efficiency of processing.
File Activity
The file activity is a measure of the proportion of records processed during a update run.
Thus we define the activity ration as follows.
Activity ratio = m / n
Where m = number of records to be inserted, modified or deleted and
n = number of records in the file.
File volatility
File volatility relates to the number of times the updating of records are required
during some time period.
File interrogation
Some files contain reference data. These files are used mainly for the purpose of
interrogation. interrogation means a reference to a specific record for a specific response
without changing the record in any manner.
Eg: Price list can be file which is to be constantly interrogative during a billing run.
18.5 LET US SUM UP
With the help of this lesson, the learner gets clear ideas about the concepts related with
Indexed Sequential Files. File-Control Paragraph for Indexed Files, Procedure Division
Statements for Indexed Files, Updating of Relative and Indexed Files. Having leant these
concepts , the learner can write application programs that involve indexed sequential files.
18.6 LESSON-END ACTIVITIES
Try to find the answers for the following exercises on your own.
1. Explain about Indexed Sequential files.
2. Explain the file control Para of Indexed Sequential files.
3. Explain READ,WRITE statements of Indexed Sequential file.
4. Explain REWRITE,DELETE statements of Indexed Sequential file.
5. What parameters are to be considered for selecting file organization?
18.7 POINTS FOR DISCUSSION
1) Explain in detail about procedure division statements for indexed sequential files.
18.8
REFERENCES
1.
COBOL Programming , M.K.Roy & Ghosh Dastidar , Tata McGraw Hill, 2nd
Edition,1998
2.
COBOL Programming , V. RAJARAMAN, PHI Pub
3.
Introduction to COBOL programming Dr. R.Krishnamoorthy, JJ Publ
4.
Structured COBOL , Welburn, TataMcGraw Hill , 4th Edition.
99
19.0
19.0
19.1
19.2
File Updating
19.3
19.4
19.5
19.6
Let us Sum Up
19.7
19.8
Lesson-end Activities
Points for Discussion
19.9
References
The aim of this lesson is to introduce the learner the Sort Verb, File Updating, Simple
Merge Verb, Input and Output Procedure in Sort Statement and Merge Verb with
Output Procedure ,as they play important role in many application programs.
19.1 THE SIMPLE SORT VERB
The process of sequencing the records in some desired manner is known as sorting.
Sorting is done upon some key data item in the record. For example, consider the case of a
pay roll file where each record contains all the necessary information of an employee, such as
his identification number, name, address, department number, basic pay, allowances,
deductions, etc.
When a sequential file is to be sorted, its record reside on the file medium and can be
accessed to only serially. In COBOL, there is no specific feature for the sorting of a table.
However, its provides a sort verb that can be used to SORT a sequential file. In addition to
the sort verb, the MERGE verb can be used to merge several sorted files to create a new file
containing the records of these files in the sorting order.
The sort verb like many other Cobol verbs, then have different forms. This form is to be
used when it is required to sort a given input file. The simple sort verb requires the naming of
three files the unsorted input file, the sorted output file and the work file. The format of the
simple SORT verb is as follows:
SORT
100
SD
file-name
[; RECORD
; DATA
[, data-name-2].
The following rules should be taken into considerations while specifying this sort verb
(i)
The input, output as well as the work file are open by the sort statement before the
starting begins and are closed by the sort statement itself after the sorting is over.
(ii)
There can be any number of SORT statement in a program.
(iii) The sorting can be done on any number of keys.
(iv)
All the keys on which the sorting is done, must appear with their description in the
record description of file name1.
(v)
Keys in the sort statement do not require any qualification.
(vi)
When two or more records in the input file have identical keys.
(vii) The SELECT clauses for the work file file- name-1 is SELECT file-name-1
ASSIGN TO hardware-name.
Eg: Assume that we have a card file with the following records description in the data
division.
FD KARD-FILE.
01 INPUT- RECORD.
02 ID-NUMBER
PIC
9(6).
02 NAME
PIC
X(24).
02 DEPARTMENT
PIC
X(10).
02 BASIC-PAY
PIC
9(5)V99.
02 ALLOWANCE
PIC
9(4)V99.
02 DETECTION
PIC
9(4)V99.
The names of the work file and output file be SORT-FILE and OUTPUT-FILE
respectively. the DATA DIVISION entries for these two files are as follows.
SD SORT-FILE.
01 SORT-RECORD
02 FILLER
02 DEPARTMENT
02 BASIC-PAY
02 FILLER
PIC
PIC
PIC
PIC
X(30).
X(10).
9(5)V99.
X(12).
FD OUTPUT-FILE.
01 OUTPUT-RECORD
PIC
X(59).
The following statement will sort the input file and will create the sorted output file.
19.2 FILE UPDATION
The process of modifying an old file with current information is known as file updating.
Master file
A master file is a file that is used to as an authority in a given job. It may contain
somewhat permanent, historical, statistical or identification type of data.
101
Transaction file
A transaction file is a file that contains a new records are changes to old records which
are used to update the master file.
The problem of file updating can be defined as follows.
v
Insertion of new records.
v
Modification of some existing records.
v
Deletion of obsolete records.
v
Copy of those records which are neither obsolete nor require any modification.
19.3
KEY
data-name-1
[ , data-name-2 ]
KEY data-name-3
[ , data-name-4 ]..
DECENDING
ASCENDING
ON
DECENDING
USING
ZONE-FILE-2
TO
TO
TO
TO
TO
TAPE.
TAPE.
TAPE.
MERGE-DISK.
TAPE.
102
01
FD
01
FD
01
ZONE-FILE-3
BLOCK CONTAINS 10 RECORDS
VALUE OF ID ZONEFILE3.
FILE-3-RECORD
PIC
X(90).
MERGED-FILE
BLOCK CONTAINS 20 RECORDS
VALUE OF ID MERGEDFILE.
MERGED-RECORD
PIC
X(90).
SD WORK-FILE.
01 WORK-RECORD.
02 FILLER
02 PROCEDURE-NAME
02 FILLER
PIC
PIC
PIC
X(50).
X(20).
X(20).
PROCEDURE DIVISION.
MERGING-PARA.
MERGE WORK-FILE ON ASCENDING KEY PRODUCT-NAME
USING ZONE-FILE-1, ZONE-FILE-2, ZONE-FILE-3
GIVING MERGED-FILE.
STOP RUN.
It has been assumed that all the three input files and the final merged file named as
MERGED-FILE are tape files.
19.4 INPUT AND OUTPUT PROCEDURE IN SORT STATEMENT
The general format of the SORT statement can written as follows.
ASCENDING
SORT file- name-1
ON
KEY
DESCENDING
ASCENDING
ON
..
103
THRU
INPUT PROCEDURE
IS
section-name-1
section-name-2
THROUGH
USING
file- name-2
[ , file- name-3] .
THRU
OUTPUT PROCEDURE
IS
section-name-3
section-name-4
THROUGH
section-name-2
THROUGH
ASCENDING
ON
104
IS
section-name-1
section-name-2
THROUGH
SORT-MERGE
At least one of the files quoted in this clause must be defined with SD. The SAME
SORT AREA clause enables two or more SORT/MERGE work files to use same area.
19.6 LET US SUM UP
This lesson has introduced the learner the Sort Verb, File Updating, Simple Merge
Verb, Input and Output Procedure in Sort Statement and Merge Verb with Output
Procedure. These are essential for any COBOL programmer for writing industry oriented
applications.
19.7 Lesson-end Activities
Try to find the answers for the following exercises on your own.
1.
2.
3.
4.
5.
105
20.1
20.2
20.3
20.4
20.5
20.6
20.7
Let us Sum Up
20.8
Lesson-end Activities
20.9
20.10
106
107
01 len-rec.
02 l pic 9(2).
02 l-c pic 9(1).
working-storage section.
01 ans pic x value space.
01 eof pic x value space.
screen section.
01 cls-screen.
02 blank screen.
01 get-screen.
02 line 3 column 5 value "Length = ".
02 column plus 3 pic 9(2) to l auto bell.
02 line 5 column 5 value "Code = ".
02 column plus 3 pic 9 to l-c bell reverse-video.
procedure division.
p-1.
open output len-file.
perform g-w-para until ans = 'n' or 'N'.
close len- file.
open i-o len- file.
read len- file at end move 'y' to eof.
perform rewrite-para until eof = 'y'.
close len- file.
stop run.
g-w-para.
display cls-screen.
display get-screen.
accept get-screen.
write len-rec.
display (10 5) "Continue [y/n] :".
accept ans.
rewrite-para.
if l-c = 1
move 5 to l-c
rewrite len-rec.
read len- file at end move 'y' to eof.
20.3 PROGRAM FOR INDEXED SEQUENTIAL FILE CREATION
(DYNAMIC MODE)
Write a program to create an Indexed Sequential File in dynamic mode for Student
particulars. Assume just 3 fields : rno(Roll Number), cl (Class) and m(Mark). Read the file
and display the records.
108
identification division.
program- id.
environment division.
input-output section.
file-control.
select stu- file assign to disk
organization is indexed
access mode is dynamic
record key is rno
file status is fs.
data division.
file section.
fd stu- file
label records are standard
value of file- id is 'stu.dat'.
01 stu-rec.
02 rno pic 9(3).
02 cl pic x(4).
02 m pic 9(3).
working-storage section.
01 ans pic x value space.
01 a-rno pic 9(3) value 0.
01 fs pic x(2) value spaces.
procedure division.
p-1.
open i-o stu-file.
if fs = "30"
open output stu-file
close stu-file
open i-o stu-file.
perform g-w-para until ans = 'n'.
go to p-2.
g-w-para.
display(1 1) erase.
display "Enter Data :".
accept rno.
accept cl.
accept m.
write stu-rec invalid key
display "Record Exists!".
display "Continue [y/n] : ".
accept ans.
p-2.
display(1 1) erase.
display(3 5) "Give Roll No : ".
accept a-rno.
move a-rno to rno.
read stu- file key is rno
invalid key
109
(RANDOM MODE)
Write a program to create an Indexed Sequential File in random mode for Student
particulars. Assume just 2 fields : rno(Roll Number), name(Name of Student)
identification division.
program- id.
environment division.
input-output section.
file-control.
select stu- file assign to disk
organization is indexed
access mode is random
record key is rno
file status is fs.
data division.
file section.
fd stu- file
label records are standard
value of file- id is "stu.dat".
01 stu-rec.
02 rno pic 9(3).
02 name pic x(20).
working-storage section.
01 fs pic x(2) value spaces.
01 ans pic x value space.
procedure division.
p-1.
open i-o stu-file.
if fs = "30"
open output stu-file
close stu-file
open i-o stu-file.
perform g-w-para until ans = "n".
close stu-file.
stop run.
g-w-para.
110
display(1 1) erase.
display(3 5) "Rno : ".
accept rno.
display(5 5) "Name : ".
accept name.
write stu-rec invalid key display(15 5) "Error!".
display(20 5) "Continue [y/n] : ".
accept ans.
20.5 PROGRAM TO DEMONSTRATE SORT VERB
A file for which a record having 2 fields, namely, Account Number and Name is already
available. Sort the file based on the ascending order of Account Number.
identification division.
program- id.
environment division.
input-output section.
file-control.
select o1- file assign to disk
organization is line sequential.
select s1-file assign to disk
organization is line sequential.
select w- file assign to disk.
data division.
file section.
fd o1- file
label records are standard
value of file- id is "o1.dat".
01 o1-rec.
02 o1-acc-no pic 9(2).
02 o1-name pic x(4).
fd s1-file
label records are standard
value of file- id is "s1.dat".
01 s1-rec.
02 s1-acc-no pic 9(2).
02 s1-name pic x(4).
sd w-file.
01 w-rec.
02 w-acc-no pic 9(2).
02 w-name pic x(4).
procedure division.
p-1.
111
112
LET US SUM UP
With the help of the above programs, the learner gets very clear ideas about how to
create a sequential file , how to rewrite records , how to cerate indexed sequential file in
dynamic and random modes. Also the learner becomes quite familiar with the concepts of
Sorting and Merging after having tried these programs.
20.8
LESSON-END ACTIVITIES
Try to find the answers for the following exercises on your own.
1) Write a program to create a sequential file for bank details. Assume the necessary
fields.
2) Write a program to read the records of a bank file and display the customers who
have amount > 10000 in their account.
113
114
UNIT V
LESSON 21: TABLE HANDLING
CONTENTS
21.0
Aims and objectives
21.1
21.2
Occurs clause
Rules for OCCURS clause
21.3
MULTI-DIMMENSIONAL TABLES
21.4
Let us Sum Up
21.5
21.6
Lesson-end Activities
Points for Discussion
21.7
References
INCOME-TAX-RATE
02
TAX-RATE-1
PIC 99.
02
TAX-RATE-2
PIC 99.
02
TAX-RATE-3
PIC 99.
02
TAX-RATE-4
PIC 99.
02
TAX-RATE-5
PIC 99.
02
TAX-RATE-6
PIC 99.
02
TAX-RATE-7
PIC 99.
02
TAX-RATE-8
PIC 99.
02
TAX-RATE-9
PIC 99.
02
TAX-RATE-10
PIC 99.
Obviously, there are ten different data names, such as TAX-RATE-1, TAX-RATE-2
etc., in the table named INCOME-TAX-RATE and each of these items is of two digits. Since
the picture of all these items are identical, these can be described by having just one entry and
then specifying that the description is to be repeated ten times. This is done as follows:
01
INCOME-TAX-RATE
02
TAX-RATE
PIC
99
OCCURS
10
TIMES.
115
This OCCURS clause indicates that the table named INCOME-TAX-RATE is having
ten elements and each one is of two digits. Now in order to refer to an individual element
uniquely we must use a subscript. The first element is referred to as TAX-RATE (1), the
second one as TAX-RATE (2), the seventh one as TAX-RATE (7), and so on. TAX-RATE
(1), TAX-RATE (2) etc., are known as subscripted data names and 1, 2 etc., which are
enclosed in parentheses are called subscripts.
The general format of OCCURS clause is as follows:
{OC}
{OCCURS}
integer
TIMES
(iii)
The OCCURS clause can be specified for an elementary item or for a group
item. The clause causes contiguous fields to be set up internally. Each field is
equivalent to the elementary or group item for which the OCCURS clause has
been specified. The number of fields that are set up is equal to the integer in
the OCCURS clause. The OCCURS clause cannot be specified for an item
whose level number is 01, 66, 77 or 88.
When a data name is defined with the occurs clause that data name as well as
any of its subordinate items cannot be referred to in the PROCEDURE
DIVISION without a subscript. A subscript may be a positive integer constant,
a numeric integral data item or an arithmetic expression. For example, an
element of the above INCOME-TAX-RATE table, can be referred to in the
PROCEDURE DIVISION as
TAX-RATE
(I)
or
as
(3*J)
In the first case, a data name I has been used as the subscript. If the current
value of I is, say 5, then TAX-RATE (I) will refer to the fifth element of the
table. In the second case, an arithmetic expression has been used as a
subscript. The value of this expression is used to identify the particular
element of the table. Thus, if the current value of J is 1, TAX-RATE (3*J) will
refer to the third element of the table.
(iv)
The highest value that a subscript can take is the one specified in the
OCCURS clause. For any table, the lowest value of a subscript is implicitly
assumed to be 1. By the range of a subscript we mean the range of values from
1 to the highest possible value of the subscript. In the above example, the
range of the subscript is 1 to 10. If during the execution of a program, the
value of a subscript is found to be outside its range, an execution error occurs
and the program is terminated by the system.
(v)
116
(vi)
If a data name with the OCCURS clause requires any qualification by its
higher level, the subscripts to be written after the last qualified name. For
example, if TAX-RATE should be qualified, it must appear as TAX-RATE
OF INCOME-TAX-RATE (I) and not as TAX-RATE (I) OF INCOME-TAXRATE.
(vii)
When an entry is defined with the OCCURS clause, the VALUE clause cannot
be specified for that particular item or any item subordinate to it.
(viii)
The REDEFINES clause cannot appear in the same data description entry
which contains an OCCURS clause. However, the REDEFINES clause can
appear for a group item whose subordinate items are defined with the occurs
clause.
(ix)
The OCCURS clause can appear in the data description entry in any order.
Example:
Consider the following table:
02
AMOUNT-TABLE OCCURS
20
TIMES.
03
AMOUNT
PIC 9(6) V99
03
AMOUNT-CODE
PIC X.
Suppose it is required to find the total of all the amounts of the table in the following
manner. If the amount code is 1, the corresponding amount is to be considered positive,
otherwise the corresponding amount should be considered negative. (Note that the amount
fields being unsigned contain only absolute value.) The following statements will perform the
said task. It is assumed that the field named TOTAL and I are suitably defined, say with
picture S9 (7) V 99 and 99 respectively.
MOVE
ZERO TO
TOTAL.
MOVE 1
PARA-LOOP
IF
AMOUNT-CODE
(I)
IS
EQUAL
TO
ADD AMOUNT
(I)
TO
TOTAL
ELSE SUBTRACT AMOUNT
(I)
FROM TOTAL.
ADD 1
TO
I
IF
I
IS
NOT GREATER THAN 20
GO
TO
PARA-LOOP.
TO
I.
It may be noted how to use of the data name as a subscript helps to write the above code.
The reader may try to find the required total without using data name or arithmetic expression
as subscripts. In that case the loop cannot be designed and one must use twenty IF sentences
to do the job.
117
SALES-TABLE
02
BRANCH-FIGURES OCCURS
18
TIMES.
03
MONTHLY-SALES PIC 9(6) V99 OCCURS
12
TIMES.
The table is assumed to store monthly sales figures for 12 months for each of the 18
branches of an organization. Note that this is a two-dimensional table because each of the 18
BRANCH-FIGURES is itself a table having 12 elements. It may be further noted that a
reference to an element of a two-dimensional table requires tow subscripts. We must specify
the branch as well as the month so that the desired element is identified. Thus MONTHLYSALES (3, 5) means the sales figure for fifth month of the third branch. Because of the
organization specified in the above description of the table, the first subscript implicitly refers
to the branch and the second subscript to the month. The two-dimensional table has been
divided first into 18 one-dimensional tables through the entry at level 02. Each of these tables
has then been defined by the entry at level 03. This organization can be diagrammatically
shown as
9 more
Occurrences
of MONTHLY SALES
9 more
Occurrences
of MONTHLY SALES
16 more Occurrences
BRANCH-FIGURES
(BRANCH-FIGURE-1)
(BRANCH-FIGURE-2)
If required, the tables for the individual branches can be referred to by the name
BRANCH-FIGURE with only one subscript indicating the branch. Thus BRANCH-FIGURE
(4) will indicate the monthly sales table for the fourth branch.
The above notion of a two-dimensional table can be easily extended to tables having
three or more dimensions. Handling of tables up to three dimensions are allowed by most
compilers; some even allow more than three. The following rules may be noted in connection
with multi-dimensional tables.
(i)
TABLE-EXAMPLE
02
A
PIC 9(5)
02
B
OCCURS
03
C
PIC
OCCURS
20
TIMES
9(3)
50
TIMES
118
03
D OCCURS 10
TIMES.
04 E OCCURS
15
TIMES PIC 9(4)V99.
04
F
PIC X (4).
A and C are one-dimensional, F is a two-dimensional table and E is a three dimensional
table. B and D are group items which can be referred to as one-dimensional and two
dimensional tables respectively.
(ii)
A table is stored in such a way that a subscript on the right of another subscript
changes more rapidly than the latter.
The organization of the SALES-TABLE shown above illustrates this. The elements
MONTHLY-SALES (1, 12) are stored first. The elements MONTHLY-SALES (2, 1) to
MONTHLY-SALES (2, 12) are stored next, and so on. Note that the second subscript is
changed more frequently than the first subscript. This fact should be taken into consideration
while redefining a multi-dimensional table.
(ii)
119
22.1
22.2
Indexed Tables
Rules for Indexed Tables
22.3.
SET verb
22.4
Let us Sum Up
22.5
22.6
Lesson-end Activities
Points for Discussion
22.7
References
ENROLL-TABLE.
02
FACULTY OCCURS 3 TIMES INDEXED BY F1.
03
DEPARTMENT OCCURS 6 TIMES INDEXED BY D1.
04
YEAR PIC 9(4) OCCURS 5 TMES.
INDEXED BY Y1.
The reference to an element of this table can be done as YEAR (F1, D1, Y1) having
set appropriate values to the index names F1, D1 and Y1.
The general form of the INDEXED phrase is as follows:
INDEXED BY index-name-1 [, index- name-2]
The OCCURS clause with the INDEXED phrase takes the following form
OC
OCCURS}
integer
TIMES
[INDEXED BY index- name-1 [, index- name-2]]
If indexing is done for any one level of a table, then indexing must be used for all
levels. Thus it will be error if in the above the INDEXED phrase is used only for
FACULTY and not for DEPARTMENT and YEAR.
120
(ii)
ENROLL-TABLE.
02FACULTY OCCURS 3 TIMES INDEXED BY F1, F2, F3.
02
DEPRTMENT OCCURS 6 TIMES INDEXED BY
D1, D2, and D3
03
DEPRTMENT OCCURS 6 TIMES INDEXED
BY D1, D2, and D3
04
YEAR PIC 9(4) OCCURS 5 TIMES
INDEXED BY Y1, Y2, and Y3.
Index items defined through the INDEXED phrase of the OCCURS clause are one kind
of indexes. There can be another kind of index items which are defined like data names in the
DATA DIVISION with USAGE IS INDEX clause. Note that earlier we discussed only the
DISPLAY and COMPUTATIONAL usages. Index is another type of usage. An index name
defined with INDEX usage should not have nay picture clause in the entry.
For example, the entry
77
I
USAGE
IS
INDEX
defines the index I.
The indexes defined with the usage INDEX are called index data items. They are
functionally identical to the indexes defined through the INDEXED phrase with the exception
that when an index name is defined with the USAGE IS INDEX phrase, the same index name
can be used for subscripts in more than one table or in more than one level of table.
22.3. SET VERB
The set verb is used to set, increase or decrease the values of the indexes. For example,
the statement
121
SET
F1
TO
To move the current value of an index to one or more identifiers, the following
form of the SET verb can be used.
SET identifier-2 [, identifier-3]
TO
index-name-3
If A and B are data names and F1 is an index name, the statement
SET A, B TO F1
Indicates that the current value of F1 will be stored in both the data names A and B.
(III)
F1, Y1
UP
BY
2.
122
123
23.2
23.3
23.4
Let us Sum Up
23.5
Lesson-end Activities
23.6
23.7
124
PROCEDURE DIVISION
.
.
.
SET A1 TO 1.
SEARCH ACCOUNT-TABLE
AT
END DISPLAY NAME NOT FOUND
NAME=NAME-OF-THE-PERSON (A1)
DISPLAY ACCOUNT-NUMBER (A1), NAME,
AMOUNT (A1).
In the above SEARCH statement, there are two parts- the AT END part and the WHEN
part. If the condition NAME= NAME-OF-THE-PERSON (A1) is satisfied for some value of
the index name A1, the statement DISPLAY ACCOUNT-NUMBER (A1), NAME,
AMOUNT (A1) is executed. The AT END part is executed only when the entire table is
searched and the condition is not satisfied for any value of A1. The increment of A1 is taken
care of by the SEARCH verb.
To illustrate another use of the SEARCH verb, suppose we wish to search the same table
to find the number of persons whose deposited amount is greater than 5000.00. For this we
describe another data NO-OF-PERSONS in the DATA DIVISION with the picture say 999.
The following statements in the PROCEDURE DIVISION will perform the desired search.
MOVE ZEROS TO NO-OF-PERSONS
SET A1 TO 1.
PARA-REPEAT
SEARCH ACCOUNT-TABLE
AT END GO TO PARA-NEXT
WHEN AMOUNT (A1) IS-GREATER THAN 5000.00
ADD 1 TO NO-OF-PERSONS
SET A1 UP BY 1
GO TO PARA-REPAEAT
PARA NEXT
.
.
.
.
SEARCH
identifier-1 [VARYING
identifier-2 index-name-1}]
[; AT END
imperative-statement-1]
;
WHEN
Condition-1 {imperative-statement-2
NEXT SENTENECE}
[; when
Condition-2 {imperative-statement-2
NEXT
SENTENCE}]
23.2 RULES FOR SEARCH VERB
The following rules apply for the SEARCH verb.
(I)
(II)
The SEARCH verb can only be applied to a table which has the OCCURS clause
and INDEXED phrase. The identifier-1 indicates the table to be searched and it
must not be indexed or subscripted.
Before the use of the SEARCH verb, the index must have some initial value. The
initial value must not exceed the size of the table. If it exceeds, the search is
125
(III)
(IV)
(V)
126
23.4
LET US SUM UP
In this lesson the learner has been introduced the Search Verb, Rules for SEARCH verb
and START Statement. With this knowledge the learner can make use of these concepts in
application programs.
23.5
LESSON-END ACTIVITIES
Try to find the answers for the following exercises on your own.
1.
2.
3.
4.
127
24.2
24.3
24.4
24.5
24.6
Let us Sum Up
24.7
24.8
Lesson-end Activities
Points for Discussion
24.9
References
128
stop run.
get-para.
accept name(i).
add 1 to i.
disp-para.
display name(i).
accept key- in.
add 1 to i.
24.2 OCCURS CLAUSE PROGRAM-2
Write a program to demonstrate occurs clause. Get names and marks of the students and
display them on the screen.
identification division.
program- id.
environment division.
data division.
working-storage section.
01 n pic 9(2) value 0.
01 i pic 9(2) value 1.
01 stu-det.
02 stu-rec occurs 10 times.
03 name pic x(20).
03 mark pic 9(3).
01 key- in pic x value space.
procedure division.
p-1.
display(1 1) erase.
display(3 5) "Enter How many times".
accept n.
display(1 1) erase.
perform get-para n times.
display(1 1) erase.
move 1 to i.
perform disp-para n times.
stop run.
get-para.
accept name(i).
accept mark(i).
add 1 to i.
disp-para.
display name (i).
display mark (i).
accept key- in.
add 1 to i.
24.3 OCCURS INDEXED BY PROGRAM
identification division.
program- id. searching.
environment division.
129
data division.
working-storage section.
01 table1.
02 data1 occurs 10 times indexed by a1.
03 name pic x(25).
03 sal pic 9(6).
01 n pic 9 value 0.
01 tot pic 9(2) value 0.
01 i pic 9 value 0.
procedure division.
p-1.
display(1 1) erase.
display(5 5) "Enter Data .....".
display(7 5) "Enter No.of Records : ".
accept n.
perform init-para varying i from 1 by 1 until i > n.
perform get-para varying i from 1 by 1
until i > n.
set a1 to 1.
p-2.
search data1 at end go to p-3
when sal (a1) > 1000
add 1 to tot.
set a1 up by 1
go to p-2.
p-3.
display(20 5) "Total Records > 1000 [sal] = " tot.
stop run.
get-para.
display(1 1) erase.
display(3 5) "Name : ".
accept name (i).
display(5 5) "Salary : ".
accept sal (i).
init-para.
move spaces to name(i).
move 0 to sal(i).
24.4 PROGRAM FOR SCREEN SECTION
identification division.
program- id.
environment division.
data division.
working-storage section.
01 a pic 9(2) value 0.
01 b pic 9(2) value 0.
01 c pic 9(3) value 123.
130
screen section.
01 b-screen.
02 blank screen.
01 screen1.
02 line 3 column 5 pic 9(2) to a auto bell.
02 line 5 column 5 pic 9(2) to b auto bell.
01 screen2.
02 line 7 column 5 pic 9(2) from a blink reverse-video.
02 line 9 column 5 pic 9(2) from b highlight blink.
procedure division.
p0.
display b-screen.
p1.
display screen1.
accept screen1.
display screen2.
compute c = a + b.
display " ".
display " c = " c.
display "Using exhibit".
exhibit c.
stop run.
24.5 PROGRAM FOR SCREEN SECTION WITH FILES
identification division.
program- id.
environment division.
input-output section.
file-control.
select stu- file assign to disk
file status is fs.
data division.
file section.
fd stu- file
label records are standard
value of file- id is 'stu.dat'.
01 stu-rec.
02 name pic x(20).
02 mark pic 9(3).
working-storage section.
01 ans pic x value space.
01 eof pic x value space.
01 fs pic x(2) value spaces.
screen section.
01 get-screen.
02 line 3 column 5 value "Name : ".
131
132
24.7
LESSON-END ACTIVITIES
Try to find the answers for the following exercises on your own.
1.
2.
3.
Write a program to read the names and marks of 5 students. Display them
using OCCURS clause.
Write a program to display a welcome message using Screen Section features.
Write a program using Screen Section the creation of a College file. Assume
necessary details.
133
25.1
25.2
25.3
25.4
25.5
25.6
25.7
25.8
25.9
25.10
25.11
25.12
Let us Sum Up
25.13
25.14
Lesson-end Activities
References
134
procedure division.
p-1.
display(1 1) erase.
move corr rec-1 to rec-2.
display rec-2.
stop run.
25.3 PROGRAM FOR CONDITION NAMES
Write a simple program to demonstrate Condition names usage.
identification division.
program- id.
environment division.
data division.
working-storage section.
01 ms pic 9(2).
88 s value 0 thru 9 .
88 m value 10 thru 99.
procedure division.
p-1.
display(1 1) erase.
display(5 5) "Enter Marriage Status : ".
display(7 5) " 0 to 9 .... Single Person ".
display(8 5) " 10 to 99 .... Married Person".
accept ms.
if s display(10 5) "Single".
if m display(10 5) "Married".
stop run.
135
136
get-para.
display(1 1) erase.
display(5 5) "Name : ".
accept emp- name(i).
display(10 5) "Salary : ".
accept emp-sal(i).
add 1 to i.
disp-para.
move emp-name(i) to e-name.
move emp-sal(i) to e-sal.
compute tot-sal = tot-sal + emp-sal(i).
display head-3.
add 1 to i.
25.5 PROGRAM FOR MASTER FILE MAINTENANCE
Write a program to maintain the stu-file for which a record has just 2 fields, namely,
rno(Roll Number) and name(Student Name). Give the provisions to add, modify, delete the
records in the file
identification division.
program- id.
environment division.
input-output section.
file-control.
select stu- file assign to disk
organization is indexed
access mode is random
record key is rno
file status is fs.
data division.
file section.
fd stu- file
label records are standard
value of file- id is "stu.dat".
01 stu-rec.
02 rno pic 9(3).
02 name pic x(20).
working-storage section.
01 fs pic x(2) value spaces.
01 ans pic x value space.
01 ch pic 9 value 0.
procedure division.
open-para.
open i-o stu-file.
if fs = "30"
137
138
139
procedure division.
open-para.
open i-o stu-file.
if fs = "30"
open output stu-file
close stu-file
open i-o stu-file.
p-1.
display(1 1) erase.
display(3 5) "Main Menu".
display(5 5) "1 to Add".
display(7 5) "2 to Modify".
display(9 5) "3 to Delete".
display(11 5) "4 to Exit".
display(13 5) "Your Choice [1..4] : ".
accept ch.
if ch < 0 or ch > 4 go to p-1.
go to add-para modi-para del-para exit-para
depending on ch.
add-para.
display(1 1) erase.
display(3 5) "Rno : ".
accept rno.
display(5 5) "Name : ".
accept name.
write stu-rec invalid key display(15 5) "Error!".
display(20 5) "Continue Add Records [y/n] : ".
accept ans.
if ans = "y" go to add-para else go to p-1.
modi-para.
display(1 1) erase.
display(3 5) " Press 1 if you know Roll No , 2 if you
- " know Name ".
accept ch.
if ch = 1
display(5 5) "Enter Roll no to Modify"
accept rno
read stu- file key is rno
invalid key display(13 5) "No Record Found"
go to c-para
else if ch = 2
display(5 5) "Enter Name to Modify"
accept name
read stu- file key is name
invalid key display(13 5) "No Record Found"
go to c-para.
display(1 1) erase.
display(5 5) "Rno = " rno.
display(7 5) "Name = " name.
display(9 5) "Sure to Modify [y/n] : ".
140
accept ans.
if ans = 'y'
display(1 1) erase
display(5 5) "Name : "
accept name
rewrite stu-rec.
c-para.
display(15 5) "Continue Modification [y/n] : ".
accept ans.
if ans = 'y' go to modi-para else go to p-1.
del-para.
display(1 1) erase.
display(3 5) " Press 1 if you know Roll No , 2 if you
- " know Name ".
accept ch.
if ch = 1
display(5 5) "Enter Roll no to Delete"
accept rno
read stu- file key is rno
invalid key display(13 5) "No Record Found"
go to c-para1
else if ch = 2
display(5 5) "Enter Name to Delete"
accept name
read stu- file key is name
invalid key display(13 5) "No Record Found"
go to c-para1.
display(1 1) erase.
display(5 5) "Rno = " rno.
display(7 5) "Name = " name.
display(9 5) "Sure to Delete [y/n] : ".
accept ans.
if ans = 'y'
delete stu- file record.
c-para1.
display(15 5) "Continue Deletion [y/n] : ".
accept ans.
if ans = 'y' go to del-para else go to p-1.
exit-para.
close stu-file.
stop run.
25.7 PROGRAM TO FIND INTEREST ON BANK DEPOSITS
Write a program to find interest on deposits
The criteria is given below :
141
______________________________________________
Principal
Years of Deposit IntRate
______________________________________________
>=5000
>=3
10%
>=5000
<3
8%
<5000
Any
7%
______________________________________________
identification division.
program- id.
environment division.
input-output section.
file-control.
select bankfile assign to disk
organization is line sequential.
data division.
file section.
fd bankfile
label records are standard
value of file- id is "bank.dat".
01 bankrec.
02 dno pic 9(5).
02 dname pic x(21).
02 p pic 9(4)v9(2).
02 n pic 9(2).
working-storage section.
01 ans pic x value space.
01 tot pic 9(6)v9(2) value 0.
01 int pic 9(6)v9(2) value 0.
01 key- in pic x value space.
01 r pic 9(2) value 0.
01 head-1 pic x(80) value all '-'.
01 head-2.
02 f pic x(8) value "Deps No".
02 f pic x(3) value spaces.
02 f pic x(10) value "Deps Name".
02 f pic x(5) value spaces.
02 f pic x(8) value "Deposit".
02 f pic x(5) value spaces.
02 f pic x(8) value "Period".
02 f pic x(5) value spaces.
02 f pic x(5) value "Rate".
02 f pic x(5) value spaces.
02 f pic x(8) value "Interest".
02 f pic x(10) value " Nett".
01 head-3.
02 e-dno pic z(5).
02 e-dname pic x(26).
02 e-p pic z(4).z(2).
142
02
02
02
02
02
02
02
02
procedure division.
p-1.
open output bankfile.
perform g-w-para until ans = 'N' or 'n'.
close bankfile.
open input bankfile.
display(1 1) erase.
display head-1.
display head-2.
display head-1.
read-para.
read bankfile at end go to close-para.
if ( p not < 5000 and n not < 3 )
move 10 to r
compute tot = p * (1 + r / 100) ** n.
if ( p not < 5000 and n < 3)
move 8 to r
compute tot = p * (1 + r / 100) ** n.
if ( p < 5000)
move 7 to r
compute tot = p * (1 + r / 100) ** n.
move tot to e-tot.
compute int = tot - p.
move int to e- int.
move dno to e-dno.
move dname to e-dname.
move p to e-p.
move n to e-n.
move r to e-r.
display head-3.
go to read-para.
close-para.
display head-1.
close bankfile.
stop run.
g-w-para.
143
display(1 1) erase.
display(3 5) "Dep No : ".
accept dno.
display(5 5) "Dep Name : ".
accept dname.
display(7 5) "Amount : ".
accept p.
display(9 5) "Years : ".
accept n.
write bankrec.
display(15 5) "Add more [y/n] : ".
accept ans.
25.8 PROGRAM FOR INVENTORY
Write a program to update the inventory file. Consider 2 files,namely, invfile and
tranfile. Invfile has 3 fields pno,name,qty. Tranfile has 3 fileds tpno,trcode,tqty. By reading
tranfile records if trcode=1 then update the qty with qty+tqty in invfile. If trcode=2 then
update the qty with qty-tqty in invfile.
identification division.
program- id.
environment division.
input-output section.
file-control.
select invfile assign to disk
organization is indexed
access mode is dynamic
record key is pno
file status is fs.
select tranfile assign to disk
organization is line sequential.
data division.
file section.
fd invfile
label records are standard
value of file- id is "inv.dat".
01 invrec.
02 pno pic 9(5).
02 name pic x(5).
02 qty pic 9(5).
fd tranfile
label records are standard
value of file- id is "tran.dat".
01 tranrec.
02 tpno
pic 9(5).
02 trcode pic 9.
02 tqty pic 9(5).
working-storage section.
01 ans pic x value space.
144
145
146
01 head-2.
02 f pic x(5) value spaces.
02 f pic x(5) value "IDNO".
02 f pic x(5) value spaces.
02 f pic x(5) value "NAME".
02 f pic x(5) value spaces.
02 f pic x(7) value "NEWHPR".
02 f pic x(36) value "MIS INFO".
02 f pic x(12) value spaces.
01 head-3.
02 e-idno pic x(3)9(6).
02 e-name pic x(25).
02 e-hpr pic z(2).z(2).
02 e-mis pic x(41).
procedure division.
p-1.
open extend payfile.
perform g-w-para until ans = 'N' or 'n'.
close payfile.
open i-o payfile.
read-para.
read payfile at end go to close-para.
display(1 1) erase.
display(3 5) "HPR = " hpr.
accept ans.
if ( hpr not greater 5 )
compute hpr = hpr + hpr * 0.25.
if ( hpr > 5 and hpr not greater 8 )
compute hpr = hpr + hpr * 0.20.
if ( hpr > 8 and hpr not greater 12 )
compute hpr = hpr + hpr * 0.15.
if ( hpr > 12 )
compute hpr = hpr + hpr * 0.10.
rewrite payrec.
move 0 to hpr.
go to read-para.
close-para.
display head-1.
close payfile.
disp-para.
open input payfile.
display head-1.
display head-2.
display head-1.
read-para-1.
read payfile at end go to close-para-1.
move idno to e-idno.
move name to e-name.
move hpr to e- hpr.
move mis to e- mis.
147
display head-3.
go to read-para-1.
close-para-1.
display head-1.
close payfile.
stop run.
g-w-para.
display(1 1) erase.
display(3 5) "ID no [ x(3) 9(6)] : ".
accept idno.
display(5 5) "Emp Name :".
accept name.
display(7 5) " Hrly Pay Rate : ".
accept hpr.
display(9 5) "Miscell Info : ".
accept mis.
write payrec.
display(15 5) "Add more (y/n) :".
accept ans.
25.10 PROGRAM FOR ELECTRICITY BILL
An electricity company supplies electricity to 4 types of
customers coded 1,2,3 & 4.The rate schedule for customers is
shown in one table as
Customer code
1
2
2
3
3
4
Consumption
All Below 1000& Below 5000& All
1000 above 5000 above
Rate/unit
0.50
0.40
0.50
0.30
0.50
0.30
148
01 erec.
02 ccode
02 units
pic 9.
pic 9(7).
working-storage section.
01 ans pic x value space.
01 head-1 pic x(80) value all '-'.
01 amt pic 9(5)v9(2) value 0.
01 head-2.
02 f pic x(11) value spaces.
02 f pic x(6) value "CSCODE".
02 f pic x(11) value spaces.
02 f pic x(5) value "Units".
02 f pic x(11) value spaces.
02 f pic x(10) value "Amount".
02 f pic x(11) value spaces.
01 head-3.
02 f pic x(5) value spaces.
02 e-ccode pic z.
02 f pic x(5) value spaces.
02 e-units pic z(7).
02 f pic x(10) value spaces.
02 e-amt pic z(5).z(2).
screen section.
01 b-screen.
02 blank screen.
procedure division.
p-1.
open extend efile.
perform g-w-para until ans = 'n' or 'N'.
close efile.
open input efile.
display head-1.
display head-2.
display head-1.
read-para.
read efile at end go to close-para.
go to c1 c2 c3 c4 depending on ccode.
c1.
compute amt = units * 0.50
go to m-para.
c2.
if ( units < 1000)
149
Columns
----------1-4
5-10
11-30
31-32
33
34
150
them in 2 files.
File-1: Records of all males over 18 years of age who are in
the third year in the college.
File-2: Records of all females under 19 years of age in the
fourth year in the college.
Use condition names for sex and year in college.
identification division.
program- id.
environment division.
input-output section.
file-control.
select collfile assign to disk
organization is line sequential.
select malefile assign to disk
organization is line sequential.
select femalefile assign to disk
organization is line sequential.
data division.
file section.
fd collfile
label records are standard
value of file- id is "coll.dat".
01 collrec.
02 sno pic 9(4).
02 rno pic 9(6).
02 name pic x(20).
02 age pic 9(2).
02 sex pic 9.
88 male value 1.
88 female value is 2.
02 yr pic 9.
88 third value 3.
88 fourth value is 4.
fd malefile
label records are standard
value of file- id is "male.dat".
01 malerec pic x(80).
fd femalefile
label records are standard
value of file- id is "female.dat".
01 femalerec pic x(80).
151
working-storage section.
01 ans pic x value space.
procedure division.
p-1.
display(1 1) erase.
open output collfile.
perform g-w-para until ans = 'N' or 'n'.
close collfile.
open input collfile output malefile femalefile.
read-para.
read collfile at end go to close-para.
if (male and age > 18 and third)
move collrec to malerec
write malerec.
if(female and age < 19 and fourth)
move collrec to femalerec
write femalerec.
go to read-para.
close-para.
close collfile malefile femalefile.
stop run.
g-w-para.
display(1 1) erase.
display(3 5) "Sno : ".
accept sno.
display(5 5) "Rno: ".
accept rno.
display(7 5) "Name: ".
accept name.
display(9 5) "Age : ".
accept age.
display(11 5) "SEX (1 - Male ; 2 -Female) : ".
accept sex.
display(13 5) "YEAR (3 - third; 4 - fourth : ".
accept yr.
write collrec.
display(20 5) "Add more(y/n) :".
accept ans.
25.12 LET US SUM UP
The learner in this lesson has been introduced 11 different programs that include
Program for Add Corresponding, Program for Move Corresponding, Program for Condition
names, Program using Occurs Clause, Program for Master File Maintenance, Program for
Master File Maintenance (Alternate Key usage), Program to find Interest on Bank Deposits,
Program for Inventory, Program to rewrite Pay Rate, Program for Electricity Bill and
152
Program to create 2 files using an Existing File. Having tried all these programs in system,
the learner can definitely feel confident to write good COBOL programs on his own.
25.13 LESSON-END ACTIVITIES
Try to find the answers for the following exercises on your own.
1. Accept from the terminal the age and name of a student and if he is over 21,display
that he is eligible to vote ; else display the number of years he must wait before he can
vote. Also check whether the last ACCEPT was terminated by pressing f2 key or not,
if f2 key was used as the terminating key, transfer control to the paragraph known as
FUNC-TWO
2. The balance b in an account with a principal p and simple interest of r % after n years
is given by the formula: B=P (1+NR/100). Given p in rupees calculate and display b
to the nearest rupee. Assume that n and r are integers obtained through ACCEPT
statement. (one program may use arithmetic Verbs and the other may use compute
statement)
3. The format of the input record is as follows
columns
----------1 - 10
11 - 30
31 36
37 - 42
(i)
(ii)
fields
-------------part number
Description of item
stock quantity(xxxx.xx)
stock value(xxxx.xx)
2 col.
1 col.
2 col.
1 col.
2 cols.
1 col.
153
Master = 2
Doctorate = 3
5.
Create a sequential file with the following record layout using the SCREEN
SECTION
FIELDS
6.
7.
PICTURES
Order number
Customer number
Salesman number
Date
Number of items
Product code
Quantity
Display the following menu:
9(6)
9(5)
9(4)
9(6)
9
x(6)
9(5)v99
1.triangle
2.square
3.rectangle
Depending on the choice, display the shape filled with asterisks (*). Assume suitable
size for these shapes.
The input record layout is given below:
Positions
fields
1-8
Account- number (alphanumeric)
9-15
Not used
16-17
Trans-code (numeric integer)
18-60
Not used.
Write a program that will sort the file in to the trans-code into the account-number
order
8.
Field
Subscriber number
Subscriber name
Address
Phone-no
The above information about new subscribers is stored in a new file. Assuming the
records are already stored in both the files, merge them and create a new file.
25.14 REFERENCES
1. COBOL Programming , M.K.Roy & Ghosh Dastidar , Tata McGraw Hill,
2nd Edition,1998
2. COBOL Programming , V. RAJARAMAN, PHI Pub
3. Introduction to COBOL programming Dr. R.Krishnamoorthy, JJ Publ
4. Structured COBOL , Welburn, TataMcGraw Hill , 4th Edition.