Cobol Module
Cobol Module
INTRODUCTION
Objectives:
1
COBOL (pronounced /ˈkoʊbɒl/) is one of the oldest programming languages still in acrive use.
Its name is an acronym for Common Business –Oriented Language, defining its primary domain
in business, finance, and administrative systems for companies and governments.
The COBOL 2002 standard includes support for object-oriented programming and other modern
language features.
A specification of COBOL was initially created during the second half of 1959. The scene was set
on April 8 at a meeting of computer manufacturers, users and university people at the
University of Pennsylvania Computing Center and subsequently the United States Department
of Defense agreed to sponsor and oversee the next activities. A meeting was held at the
Pentagon on May28 and 29(exactly one year after the Zürich ALGOL 58 meeting), chaired by
Charles A. Phillips. There it was decided to set up three committees, short, intermediate and
long range ( the last one was actually never formed). It was the Short Range Committee,
chaired by Joseph Wegstein of the US National Bureau of Standards that during the next months
would create a description of the first version of COBOL. The committee was formed to
recommend a short range approach to a common business language. The committee was made
up of members representing six computer manufacturers and three government agencies. The
six computer manufacturers were Burroughs Corporation, IBM, Minneapolis-
Honeywell(Honeywell Labs), RCA, Sperry Rand, and Sylvania Electric Products. The three
government agencies were the US Air Force, the David Taylor Model Basin, and the National
Bureau of Standards (now National Institute of Standards and Technology). The intermediate-
range committee was formed but never became operational. In the end of a sub-committee of
the Short Range Committee developed the specifications of the COBOL language. This sub-
committee was made up of six individuals:
2
COBOL-60) and on 6 and 7 of December essentially the same COBOL program was run on two
different makes of computers, a RCA computer and a Remington-Rand Univac computer,
demonstrating that compatibility could be achieved.
Since 1959 COBOL has undergone several modifications and improvements. In an attempt to
overcome the problem of incompatibility between different versions of COBOL the American
National Standards Institute (ANSI) developed a standard form of the language in 1968. This
version was known as American National Standard (ANS) COBOL. In 1974, ANSI published a
revised version of (ANS) COBOL, containing a number of features that were not in the 1968
version. In 1985, ANSI published still another revised version that had new features not in the
1974 standard. The language continues to evolve today. Object-oriented COBOL is a subset of
COBOL 97, which is the fourth edition in the continuing evolution of ANSI/ISO standard COBOL.
COBOL 97 includes conventional improvements as well as object-oriented features. Like the C++
programming language, object-oriented COBOL compilers area available even as the language
moves toward standardization.
The specifications approved by the full Short Range Committee were approved by the Executive
Committee on January 3, 1960, and sent to the government printing office, which edited and
printed these specifications as COBOL 60.
The American National Standards Institute (ANSI) has since produced several revisions of the
COBOL standard, including:
COBOL-68
COBOL-74
COBOL-85
COBOL 2002
From 2002, the ISO standard is also available to the public coded as ISO/IEC 1989.
Legacy
COBOL programs are in use global in governmental and military agencies, in commercial
enterprises, and on operating systems such as IBM’s z/OS, Microsoft’s Windows, and the POSIX
families (Unix/Linux etc.). In 1997, the Gartner Group reported that 80% of the world’s business
ran on COBOL it over 200 billion lines of code in existence and with an estimated 5 billion lines
of new code annually.
Near the end of the twentieth century the year 2000 problem was the focus of significant
systems decades before. The particular level of effort required for COBOL code has been
attributed both to the large amount of business-oriented COBOL, as COBOL is by of the COBOL
language such as the PICTURE clause, which can be used to define fixed-length numeric fields,
including two-digit fields for years.
3
COBOL 2002 and object-oriented COBOL
The COBOL2002 standard supports Unicode, XML generation and parsing, calling conventions
to and from non-COBOL languages such as C, and support for execution within framework
environments such as Microsoft’s .NET and Java (including COBOL instantiated as Enterprise
JavaBeans). Fujitsu and Micro Focus currently supports object- oriented COBOL compilers
targeting the .NET framework.
COBOL Advantages
It is machine independent. A COBOL program can be executed in different types of
computer with slight or no modifications at all.
It is easy to maintain. There are few modifications of the COBOL-74, it was revised only
in 1985 through COBOL-85, the latest began its modification only in late 1990s.
Therefore, a program that is easy to maintain can save a company considerable time and
money.
It is easy to understand. The programming language instructions or code contain
English-like words and phrases.
COBOL programs are uniquely organized. Only four major parts are needed to
understand. These parts are called divisions.
A COBOL program can handle voluminous commercial data processing using only a few
statements. COBOL is well suited for handling and processing large quantities of data by
writing several program statements using its input-output operations. This is unique in
comparison with other language.
COBOL as defined in the original specification included a PICTURE clause for detailed
field specification. It did not support local variables recursion, dynamic memory
allocation, or structured programming constructs. Support for some or all of these
features have been added in later editions of the COBOL standard.
COBOL has many reserved words (over 400), called keywords. The original COBOL
specification supported self-modifying code via the infamous “ALTER X TO PRECEED TO Y
“statement. This capability has since been removed.
Syntactic features
4
The abbreviated conditional expression
IF SALARY>9000 OR SUPERVISOR-SALARY OR =PREV-SALARY
is equivalent to
IF SALARY> 9000
OR SALARY>SUPERVISOR-SALARY
OR SALARY=PREV-SALARY
COBOL provides “named conditions” (so-called 88-levels). These are declared as sub-items of
another item (the conditional variable). The named condition can be used in an IF statement,
and tests whether the conditional variable is equal to any of the values given in the named
condition’s VALUE clause. The SET statement can be used to make a named condition TRUE (by
assigning the first of its values to the conditional variable).
COBOL allows identifiers to be up to 30 characters long. When COBOL was introduce, much
shorter lengths (e.g., 6 characters for FORTRAN) were prevalent.
The concept of copybooks was introduced by COBOL; these are chunks of text which can be
inserted into a program’s code. This is done with the COPY statement, which also allows parts
of the copybook’s text to be replaced with other text (sing the REPLACING … BY… clause).
Hello, world
IDENTIFICATION DIVISION.
PROGRAM-ID. HELLO-WORLD.
PROCEDURE DIVISION.
MAIN.
DISPLAY ‘Hello, world.’.
STOP RUN.
5
COBOL applications often run in critical areas of business. For instance, over 95% of
finance- insurance data is processed with COBOL. The serious financial and legal
consequences that can result from an application failure is one reason for the near panic
over the year 2000 problem.
COBOL applications often deal with enormous volumes of data. Single production files
and databases measured in terabytes are not uncommon.
When programmers are new, both the in-program comments and the external
documentation accurately reflect the program code. But over time as more and
more revisions are applied to the code, it gets out of step with the documentation
until the documentation is actually a hindrance to maintenance rather than a help.
The self-documenting nature of COBOL means that this problem is not as severe with
COBOL programs as it is with other languages.
Readers who are familiar with C or C++ or Java might want to consider how difficult it
becomes to maintain programs written in these languages. C programs that you
have written yourself are difficult enough to understand when you come back to
them six months later. Consider how much more difficult it would be to understand
a program that had been written fifteen years previously, by someone else and which
had since been amended and added to by so may others that the documentation no
longer accurately reflects the program code. This is a nightmare still awaiting
maintenance programmers of the future.
6
COBOL is simple
COBOL is a simple language (no pointers, no user defined functions, no user defined
types) with a limited scope of function. It encourages a simple straightforward
programming style. Curiously enough though, despite its limitations, COBOL has
proven itself to be well suited to its targeted problem domain (business computing).
Most COBOL programs operate in a domain where the program complexity lies in the
business rules that have to be encoded rather than in the sophistication of the data
structures or algorithms required. And in cases where sophisticated algorithms are
required COBOL usually meets the need with an appropriate verb such as the SORT
and the SEARCH.
We noted above that COBOL is a simple language with a limited scope of function.
And that is the way it used to be but the introduction of OO-COBOL has changed all
that. OO-COBOL retains all the advantages of previous versions but now includes-
7
III. FEATURES OF A COBOL PROGRAM
A. English-like syntax
B. Unusual length compared with programs written in other languages.
C. Column-sensitive organization of the program.
D. Spacing between any two-program segments.
E. Use of indentations.
COBOL programs are written according to a special structure that is organized into a
hierarchy of parts. The structure of the hierarchy is described as follows:
A. A character is the lowest form in the program structure.
B. A word is made up of one or more characters.
C. A clause consists of characters and words, and is used to specify an attribute of an
entry.
D. A statement is a syntactically valid combination of words and characters written in
the PROCEDURE DIVISION of a COBOL program and beginning with a verb.
E. A sentence is a sequence of one or more statements the last of which is terminated
by a period followed by a space.
F. A paragraph consists of one or more sentences.
G. A division consists of one or more paragraphs or sections. Every COBOL program
consists of four divisions in the following order: IDENTIFICATION DIVISION,
ENVIRONMENT DIVISION, DATA DIVISION and PROCEDURE DIVISION.
Every COBOL program consists of for separate divisions, each with specific functions:
8
The structural organization of a COBOL program is perhaps one of its unique features.
No other language is written like it. The program follows a hierarchical organization. The basic
structural unit of a program is the division. COBOL programs are divided into major and minor
parts namely, divisions sections, and paragraphs. These can be illustrated as follows:
INPUT-OUTPUT FILE-CONTROL
DATA FILE
WORKING-STORAGE
COBOL program is written in an 80-column format. The column on the leftmost side is
the column 1; the rightmost is column 80. Of the 80 columns, only 66 columns (columns 7-72)
are actually used for the program itself. Columns 1-6 and 73-81 are for reference only.
9
B. COLUMN 7 (INDICATOR ARE)
This column is used for special purposes. A specific entry in this column has a special
meaning. Special characters are:
* - Indicates a comment statement. This line provides remarks for the
program. Lines having asterisk in column 7 are ignored by the COBOL compiler.
/ - Makes the computer go to the top of a new page before printing a report.
- - Indicates that the line is a continuation of the preceding line.
Column 8 which represents Area A, is the start of Division, Section Heading, File
Description Heading, Records Heading and Procedure Heading.
Column 12 which represents Area B, is the start of Program statement. Every line of the
sample program ends with a period. This is considered an important part of COBOL programs.
Fig. 3 Sample of Program Area A
and B.
D. COLUMN 73 – 80
(IDENTIFICATION AREA)
Writing part of program
statement in this area is
prohibited in COBOL. Anything
written on it is ignored by COBOL during its compilation. These were used when programs were
punched on cards, in order for the cards of different programs not to get mixed up.
10
Fig. 5 Sample of COBOL Template
11
Review Questions
3. What are the four (4) divisions of COBOL program and be able to differentiate each.
4. Draw the complete parts of the Coding form at the back of this page.
12
LESSON 2
STRUCTURE OF THE
LANGUAGE
Objectives:
13
I. COBOL CHARACTER SET
CHARACTER MEANING
0,1,2,.….9 Digit
A,B,C,…Z Letter
Space (blank)
+ - * / > <
A. USER-DEFINED WORD
This is given by the programmer of the language user. In the use of this word, certain rules are followed,
1. A name must be constructed from the letters of the alphabet, the digits 0 through 9, and the hyphen. No other
4. A name must contain at least one letter of the alphabet. Digits only and digits in combination with hyphens are not
allowed.
5. A name must not be a reserves COBOL word because reserves COBOL words have pre-assigned meanings.
B. RESERVED WORD
14
C. This is a word which has a special meaning in COBOL. It is defined by the COBOL language. The programmer
cannot use this word except in the form specified by the language.
D. Keyword – Word that is required in a particular COBOL statement for the computer to interpret. For example, “
E. Optional Word - Word that may be included in the COBOL statement to improve readability for users. For
F. Figurative Constant – This is a reserved word that may be used in place of certain literals. It is used in COBOL
statements to enhance the readability of the language. For example, “ZERO”, “ZEROS”, “ZEROES” – represents the
value of 0.
This module will use an illustrative example of a running program. The sequence will be illustrated and discussed in
Case Study: Write a COBOL program that will compute for the average grade of students. The program will ask for
an input of student no, student name, midterm and final grade. Compute for the average grade.
INPUT DATA:
PUP
CCMIT
AVERAGE : ________
15
2 PROG RAM-ID AVERAGE.
8 FILE -CONTROL.
10
11 DATA DIVISION.
12 FILE SECTION.
13 FD GRADEFILE
22 01 ANS PIC X.
24 01 GR-REP.
28 01 HDGI.
32 01 HDG2.
16
34 05 FILLER PIC X(5) VALUE “CCMIT”.
36 01 HDG3.
41 01 HDG4.
47 01 HDG5.
49
50 SCRE EN SECTION.
51 01 SCRN.
52 05 BLANK SCREEN.
53
56 PERFORM HDG-RTN.
58 GO TO FIN-RTN.
59 HDG- RTN.
65 COMP GRADE.
17
66 DISPLAY SCRN.
72 ACCEPT MIDTERM.
74 ACCEPT FINALS.
76 END-ADD.
84 ACCEPT ANS.
85 FIN- RTN.
86 CLOSE GRADEFILE.
87 STOP RUN.
Review Questions
18
2. Be able to differentiate the two types of COBOL Word.
EXERCISES
1. Write Valid if the user-defined word is valid and Invalid if the user-defined word is
invalid.
19
IDENTIFICATION DIVISION.
__________________________
________________ DIVISION.
_________________ SECTION.
SOURCE-__________________
___________________________
_________________ SECTION.
_________________ DIVISION.
_________________ SECTION.
__________________ DIVISION.
20
LESSON 3
IDENTIFICATION AND
ENVIRONMENT DIVISION
Objectives:
This module will follow specific format in typing program syntax. Rules are as follows:
21
A. Uppercase words are COBOL reserved words that have special meaning to the compiler.
B. Lowercase words are use-defined entries. They are within curly braces { }.
C. Underlined words are required in the paragraph.
D. If punctuation is specified in the format, it is required.
E. Brackets [ ] mean the clause or paragraph is optional.
F. The use of dots or ellipses (…) means that additional entries of the same type may be
included if desired.
A. IDENTIFICATION OF DIVISION
Syntax:
IDENTIFICATION DIVISION.
PROGRAM-ID. program name
[AUTHOR. {comment-entry}…..]
[INSTALLATION. {comment-entry…..}]
[DATE-WRITTEN. {comment-entry…}]
DATE-COMPILED.
[SECURITY. {COMMENT-ENTRY….}]
REMARKS.
IDENTIFICATION DIVISION is the first division of CPBOL program. The function of this
division is to supply information about the program to others who may use it as reference. It
describes the program to potential users. It states the name of the program and other optional
information such as information regarding author, the date the program was written, security.
Etc. its purpose is to identify program and its author and to provide other general information
about the program, such as the dates the program is written and compiled, any program
security, and so forth. They start in column-8 of the COBOL coding sheet. The only required
paragraph in this division is the PROGRAM-ID paragraph while the rest is optional.
TIP:
A clause with a combination of two words is always connected with hyphen.
22
Ex. PROGRAM-ID, INPUT-OUTPUT SECTION, FILE-CONTROL
Take note also of how the statement is separated by period.
All paragraph-names start in column 8 and, as indicated above, are optional with
exception of the PROGRAM-ID. The compiler does not process what follows the COBOL words
but only prints the content. Thus, after the DATE-WRITTEN we could have written ANYTIME IN
JUNE. The compiler derives no more meaning from it, therefore, the programmer should be
concerned simply with choosing verbal descriptions that will be meaningful to the potential
readers of the program.
The DATE-COMPILED paragraph may be left blank. The compiler will insert the actual
date and the source listing will include that date.
B. ENVIRONMENT DIVISION
Syntax:
ENVIRONMENT DIVISION.
[CONFIGURATION SECTION.
SOURCE-COMPUTER. {computer name}
OBJECT-COMPUTER {computer name}
SPECIAL NAMES {computer name}
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT {filenamne-1}
ASSIGN TO {implementor-name-1}….]
23
entries in this division will be dependent in [1] the computer system and [2] the specific devices
or hardware used in the program. This division also briefly describes the data files required by
the program.
The ENVIRONMENT DIVISION is the only division of a COBOL program that will change
significantly if the program is to be run on a different computer. Since computers have various
models and equipment, each computer center will require division. The CONFIGURATION
SECTION and the INPUT-OUTPUT SECTION, which are again divided into paragraphs.
1. CONFIGURATION SECTION
Syntax
[CONFIGURATION SECTION.
SOURCE-COMPUTER. {computer-name}
OBJECT-COMPUTER. {computer-name}
SPECIAL-NAMES. {computer-name}
It supplies the information about the computer on which the COBOL program will be
compiled and executed. (It is optional in COBOL-85) Configuration section provides
documentation information which includes the computer manufacturer, computer number and
computer model number. The two sections are coded in column 8. Configuration section has
three paragraphs:
a. SOURCE-COMPUTER – The computer that will be used for compiling the program.
b. OBJECT-COMPUTER – The computer that will be used for executing or running the
program.
c. SPECIAL-NAMES – A third paragraph that is optional in the configuration section. This
focuses on special devices used for reading or displaying data.
24
Fig. 7 Sample of CONFIGURATION SECTION
Each paragraph name is directly followed by a period and then a space. The designated
computer IS ALSO FOLLOWED BY A PERIOD. In the example, the source and object computers
are the same. In general, this will be the case, since compilation and execution are usually
performed on the same computer. If, however, the program will be compiled on one model
computer and executed, at some future time, on another model computer, these entries will
differ. This is also optional in COBOL program.
2. INPUT-OUTPUT SECTION
Syntax:
FILE-CONTROL.
SELECT {filename}
ASSIGN TO {implementor-name-1}
The INPUT-OUTPUT SECTION supplies the information about the specific devices used in
the program namely: terminals, printers, and disk drives. It is also optional but is being used
most of the time since programs use files. It supplies information concerning the input and
output devices used in the program. This is started by the FILE-CONTROL paragraph. The FILE-
CONTROL paragraph consists of SELECT statements. A SELECT statement defines a filename and
assigns a device to that file (A file is the major collection of data for a given application).
Typically, we have an input file and an output file. Input file is a collection of data which serves
as a reference for processing of data and the output file is a second collection of data which
serves as an output report. The implementor-name is not a COBOL reserved word nor user-
defined word. It is machine-dependent device specification provided by the computer center.
TIP:
25
A filename must correspond to the rules of forming user-defined names stated above
(i.e. maximum of 30 characters, letters, digits, and hyphen only, no embedded blanks, at
least one alphabetic character and not a reserved word).
It is more logical to define the input file first before the output file.
Write SELECT statement on two lines for better readability. The best format is as follows:
SELECT filename
ASSIGN TO device
A filename must be specific and meaningful. Avoid acronyms, person’s name and
aliases. Typically, a filename must be related to the subject of the program. If the
program is regarding sales, it can be regarded as SALES-INPUT on input file and SALES-
OUTPUT on output file.
The implementor-name varies depending on the computer used. It can rather be cryptic
as: SELECT CUSTFILE ASSIGN TO SYS005-UR-2540R-S or can be easily as: SELECT GRADEFILE
ASSIGN TO “MYFILE.DAT”. The program syntax of Implementor-name is as follows:
Example:
SELECT SALES-INPUT ASSIGN TO B:\DATA\SALES-INPUT.DAT.
It must be noted that PRINTER is commonly used in an output file and that there must be a
connected printed to it.
26
Review Questions
4. Write the COBOL statement for the following situations. Consider the rules in using
the coding form.
a. The computer to be used in encoding the program is IBM-PC.
b. The writer of the program is you.
c. The place of where the program is to be processed is PUP.
d. The computer to be used in compiling and executing the program is IBM-PC.
27
e. The file to be read by the program is student file. (STUDFILE is the external
file and the INSTUD is the internal file).
f. The result of processing is to be printed(OUTFILE is the external file and the
OUTSTUD is the internal file).
28
LESSON 4
DATA DIVISION
Objectives:
It should be up to 30 characters.
A name must be constructed from the letters of the alphabet, the digits 0 through 9,
and the hyphen. No other characters are allowed.
There should be no embedded blanks (i.e. no blanks are permitted within the data-
name)
29
A name must not be a reserved COBOL word because reserved COBOL words have
pre-assigned meanings.
Use prefix of suffix whenever it is needed. This is to make the data-name easier to
read and remember. By placing prefix or suffix, it will be easier to distinguish an input
field from an output field and those fields which belongs to the same group level. For
example, STUDREC-IN and STUDREC-OUT.
A. Variable Data – These are data that change during each run of a program. Variable data are
used as storage for a value that varies during processing.
B. Constant Data – A fixed value or literal that is used in a program. Constant data is not
dependent on the input to the system since this is coded directly in the program. It can
come directly in the PROCEDURE DIVISION or defined in the DATA DIVISION with a VALUE
clause. This will be explained later on in this chapter.
30
IV. DATA ORGANIZATION FOR COBOL PROGRAM
A. File – An organized accumulation of related data. Data are organized in the form of a file.
Any number of input and output files can be used in a COBOL program. A file is divided
into records, and records are, in turn, subdivided into data fields. In the program we are
using as basis of our example, the files are INFILE as our input file and OUTFILE as out
output filed.
B. Record – A file is divided into many segments of data called record. COBOL reads and
writes the file per record. Each record contains information that can be divided into field.
For example, a student file containing information of group of students.
C. Data field – A record is divided into smaller segments, called data field, or simply field. It
is a group of consecutive positions reserved for an item of data. A record may be divided
into any number of data fields. For example, a student record can be divided into
student identification number, name, course, year and section, in COBOL, data fields can
be of three different types numeric, alphabetic, and alphanumeric.
a. Numeric Data Field – A data field used to store numbers. This represents only the digits
0 to 9. It is represented by 9 and V character in the data declaration. Examples are age,
price, sales, quantity, grade, etc.
31
A + or sign may be used, but it must appear to the left of the number. A plus or
minus sign is not required within the literal, but it may be included to the left of the
number. That is, +16 and -12 are valid numeric literals but 16+ and 12- are not. If no
sign is used, the number is assumed positive.
A decimal point is permitted within the literal. The decimal point, however, may not be the
rightmost character of the literal.
c. Alphanumeric Data Field – A Data field used to store both number and
nonnumeric data. This data field can represent both numeric and nonnumeric
characters. It is represented by X character in the data declaration. Examples are
social security numbers, address since it may contain letters and numbers.
Although most names contain letters of the alphabet only, there are names that
consist of alphabets and special characters such as the apostrophe in the name
SHAQUILLE O’NEAL. For this reason, most COBOL programs store names as
alphanumeric data.
d. Figurative Constant – These are COBOL reserved words which has special
meaning to the program. It can be coded in replacement for the equivalent
character set for better readability of the program. Some of these constants are:
ZEROS All three forms are equivalent, and they reference the value of
ZEROS In an instruction such as MOVE ZEROS TO AMOUNT, the
ZEROES storage field AMOUNT would be filled by as many zeroes as there
are positions in that field. Thus the context determines the number
of occurrences of the character 0.
32
SPACES Both forms are equivalent, and they reference one or more blanks,
SPACES similar to the ZERO constants.
QUOTE Both forms are equivalent, and the reference the quotation marks.
QUOTES
ALL References one or more occurrences of the single character
nonnumeric literal, as in MOVE ALL “A” TO HEADER, which
results in the storage field HEADER being filled with As.
HIGH-VALUE Both forms are equivalent, and they reference the highest
HIGH-VALUE value in the collating sequence for the particular computer
system.
LOW-VALUE Both forms are equivalent, and they reference the lowest
LOW-VALUES value in the collating sequence for the particular computer
system.
Elementary Data Field – A data field that cannot further be divided into components.
Another example is the mailing address, which is considered as group data field. Its
components are “residence number”, “street name”, “city name”, state name”, and “zip
code”. These are elementary data fields.
Syntax
DATA DIVISION
FILE SECTION
FD filename
[LABEL RECORDS IS STANDARD]
[LABEL RECORDS ARE OMMITED]
[RECORD CONTAINS _______ CHARACTERS]
[DATA RECORD IS _________________]
33
01 record name
WORKING-STORAGE SECTION
{record description entry
variables description entry
77-level description entry
DATA DIVISION is the one concerned with the identification and description of storage fields
and data used by program. It describes the input and output files to specific devices in the
INPUT-OUTPUT SECTION of CONFIGURATION SECTION. It defines and describes fields, records,
and files in storage. Whatever variables and constant used in PROCEDURE DIVISION statements
are declared here. It consists of two sections: the FILE SECTION and the WORKING-STORAGE
SECTION.
DATA DIVISION.
FILE SECTION.
FD filename
[LABEL RECORD IS STANDARD]
[LABEL RECORDS ARE OMMITED]
[RECORD CONTAINS ______ CHARACTERS]
[DATA RECORD IS _________________]
1 RECORD NAME.
A. FD clause – is an abbreviation for file description and is coded in Area A. this paragraph
is followed by file name that must correspond exactly, character for character, to a file
that is already mentioned in the ENVIRONMENT DIVISION.
B. LABEL RECORD or LABEL RECORDS clause – These clauses are optional for COBOL 85.
This used to indicate if a header and a trailer record are to be created by system. Both
34
records provide file identification information about the file. The first record will bear
the header label while the last record will be a trailer label. These are created on output
files and checked on input files. If LABEL RECORDS is used, these records are not created.
This is typically used on files that are directed to a printer or screen which do not require
the header and trailer records.
For disk or tape files, the RECORD CONTAINS clause varies. One of the
advantages of storing data on the media is that records can be of any size.
D. BLOCK CONTAINS clause – indicates the blocking factor for disk or tape.
All other entries should be coded in Area B (i.e. filename and LABEL RECORDS)
If LABEL RECORDS clause is used, no period is coded from FD until the last clause has
been specified.
Commas are always optional in a program to separate clause. If used, they must be
followed by at least on blank.
It is recommended that each clause appear on separate line for clarity and ease of
debugging.
35
Fig. 9 Sample of FILE SECTION
of DATA DIVISION
Fig. 10 describes INREC as level 01, AREA-CODE, SALENO and SALE-NAME are all coded in
Level 05. all items that are coded on the same level are not subordinated to or related to one
another. These are called independent items. Note that level 05 is used and not level 02. we will
use levels 5, 10, 15 and so on in our further discussion. This is to provide additional levels in
case insertion of field is needed. In case the SALE-NAME field is further divided as LASTNAME,
FIRSTNAME and MIDINITIAL, this will be declared as:
36
Fig. 11 Sample of Record Entry with Elementary and Group Level
SALE-NAME becomes a group data field and its subordinate an elementary field. Note
that declaration of data field length and type is coded on elementary field.
Although it is legal to choose any level numbers to describe the data fields that are at
the same level. The following example illustrate this point.
Fig.11 Sample of Record Entry with Invalid Elementary and Group Level
B. WORKING-STORAGE SECTION – this is where variables and constant which not part of
input but nonetheless required for processing are declared. These include counters,
end-of-file indicators, and work areas.
The WORKING-STORAGE SECTION immediately follows the FILE SECTION in the program.
This section provides for the storage of data items that are not part of any section, such as
intermediate calculations, report headings for printing and numeric constants for use in
calculations. The procedure for declaring an elementary and group item is still the same
however, in older version of COBOL, it uses a special level number 77 to describe all
elementary independent items. The practice is not common now since using level 77 and
level 01 is just the same. It is also suggested to put a prefix of WS for every variable entry to
distinguish it from those in FILE SECTION.
37
The WORKING-STORAGE SECTION must succeed the FILE SECTION. It must not be
encoded before the FILE SECTION.
WORKING-STORAGE SECTION is coded on Area A and ended with a period.
Group item that will be submitted into other subordinate levels must be defined PIC
clause must appear in the elementary item.
Elementary item must contain a PIC clause. It may contain an initial value using VALUE
clause. VALUE clause may precede or succeed PIC clause.
VALUE clause is used only in the WORKING-STORAGE SECTION and not in the FILE
SECTION.
All items must follow the rules for forming data-names.
a. For storing intermediate results, counters and end-of-file indicators through the use of
variable data field.
b. For storing initial value not contained in the input file.
There are item entries and clauses which define the type of data that will be used in
variable declaration.
After declaring the level numbers, the term PIC follows. PIC is short for PICTURE clause.
Each elementary data field must be defined by a PIC clause that provides information as to
its(numeric, alphabetic, or alphanumeric.) and its size. A specific picture character A gives a
specific type of data. It is also used to declare the size or length of the field (i.e. the number
enclosed in parentheses). Size or length of the fields pertains to a maximum number of
characters that will be accepted by the program. The PIC clause is written at the end of the data
field (leaving at lest one blank space after the data field name with the word PIC followed by at
least one blank space and the appropriate picture character (X or 9 or A). if a data field requires
more that one picture character, the number of characters to which the picture characters
applies be enclosed in parentheses following the picture character.
38
There must be at least one blank space between the word PIC and the picture
characters. There must not be a space between the character type and field length
enclosed in parentheses.
If a data field requires more than one picture character, the number of times the picture
character appears can be enclosed in parentheses. Thus, PIC 9999 is the same as PIC9(4).
Each group data field must end with a period. Each elementary data field must also end
with a period after the picture characters.
It is important to understand the distinction between a numeric data value that can be
contained in a data field with 9’s for picture characters and in a data field with X’s as
picture characters. Only a data field that specifies “9” for picture characters can contain
numeric data that is to be used in a calculation.
The V character indicated the position of an assumed decimal point. This means that the
decimal point is not written as part of the field and therefore is not included as part of the field
39
size. This does not occupy a storage position. Instead, the information about decimal-point
location is stored elsewhere in the computer, so that any arithmetic computations can be done
correctly.
The X PICTURE character denotes that alphanumeric positions are contained in a field.
Fig. 9 declares AREA-CODE as of alphanumeric type and of size 1, SALENO is alphanumeric and
size 10, SALE-NAME is alphanumeric and can contain a maximum of 25 characters. This means
that it can include alphabetic characters, numeric characters and special symbols. The PICTURE
X is most likely to use in variable NAME because there are names which contain special symbol
as “SHAQUILLE O’NEAL”. When the characters do not fill an X field completely they are left
justified, with blanks filling the remaining positions in the right.
The A PICTURE character is similar to the X character, except that it indicates only
alphabetic characters and blanks.
The P PICTURE character is used in conjunction with the V character to indicate the
position of a decimal point in cases where the decimal po8int is not within the number. The P
character is not used very much in administrative applications. It is used best to scientific
computational needs, which are likely to be better satisfied by the use of languages other than
COBOL. This character is used, for example, when it is understood that a value held in storage
represent thousands of units and we wish to indicate the decimal position for this value. The
following examples indicate the use of this character. As before, the caret indicates the position
of an assumed decimal point.
The S character is used to designate a numeric field that is signed (i.e., one that can be
negative in value.) In COBOL, all fields are considered positive unless the S has negative value.
40
Only one S character may be used in a field. It is coded in the leftmost character. The S is not
counted in the size of the filed, and therefore S999 is a field of three positions. In the following
examples, the negative sign in machine representation is as shown “-“ on top of the rightmost
digit, in order to preserve the concept that it does not take up an extra position.
FILLER is a COBOL reserved word used to define areas within a record that will not be
referenced individually during processing. This is a generic data name used extensively in the
DATA DIVISION with respect to data items that are not referenced specifically in the PROCEDURE
DIVISION.
41
FILLER clause is also optional in record description. The following is acceptable:
Fig. 14 Example of Data Division without FILLER command.
This process of assigning an initial value to a data field is known as initialization and is
performed by using a VALUE clause. A VALUE clause consists of the word VALUE followed by the
initial value, and is placed immediately after the PICTURE clause. The initial value can be a
numeric literal, a nonnumeric literal, or a figurative constant. Rules for this paragraph Literal and
figurative constants were discussed earlier.
42
Printing of asterisks for check protection.
Printing of plus and minus signs.
Printing of debit or credit symbols for accounting applications.
Printing of spaces or zeros as separators within fields.
The purpose of editing is to increase readability of the report. Editing is associated with printing
data on the printer. All editing is accomplished by moving an elementary item to a report item
which contains appropriate edit symbols. The editing function involves a change in the form of
data. For example, we may suppress leading zeros, we may use commas to make long numeric
values more legible, we may insert a dollar sign in front of a value, and so forth. This module will
not tackle the $, +, -, DB, CR, * picture characters since these are not typically used.
Decimal (.) PICTURE character indicates the position of the decimal point and serves to
align the actual decimal values in the field. Only one decimal point must appear in a field while
a field may contain more than one comma if the size of the field conforms to it. Each of these
insertion characters is used to indicate the position of the indicated character in the storage
location. A field cannot contain both V and . PICTURE characters.
43
The B PICTURE character is used to insert blank in the data entry. This is used to
increase readability of the data entry. For example, 05 SALENAME PIC X (!0) BX (14) BX. The
first 10 characters will be written first then a blank is inserted another 14 characters before
another blank is inserted.
The Zero insertion character is used to insert zeros in the designated position. This is
best used when we want to show the full value of digits. Let’s say, in thousands form. For
example 05 WS-POPULATION PIC 9,999,000 will result in 2,500.00. Assuming it has value of
2500.
The / PICTURE character is used to insert a stroke or forward slash in the designated
position. This is best used is editing date of birth. For example,
Further processing as MOVE DATEOFBIRTH TO DOB will cause DOB to contain 01/15/91.
44
- Minus sign
DB Debit sign
CR Credit sign
B Blank insertion
0 Zero insertion
/ Stroke insertion
Review Questions
45
5. Write the appropriate statement for the following situations.
e. The input file SALESFILE is to be read from the disk and the input record is
INREC. Give the FILE SECTION ENTRIES.
f. The computer that will be used in encoding the program is NEC and the
computer to be used in executing the program is IBM-PC. Give the
CONFIGURATION SECTION ENTRIES.
g. The name of the COBOL program is PUP-SRE. The author is ALET, B3 is the
computer laboratory to be used, the program is to be created on this date
and to be compiled and executed tomorrow.
46
EXERCISES
STUDENT RECORD
{record#1}
{record#2}
47
……………
……………
……………
{record#n}
LESSON 5
Objectives:
48
At the end of the lesson, the students must be able to:
OPEN Statement
The OPEN statement used to link the actual physical file to a program file and prepare
the file to be processed. The file must be opened before data can be read from or written to a
file. The OPEN statement has the following format:
INPUT
OPEN OUTPUT filename-1, filename-2,..., filename-n
I-O
EXTEND
The filename must be exactly the same as it is in the SELECT statement of the
ENVIRONMENT DIVISION and the FILE SECTION of the DATA DIVISION.
A file may be opened for one of the following purpose:
1. INPUT
2. OUTPUT
3. I-O
4. EXTEND
When the program needs to read data from a file, the file must be opened for INPUT. A file
is opened for OUTPUT when the program will write data to the file. Only direct access files can
be opened for I-O and therefore the file should be stored in a direct access storage medium
such as magnetic disks. A file is opened in EXTEND mode when additional data are to be added
to the end of the file. To use a file in EXTEND mode, the file must already exist.
Examples:
49
OPEN INPUT STUDENT-FILE.
OPEN OUTPUT REPORT-FILE.
OPEN I-O EMPLOYEE-FILE.
OPEN EXTEND SALES-FILE.
In the first statement the file STUDENT-FILE must be opened for INPUT function only and
the second statement, REPORT-FILE is opened for OUTPUT function only. The third statement
opened EMPLOYEE-FILE as I-O, which means it can be used as an INPUT and at the same time as
OUTPUT. In the fourth statement, SALES-FILE was opened using the EXTEND option which
means that any new record written to it will be appended to the end of the file.
A single OPEN statement may be used to open more than one file.
Each filename must be preceded by the keyword INPUT or OUTPUT. A period is placed at the
end of the last file name only.
Example:
A single OPEN statement can also be used to open several input and output files.
Example:
OPEN INPUT FILE1, FILE2, OUTPUT FILE2, FILE4.
READ Statement
The READ statement reads data from the input file. The data are read one record at a
time. When processing a sequential input file, the READ statement reads records in sequence.
The first READ statement reads the first record, the next record reads the second record, and so
on. The READ statement has the following format.
The READ statement refers to the name of the input file defined in the INPUT-OUTPUT
SECTION of the ENVIRONMENT DIVISION.
The AT END clause of the READ statement tests whether the end of the file has been
reached. If the READ statement provided with the AT END clause execution time or a run time
error will result.
Example
50
In the give example, the records of the STUDFILE will be sequentially read until the end
of the file is reached. The imperative statement MOVE 1 TO EOFSW will be executed only if all
records in the file have been read already or a run time error was encountered. In this READ
statement, the PIC clause of EOFSW must be defined as a numeric data field with one digit (PIC
9). The value moved to the EOFSW, can be anything that the programmer wants it to be as long
as its PIC clause is appropriate for that value.
MOVE Statement
The MOVE statement moves a literal or the contents of a data field to another data field.
The data field receiving the value is called the receiving data field. The data field from which
the data are copied is the sending data field. There are two types of the MOVE statements: the
direct MOVE in which a value is directly moved to a data field, and the indirect MOVE, in which
a value contained in data field is moved to another data field. The general format of the direct
MOVE statement is
Examples:
MOVE 1 TO EOF-SW.
MOVE “Y” TO OPTION.
MOVE 20 TO COUNTER.
In the first example, the value 1 was moved to the data field EOF-SW. The second
example moved the character “Y” to the data field OPTION which was defined in the DATA
DIVISION having an alphabetic or an alphanumeric picture. The third example moved the value
20 to the data field COUNTER which was previously defined in the DATA DIVISION having a
numeric picture.
When moving a data value, it is important to ensure that the receiving data field is
correctly defined for that value. If a numeric value is moved, the data field should be defined as
numeric with an adequate number of digits. If an alphanumeric value is moved, the data field
should be defined as alphanumeric with an adequate number of characters.
51
In the previous examples, the data fields to which data values are moved should be
defined in this way:
05 EOF-SW PIC 9.
05 OPTION PIC X.
05 COUNTER PIC 99.
It also possible to use figurative constants with the MOVE statement. Figurative
constants have predefined meanings to the COBOL compiler. The following table gives the
meanings of some commonly used figurative constants when used in the MOVE statements.
Its value can be initialized to 10 blank spaces using this MOVE statement.
The movement of data to the receiving data field depends on the type of data being
moved. If alphanumeric or alphabetic data are being moved, the movement starts from the
leftmost character. If numeric data are being move, the movement starts from the rightmost
digit. If the receiving data field is longer than the value being moved, the additional positions
are padded with blanks on the right if the data field is defined as alphanumeric, and with zeroes
on the left if the data field is defined as numeric. Truncation or cutting off of the value occurs
from the right is the data field is defined as alphanumeric, and from the left of the value if the
52
data field is defined as integers. The following examples show the effect of the MOVE
statements on longer and shorter receiving data fields:
In the first example, four remaining positions on the right of the receiving data field are
padded with blanks. In the second example, truncation of the data value occurs from the right.
In the third example, a data field is padded with a zero on the left. In the fourth and fifth
examples, Truncation of data values occur from the left.
Either the VALUE clause or the MOVE statement may be used to assign an initial value to
a data field. The VALUE clause assigns the value during compilation, whereas the MOVE
statement assigns it during program execution. In general, if the value of data field is not going
to change, it is better to use the VALUE clause because it uses less execution time. However, if
the value needs to be continually reinitialized, the MOVE statement should be used.
PATRICK
53
EMPNAME EMPNAME-OUT
PATRICK PATRICK
EMPNAME EMPNAME-OUT
The PIC clauses of both the sending data field and the receiving data field play an
important role in what happens after the MOVE statement is executed. If the PIC clauses of
both data fields are exactly identical and exact copy of the data value is moved from the sending
data field to the receiving data field. If the PIC clause of the receiving data field is longer or
shorter than that of the sending data field, the extra spaces are padded, or truncation occurs, in
the same way as mentioned for direct moves.
1. Non numeric literals or data values may not be moved to alphabetic data fields.
2. Data may move from a non numeric field to a numeric field only if the non numeric field
contains a valid integer (It cannot be a real number). However, the practice is
discouraged because of unpredictable results. If the field does not contain valid integer
data, an error will occur.
3. Non numeric literals or data values may not be moved to numeric data fields.
4. When a receiving field is non numeric, the value moved into it is left-justified in the field.
This means that the first character is placed in the first position on the left side of the
data field. If the field is larger than the data value, blank spaces will be placed on the
right side to fill out the field. If the size of the field is smaller than the data value, the
value will be truncated to fit in the field. Any extra characters on the right side will be
cut off.
5. When the receiving field is numeric, the data will be aligned at the decimal point. If
there are fewer digits than the size of the field, zeroes will be added to fill out the field.
If the numeric data are longer than the field, the number will be truncated to fit into the
field.
54
Sending Data field Longer Shorter
Decimal
Integer position Pad on the left with zeroes Truncate on the left
Decimal position Pad on the right with zeroes Truncate on the right
WRITE Statements
The function of the WRITE statement is to write a record to an output file. WRITE
statement has the following format.
WRITE output-record-name
The data field output-record-name must be the same as that declared in the FILE
SECTION of the DATA DIVISION. The WRITE statement causes all data fields that are part of the
record to be written, one after another, to the output file.
Before writing an output record, make sure that a data value has been moved to each
data field that is part of the output record.
The WRITE statement is always followed by the name of the output record, not the
output file. Numeric edited (rather than numeric) fields should be used to output numeric data
that are destined for a printer.
Example:
WRITE EMPLOYEE-REC.
CLOSE Statement
55
The CLOSE statement closes a file so that it is no longer available for processing. All files
that are opened at the beginning of a program should be closed before ending the program.
The format of the CLOSE statement is
More than one file may be closed with one CLOSE statement. If more than one file is
closed with on CLOSE statement, the period appears at the end of the last file name. Do not use
the keyword INPUT or OUTPUT before the file name in a CLOSE statement.
Example
CLOSE STUDENT-FILE
CLOSE EMPLOYEE-FILE
TAXTABLE-FILE
REPORT-FILE
STOP RUN Statement
The STOP RUN statement terminates execution of the program. As soon as this
statement is encountered, the program stops execution. The format of the STOP RUN
statement is
STOP RUN.
The STOP RUN statement does not have to the last physical statement in the program,
but it must be the last statement that is executed by the program.
ARITHMETIC STATEMENTS
ADD Statement
The ADD statement is used to add the contents of two or more numeric data fields. The
format of the ADD statement is
56
ADD datafield-1 TO datafield-2.
This statement performs two functions: it adds the contents of datafield-1 and datafield-
2 and stores the result in datafield-2. With an ADD statement, the result is stored in the data
field listed last. On execution of the ADD statement, the contents of the data field that receives
the result of the calculation are changed. However, the contents of the other data field remain
unchanged.
Examples
SALARY TOTAL-SALARY
Before Execution
50000 0
After Execution
50000 50000
PRODUCTION TOTAL_PRODUCTION
Before Execution
200 500
After Execution
200 700
When using the ADD statement, care must be taken to ensure that the data field that
receives the result of the calculation is large enough to hold the result. Otherwise, overflow
occurs and the result stored will be incorrect.
57
More than two data fields can be used in the ADD statement.
Example:
In this example, the content of the data TOTAL-QUIZ has been changed, but the contents
of the other three data fields remain unchanged. A numeric literal can be used in the ADD
statement. However, the result of the calculation may not be stored in a numeric literal. The
result of the calculation must always be in a data field in order to be valid.
Example:
ADD 1 TO RECORD-COUNTER.
1. The contents of the first data field are added to the contents of the last data field.
2. The result is always stored in the last data field. All other data fields remain unchanged.
3. Any number of data fields may be listed in an ADD statement. They all will be added to
the last data field.
4. The last data field must be large enough to hold the sum.
5. Numeric literals may be used in add statements. However, the sum must be stored in a
data field. The last item in an ADD statement must be a data field.
6. All data fields that take part in a calculation must be numeric with PIC 9s (may have an S
or V). The data field that holds the result must be either numeric or numeric edited. If it
is numeric, the data field can be used in other additional arithmetic statements.
However, if it is numeric edited, the data field may not be used in other arithmetic
statements. This rule applies not only to the ADD statement, but also to all other
arithmetic statements.
58
SUBTRACT Statements
The SUBTRACT statement subtracts the contents of two or more data fields. It has the
following format
The SUBTRACT statement subtracts the contents of datafield-1 from the contents of
datafield-2 and stores the result of the calculation in datafield-2. The contents of datafield-1
remain unchanged after the statement is executed.
Examples:
DISCOUNT PRICE
Before execution
250 1000
After execution
250 750
EXPENSES INCOME
Before execution
1000 25000
59
After execution
1000 24000
It is possible to subtract the contents of several data fields from that of another data
field.
Example:
The contents of WITH-TAX and MEDICARE remain unchanged, the contents of GROSS-
INCOME was changed.
Example:
1. The contents of the first data field are subtracted from the contents of the last data field.
2. The result is always stored in the last data field. All other data fields remain unchanged.
3. Any number of data fields may be subtracted from the last data field.
MULTIPLY Statement
60
MULTIPLY datafield-1 BY datafield-2.
This statement multiplies the contents of datafield-1 and datafield-2 and stores the
result in datafield-2. The contents of datafield-1 are not changed after the statement is
executed; the contents of datafield-2 are changed.
Examples:
RATE PRICE
Before Execution
10 150
After Execution
10 1500
2. The result is always stored in the second data field. The other data field remains
unchanged.
4. Care must be taken to ensure that the PIC clause of the data field where the result of the
multiplication will be store is large enough to hold the result.
5. As wit ADD and SUBTRACT statements, numeric literals are allowed in the MULTIPLY
statement, but the result of the multiplication must be sorted in a data field.
61
DIVIDE Statement
The DIVIDE statement divides the contents of one data field by the contents of another
data field. There are two methods of writing the DIVIDE statement. The format of the first type
is
The dividend is the number being divided and the divisor is the datafield-2. In a DIVIDE
statement, the result of the division is saved in the dividend data field. Thus, the above DIVIDE
statement saves the result in datafield-1.
In this statement, the dividend is datafield-2 and the divisor is datafield-1. The result of
division is stored in datafield-2.
Example:
1. There are two formats for the DIVIDE statement. DIVIDE BY and DIVIDE INTO.
2. When the DIVIDE BY statement is used, the first data field is the dividend and the second
is the divisor.
62
3. When the DIVIDE INTO statement is used, the first data field is the divisor and the
second is the dividend.
4. Regardless of which format is used, the quotient is always placed in the dividend field.
5. The divisor may be a numeric literal, but he dividend must always be a numeric data
field.
All four arithmetic statements (ADD, SUBTRACT, MULTIPLY and SUBTRACT) can be
written in another form. This form uses the GIVING clause. When the GIVING clause is used in
any of these statements, the result of the calculation is stored in a data field specified by the
GIVING clause. This data field can be either one of the data fields that are part of the
calculation or a new data field. The GIVING clause is added toward the end of these
statements. Since the GIVING clause can be used and not interfere with the contents of the
data fields that take part in an arithmetic operation.
In this format, the contents of datafield-1 and datafield-2 are added and the
result is stored in a different data field called datafield-x.
Example:
In this example, the contents of QUIZ1 and QUIZ2 values did not changed, only
the content of the data field TOTAL-QUIZ was changed.
63
This statement subtracts the contents of datafield-1 from the contents of
datafield-2 and stores the result in datafield-3. More than two data fields may
participate in the calculation.
Examples:
The MULTIPLY statement with the GIVING option has the following format:
Examples:
Or
Examples:
64
DIVIDE TOTAL-GRADE BY UNITS GIVING AVE-GRADE.
Problems with insufficient size of the data field to hold the digits to the right of
the decimal points can be handled by using the ROUNDED clause. This clause rounds
the digits on the right of the decimal point to the number of decimal places that the
receiving data field can hold. Truncation of data is more common with multiplication
and division operations than with addition and subtraction.
The contents of datafield-1 are divided by the contents of datafield-2, the integer
part of the division operations is stored in datafield-3, and the remainder is stored in
datafield-4.
When a data field is not large enough to hold the digits to the left of the decimal
point or digits without any decimal point, the ONSIZE ERROR clause is used. If this
clause is not used in a situation where an insufficient size problem occurs, digits are
truncated from the left, which greatly affects the value stored. The use of the ON SIZE
ERROR option provides a warning signal and does not store the truncated value in the
receiving data field.
The format of the ON SIZE ERROR is
65
ON SIZE ERROR imperative-statement.
Example:
GIVING COMMISSION
ON SIZE ERROR
MOVE 1 TO ERROR-SW.
COMPUTE statement
The word COMPUTE is followed by a blank space, a data field where the result of
the calculation is to be stored, another blank space, an equal sign (=), another blank
space, and then the expression. All arithmetic signs, such as the equal sign, plus sign,
and minus sign, must be preceded and followed by at least one blank space. The
COMPUTE statement makes it possible to perform several arithmetic operations in a
single statement.
Examples:
66
RULES FOR ORDER OF ARITHMETIC OPERATIONS
2. Exponentiation.
3. Multiplication / Division.
4. Addition / Subtraction.
CONDITION STATEMENTS
CONDITION STATEMENTS are special group of COBOL statements that use selection
structures to check for specified conditions that control whether a statement or group of
statements will be executed.
The IF Statement
The IF statement is a kind of condition statement that compares two values. If the result
of the comparison is true, a specified statement or set of statements is executed. The format of
the IF statement is
IF condition
Statement(s).
Example:
IF condition
Statement(s)
ELSE
NEXT SENTENCE
67
Statement(s)
Example:
IF TRANSCODE = “D”
ADD AMOUNT TO BALANCE
ELSE
SUBTRACT AMOUNT FROM BALANCE.
RELATION CONDITIONS
1. IS EQUAL TO (=)
EQUAL TO
68
NOT EQUAL TO
LESS THAN
IF datafield-1 NOT LESS THAN datafield-2
GREATER THAN
NOT GREATER THAN
GREATER THAN OR EQUAL TO
LESS THAN OR EQUAL TO
CLASS CONDITIONS
COBOL can test the class type of a data field to determine whether the contents are
numeric or non numeric. The condition is called CLASS condition.
The general format is
NUMERIC
IF datafield-1 NOT NUMERIC
ALPHABETIC
NOT ALPHABETIC
The numeric test is valuable because it can be used to test the contents of a numeric
data field before using its contents in arithmetic calculations. When numeric data fields
containing non numeric data values are used in arithmetic calculations, errors are generated.
The numeric test prior to using a data field in calculations helps avoid such errors.
SIGN CONDITIONS
The sign of the contents of a numeric data field can be tested using sign condition
statements. A sign condition test can determine whether the contents of a data field are less
than zero, greater than zero, equal to zero, or not equal to zero. This statement has the
following format.
NEGATIVE
NOT NEGATIVE
IF datafield-1 POSITIVE
69
NOT POSITIVE
ZERO
NOT ZERO
Note that NOT POSITIVE is the same as NEGATIVE, and NOT NEGATIVE is the same as
POSITIVE. Similarly, NEGATIVE is the same as LESS THAN ZERO, and POSITIVE, is the
same as EQUAL TO or MORE THAN ZERO.
CONDITION NAMES
In COBOL, conditions can be defined and names assigned. This is done through the
WORKONG-STORAGE SECTION of the DATA DIVISION, using level 88. Defined conditions can be
referred to by name in the PROCEDURE DIVISION.
Example:
05 END-OF-FILE PIC X.
END-OF-FILE is a condition data field in the WORKING-STORAGE SECTION. This data field
can be given condition names with level number 88, and the condition names can be associated
with particular values of END-OF-FILE.
These level 88 entries are the condition names. The first condition name, NO-MORE-
DATA, is true if END-OF-FILE is equal to “Y”, the second condition name, MORE-DATA, is true if
END-OF-FILE is equal to “N”. Once defined, both condition names can be used in the
PROCEDURE DIVISION of a program.
PERFORM PROCESS-DATA
UNTIL NO-MORE-DATA.
LOGICAL OPERATORS
Compound condition statements evaluate more than one condition. These conditions
are joined using logical operators. LOGICAL operators are operators used with logical
conditions, or conditions that can always be evaluated as true or false.
70
AND
IF condition-1 OR condition-2
NOT
Examples:
IF COLLEGE-CODE = “CCMIT”
AND YR-LEVEL = 3
AND SEX-CODE = “M”
ADD 1 TO COUNTER.
The following order of priority enforced in evaluating multiple logical operators in a single
COBOL statement.
It is a statement that transfers program control to specific part of the program. This
statement is one of the most powerful and widely used in COBOL statements. On the
transferring control to the specified paragraph, the paragraph executes all the statements in
that paragraph, and then returns to the statement immediately following the PERFORM
statement.
1. Unconditional – a statement in which the specified action is taken. The format of the
simplest unconditional PERFORM statement is
a. PERFORM statement
Example:
MAIN-RTN.
PERFORM BSIT-RTN
71
PERFORM BSCS-RTN
BSIT-RTN.
MOVE STUDENT-NO TO P-STUDENT-NO.
MOVE STUDENT-NA TO P-STUDENT-NA.
BSCS-RTN.
WRITE OUTREC FROM PRT-AREA AFTER 1 LINE.
BSIT-RTN and BSCS-RTN are two paragraph names that will be executed immediately by
the PERFORM statement. The first PERFORM statement transfers control to paragraph
BSOR-RTN in which the two MOVE statements are executed, then the control returns to
the MAIN-RTN to execute the next unconditional PERFORM statement. Control will
transfer to the paragraph BSCS-RTN to execute the WRITE statement and again will
return to the calling routine to perform the next statement.
This statement will execute the paragraph several times depending on the
integer times specified on the statement.
Examples:
BSIT-RTN.
PERFORM CCMIT-RTN 5 TIMES.
CCMIT-RTN.
MOVE ‘COMPUTER’ TO PRT-AREA-COURSE.
WRITE OUTREC FROM DETAIL AFTER 1 LINE.
CCMIT-RTN will be executed five times. This will result to an output displayed below.
COMPUTER
COMPUTER
COMPUTER
COMPUTER
COMPUTER
72
statement will execute five statements, once each, before returning to the statement
immediately following the PERFORM statement.
Example:
CCMIT-RTN.
PERFORM BSIT-RTN THROUGH BSCS-RTN.
…
BSIT-RTN.
MOVE STUDEN-NO TO PRT-STUDNO.
MOVE STUDEN-NA TO PRT-STUDNA.
MOVE COURSE TO PRT-COUR.
MOVE YEAR TO PRT-YR.
BSCS-RTN.
WRITE OUTREC FROM DETAILS.
ADD 1 TO TOTAL.
This statement will perform the two paragraphs immediately, before returning to
the next statement following the PERFORM statement.
CCMIT-RTN.
PERFORM BSIT-RTN THRU BSIT-RTN-END.
BSIT-RTN.
MOVE STUDEN-NO TO PRT-STUDNO.
MOVE STUDEN-NA TO PRT-STUDNA.
MOVE COURSE TO PRT-COUR.
MOVE YEAR TO PRT-YR.
WRITE OUTREC FROM DETAILS.
ADD 1 TO TOTAL.
BSIT-RTN-END.
THRU in some old compilers can be used to replace the reserved word
THROUGH.
2. Conditional – a statement in which the specified action may or may not be taken
depending on the result of the stated condition.
The two characteristics of this statement are,
1. It must make a comparison between two values, the result of which must be true or
false.
2. It must contain an action. Whether or not this action is taken is dependent upon the
results of the comparison.
73
a. PERFORM paragraph-name-1 UNTIL condition.
ENTRY
STATEMENTS
FALSE
TRUE
EXIT
When the PERFORM statement is used with a conditional clause, the condition is
tested before the specified paragraph is executed. If the condition is true, the paragraph
is not executed.
Example:
MAIN-RTN.
PERFORM BSCS-RTN THRU BSCS-RTN-END.
PERFORM BSIT-RTN UNTIL EOFSW=1.
STOP RUN.
BSCS-RTN.
OPEN INPUT INFILE, OUTPUT OUTFILE.
74
READ INFILE AT END MOVE 1 TO EOFSW GO TO BSCS-
RTN-END.
PERFORM HEADING-RTN.
BSCS-RTN-END.
BSIT-RTN.
READ INFILE AT END MOVE 1 TO EOFSW.
MOVE STUDEN-NO TO PRT-STUDNO.
MOVE STUDEN-NA TO PRT-STUDNA.
WRITE OUTREC FROM DETAILS AFTER 1.
READ INFILE AT END MOVE 1 TO EOFSW.
The two PERFORM statements will be executed immediately as part of the MAIN-
RTN. First the unconditional perform will transfer its control to the BSCS-RTN through
BSCS-RTN-END. Next the second unconditional will be executed. The condition
after the reserved word UNTIL will be tested. If the EOFSW is false, then the specified
paragraph in the PERFORM will be executed. Otherwise if it is true, then the next
statement will be performed, which is STOP RUN. The format below is also a valid
statement.
…
PERFORM BSIT-RTN THROUGH BSIT-RTN-END UNTIL
EOFSW = 1.
BSIT-RTN.
READ INFILE AT END MOVE 1 TO EOFSW.
MOVE STUDEN-NO TO PRT-STUDNO.
MOVE STUDEN-NA TO PRT-STUDNA.
WRITE OUTREC FROM DETAILS AFTER 1.
READ INFILE AT END MOVE 1 TO EOFSW.
BSIT-RTN-END.
This statement is used in TABLE handling. TABLE is a sequence of data values grouped
together with a common name. Each data item in the table is referred to as an
ELEMENT. The elements in the table are accessed using common table name and a
SUBSCRIPT, which references a specific table element. A subscript is a constant or a data
field used to access a specific element of a table. The syntax used to access the
individual element of a table is
Table-name (subscript)
75
The table-name is followed by at least one blank space, a left parenthesis, the
subscript, and a right parenthesis.
Tables are defined using OCCURS clause. This clause appears with the data-name
in the FILE SECTION or WORKING-STORAGE SECTION of the DATA DIVISION.
The syntax of the OCCURS clause is
The data-field is the name of the table. The integer values define the size, or the
number of elements in the table. The integer indicates the range of the subscripts that
can be used with this table and must be greater than zero.
1. The integer value in the OCCURS clause indicates the number of elements in the table. It
cannot be zero. The subscript range is from one through a given value.
2. The PIC clause must appear at the elementary data-field level, although the OCCURS
clause can appear either at the elementary or group level.
3. The subscript must follow the table name and be placed in parentheses. There must be
one or more spaces between the table name and the left parenthesis.
4. The subscript must be within the range of the table.
5. The subscript must be and integer. It can be either a constant or a numeric data-field.
6. If a data-field is used as a subscript, the data-field must be defined in the WORKING-
STORAGE SECTION or FILE SECTION as an integer with PIC 9s.
76
ENTRY
MOVE INITIAL
VALUE TO
DATA-FIELD
INCREASE
EXECUTE DATA-FIELD
SPECIFIED BY
PARAGRAPH INCREMENT-
VALUE
EXIT FROM
PERFORM
STATEMENT EXIT
Example
PROCEDURE DIVISION.
CCMIT-RTN.
READ STUDENT AT END MOVE 1 TO EOFSW.
PERFORM BSIT-RTN VARYING I FROM 1 BY 1 UNTIL 1 > 5.
COMPUTE AVE = TQ / 5.
MOVE AVE TO PRT-AVE.
WRITE OUTREC FROM DETAILS AFTER 1 LINE.
BSIT-RTN.
MOVE QUIZ (I) TO PRT-QUIZ (I).
ADD QUIZ (I) TO TQ.
Suppose the set of 5 quizzes are stored from the input file student.
DATA DIVISION .
FILE SECTION .
FD STUDENT
LABEL RECORD IS STANDARD
DATA RECORD IS INREC .
01 QUIZ OCCURS 5 TIMES PIC 99
77
03 PRT QUIZ PIC 99 .
03 FILLER PIC X 5 .
The PERFORM statement will execute. Since this is a conditional perform statement with
a VARYING option, a data field will be first initialized and be compared with the limit value. If
the condition is false, specified paragraph will be executed and the control will return to the
same calling statement, with the data −field being incremented as specified in the same
statement, and again, to be compared with the limit value repeatedly. Until the final value
exceeds the limit value for the PERFORM statement to become true, then the control will
proceed to the next statement, thus terminating the PERFORM statement.
The table of quizzes is a one-level table and is used to accumulate total quiz. This is one
of the several uses of the table in many of the programming languages like COBOL. In our
example I is the only subscript to reference the table of QUIZ, which is a one-level table. I is
being initialized and compared, incremented and compared until I exceeds the limit value which
is 5.
The diagram below illustrates graphically how the PERFORM VARYING AFTER option
works.
MOVE INITIAL
VALUE TO
DATA-FIELD-1
MOVE INITIAL
VALUE TO
DATA-FIELD-2
N N EXECUTE ADD
SPECIFIED INCREMENT
PARAGRAPH VALUE TO
Y Y DATA-FIELD-2
This statement is used to process a Two-level table with One-level-table we used only one
subscript and with Two-level table, there must be two subscript that represents the total
78
number of two-level table. The PERFORM statement with the VARYING AFTER option is used in
COBOL to allow automatic control over two subscript. The first subscript is the major subscript
that represents the total number of rows and the second subscript is the minor subscript that
represents the total number of columns.
Example:
CCMIT
DATA DIVISION:
FILE SECTION
FD STUDENT
LABEL RECORD IS STANDARD
DATA RECORD IS CCMIT.
01 CMIT .
02 YEAR OCCURS 4 TIMES .
03 COURSE 2 TIMES PIC 999
Suppose one of the requirements is to print the table with the total no. of students per year.
79
SOPHOMORE 200 200
JUNIOR 300 400
SENIOR 400 200
WORKING-STORAGE SECTION.
1 I PIC 9 VALUE IS 0.
1 JPIC 9 VALUE IS 0.
1 TOTAL/YEAR PIC 9999 OCCURS 4 TIMES.
1 DETAILS
02 FILLER PIC X(5).
02 PRT-YEAR PIC X(9).
02 P-TAB OCCURS 2 TIMES.
03 FILLER PIC X(5).
03 P-CTR PIC 999.
80
WRITE OUTREC FROM DETAILS AFTER 1.
MOVE2-RT.
MOVE COURSE (I, J) TO PRT-TAB (J)
FINISH-RTN.
CLOSE STUDENT, OUTFILE.
The statement PERFORM VARYING AFTER option is a nested iteration control structure.
The first to be executed is the first VARYING. It initializes the data-field-l and compared to the
limit value after the first condition. If it false, the data-field-2 after the reserved word AFTER will
be initialized and compared to the limit value after the second condition. If it false, then the
specified paragraph will be executed. Data-field-2 will vary faster than Data-field-1 depending
on its increment value and Data-field-2 will be tested after the second condition. If it is false,
data-field-2 will be repeatedly incremented until it exceeds the limit value. Once the second
condition becomes true, then the Data-field-1 will be now incremented depending on its
increment value and to be compared against the first limit value. If it false, the Data-field-2 will
be again initialized and compared to the second limit value. If it false, the Data-field-2 will be
again initialized and compared to the second limit value. If it false, then the specified
paragraph will be executed. Execution of this statement will only be terminated when Data-
field-1 exceeds the limit value in the first condition.
Required:
For each record, print area code, salesman number, sales man name and amount/ For a
break in are code, print the total number of salesman and total accumulated amount for each
area.
OUTPUT LAYOUT:
81
22
Sample Program
82
02 SNO PIC 9(5).
02 SNA PIC X(25).
02 AMT PIC 9(5)V99.
FD OUTFILE
LABEL RECORD IS OMITTED
DATA RECORD IS OUTREC.
01 OUTREC.
02 FILLER PIC X(80).
WORK ING-STORAGE SECTION.
01 SVAC PIC X VALUE SPACES.
01 TNS PIC 9(4) VALUE ZERO.
01 TA PIC 9(7)V99 VALUE ZERO.
01 EOFSW PIC 9 VALUE ZERO.
01 HEAD-1.
02 FILLER PIC X (29) VALUE SPACES.
02 FILLER PIC X(22) VALUE ‘SAN MIGUEL
CORPORATION’.
02 FILLER PIC X (29) VALUE SPACES.
01 HEAD-2.
02 FILLER PIC X (31) VALUE SPACES.
02 FILLER PIC X (17) VALUE, STA.MESA,
MANILA’.
02 FILLER PIC X(32) VALUE SACES.
01 SUB-1.
02 FILLER PIC X(34) VALUE SPACES.
02 FILLER PIC X (12) VALUE ‘SALES
REPORT’.
02 FILLER PIC X(34) VALUE SPACES.
01 SUB-2.
02 FILLER PIC X(7) VALUE SPACES.
02 FILLER PIC X(4) VALUE ‘AREA’.
02 FILLER PIC X(7) VALUE SPACES.
02 FILLER PIC X(8) VALUE ‘SALESMAN’.
02 FILLER PIC X(16) VALUE SPACES.
02 FILLER PIC X(8) VALUE ‘SALESMAN’.
02 FILLER PIC X(15) VALUE SPACES.
02 FILLER PIC X(6) VALUE ‘AMOUNT’.
02 FILLER PIC X(9) VALUE SPACES.
01 SUB-3.
02 FILLER PIC X(7) VALUE SPACES.
02 FILLER PIC X(4) VALUE ‘AREA’.
02 FILLER PIC X(8) VALUE SPACES.
83
02 FILLER PIC X(6) VALUE ‘NUMBERS’.
02 FILLER PIC X(18) VALUE SPACES.
02 FILLER PIC X(4) VALUE ‘NAME’.
02 FILLER PIC X(33) VALUE SPACES.
01 DETALYE.
02 FILER PIC X(9) VALUE SPACES.
02 P-AC PIC X.
02 FILLER PIC X (10) VALUE SPACES.
02 P-SNO PIC 9(5).
02 FILLER PIC X (8) VALUE SPACES.
02 P-SNA PIC X (25).
02 P-MAT PIC 99,999.99.
02 FILLER PIC X(9) VALUE SPACES.
01 TOTAL-1.
02 FILLER PIC X (7) VALUE SPACES.
02 FILLER PIC X (9) VALUE ‘TOTAL NO.’.
02 FILLER PIC X (13) VALUE ‘OF SALESMEN:’.
02 FILLER PIC X (9) VALUE SPACES.
02 P-TNS PIC 9,999.
02 FILLER PIC X (38) VALUE SPACES.
01 TOTAL-2.
02 FILLER PIC X (7) VALUE SPACES.
02 FILLER PIC X (6) VALUE ‘TOTAL’.
02 FILLER PIC X (11) VALUE
‘ACCUMULATED’.
02 FILLER PIC X (7) VALUE ‘AMOUNT:’.
02 FILLER PIC X(4) VALUE ‘ PHP’.
02 P-TA PIC 9,999,999.99.
02 FILLER PIC X (33) VALUE SPACES.
SCRE EN SECTION.
01 SCRE.
02 BLANK SCREEN.
PROC EDURE DIVISION.
MAIN -RTN.
PERFORM INIT-RTN THRU INIT-RTN-END.
PERFORM PROCESS-RTN UNTIL EOFSW = 1.
PERFORM FINISH-RTN.
STOP RUN.
INIT -RTN.
OPEN INPUT INFILE, OUTPUT OUTFILE.
READ INFILE AT END PERFORM END-RTN
GO TO INIT-RTN-END.
84
MOVE AC TO SVAC.
PERFORM HEADING-RTN.
INIT -RTN-END.
END- RTN.
MOVE 1 TO EOFSW.
DISPLAY ‘EMPTY FILE’ LINE 3 COLUMN 20.
HEAD ING-RTN.
WRITE OUTREC FROM HEAD-1 AFTER PAGE.
WRITE OUTREC FROM HEAD-2 AFTER
ADVANCING 1 LINE.
WRITE OUTREC FROM SUB-1 AFTER 3.
WRITE OUTREC FROM SUB-2 AFTER 2.
WRITE OUTREC FROM SUB-3 AFTER 1.
PROC ESS-RTN.
DISPLAY SCRE.
IF SVAC NOT = AC PERFORM AC-BREAK-RTN ELSE
NEXT SENTENCE.
MOVE SVAC TO P-AC.
MOVE SNO TO P-SNO.
MOVE SNA TO P-SNA.
MOVE AMT TO P-AMT.
WRITE OUTREC FROM DETALYE AFTER 1.
ADD 1 TO TNS.
ADD AMT TO TA.
READ INFILE AT END MOVE 1 TO EOFSW
PERFORM AC-BREAK-RTN.
AC-B REAK-RTN.
MOVE TNS TO P-TNS.
WRITE OUTREC FROM TOTAL-1 AFTER 3.
MOVE TA TO P-TA.
WRITE OUTREC FROM TOTAL-1 AFTER 1.
MOVE 0 TO TNS, TA.
MOVE AC TO SVAC.
FIN ISH-RTN.
CLOSE INFILE, OUTFILE.
DISPLAY ‘TAPOS NA’ LINE 6 COLUMN 20.
IF YOU HAVE ANY QUESTION. PLS. ASK YOUR TEACCHER ABOUT THE PROGRAM.
85
IF YOU HAVE NO QUESTION, PLS. PASS THIS PORTION TO YOUR TEACHER.
WE CAN PROCEED TO THE NEXT PROGRAM MA’M
_________________________
First, the DOSBOX 0.72 must be loaded to your windows ( check if your computer has
the installation of the said software).
Click the DOSBOX icon and click the DOSBOX
You will be prompted by the following
Z:\mount c: c:\
Z:\ c:
C:\> cd COBOL
86
C:\COBOL\ LINK
C:\ SAMPLE1.EXE
Problem Solving
A. This file will contain records that does not contain a multi-dimensional table
Input File: Studentfile
Input Format:
87
Requirements:
1. The records of the students are arranged sequentially according to the year code and from
every year, the course codes are arranged.
Year Year level
1 “Freshman”
2 “Sophomore”
3 “Junior”
4 “Senior”
Course Codes are “BSCS” and “BSIT”
2. Count the total no. of BSCS and total no. of BSIT foe every year level. (Two-dime table)
3. Count the total no. of students per year and count also the total no. of students per course
(One-dime table)
4. The totals will be printed at the end of file.
Note: this module will show you only important parts of the program. You are required to
complete the COBOL program.
ENVIRONMENT DIVISION.
FILE-CONTROL.
SELECT INFILE ASSIGN TO “BILANG”.
SELECT OUTFILE ASSIGN TO “DAMI”.
DATA DIVISION.
FILE SECTION.
FD INFLE
LABEL RECORD IS STANDARD
DATA RECORD IS DAGDAG.
01 DAGDAG
02 YR PIC 9.
02 CC PIC X (5).
02 SNO PIC X (10).
02 SNA PIC X (25).
FD OUTFILE
LABEL RECORD IS OMITTED
DATA RECORD IS BAWAS.
01 BAWAS.
02 FLLER PIC X (80).
WORKING-STORAGE SECTION.
01 OFSW PIC 9 VALUE 0.
02 MESA.
88
02 TAON OCCURS 4 TIMES
03 KURSO OCCURS 2 TIMES.
04 KURSO PIC 999 VALUE 0.
01 SUB1 PIC 9 VALUE 0.
01 SUB2 PIC 9 VALUE 0.
01 TS-YEAR CCURS 2 TIMES.
02 TOT-YR PIC 9(4) VALUE 0.
01 TS-COUR OCCURS 2 TIMES.
02 TOT-CR PIC 9(4) VALYE 0
01 DETALYE
(Same with previous program)
01 TOTAL.
02 FILLER….
02 FILLER … VALUE ‘TOTAL’.
02 FILLER …
02 P-TOTAL OCCURS 2.
03 P-TOTAL OCCURS 2.0
03 FILLER …..
PROCEDURE DIVISION.
MAIN-RTN.
PERFORM INIT-TN THRU INIT-RTN-END.
PERFORM PROCESS-RTN UNTIL EOFSW = 1.
PERFORM FINISH-RTN.
STOP RUN.
INIT-RTN.
OPEN INPUT INFILE, OUTPUT OUTFILE.
READ INFILE AT END PERFORM END-RTN GO TO INIT-RTN-END.
PERFORM HEADING-RTN.
INIT-RTN-END.
PROCESS-RTN.
ADD 1 TO KURS ( YR,CC ).
IF CC == ‘BSCS’ ADD 1 TO TOT-COUR(1) ELSE ADD 1 TO TOT-COUR(2).
ADD 1 TO TOT-YR ( YR).
…
FINISH-RTN.
PERFORM MOVE1-RTN VARYING SUB1 FROM 1 BY 1 UNTIL SUB1>4.
PERFORM TOTAL-COUR-RTN VARYING SUB2 FROM 1 BY 1
UNTIL SUB2 >2.
…
CLOSE INFILE, OUTFILE.
89
MOVE1-RTN.
…
*** Assignment:
Complete the given program above.
Submit the hardcopy of this program.
Submit the hardcopy of the input file.
Submit the hardcopy of the output file.
Requirements:
Note: the file is sorted in ascending account number. There are two possible values of
transaction code, ‘D’ for ‘Deposit’ and ‘W’ for withdrawal.’
For a break in account number, print account number, account name and balance. At
end of file, print the Total Number of Records printed and Total Accumulates Balance of all
records in the file. (Balance =Deposit – Withdrawal)
Output Layout
90
China Trust Bank
Makati Avenue
Makati City
2 spaces
Account’s Report
I space
Account Account Balance
Number Name
X(10) X(25) ZZZ,ZZZ,ZZ9.99
EXERCISES
91
Write PERFORM… UNTIL statement that will read the input records and will prinit the required
output
92
displacement value. The displacement value refers to the number of bytes a table
element is from the start of the table. Knowing the starting address of a bytes a table
displacement of a table element, the computer can calculate the location of the element
quicker than is possible with subscripts.
Indexing is especially useful when a program must search a large table. To use
indexing, an INDEXED BY clause is added to the definition of a table as follows:
Data-field-2 is the name of the index. This data field is completely defined by the
phrase INDEXED BY. This data field must not appear in the WORKING-STORAGE SECTION.
The index name is used in the same manner as a subscript when referring to table
elements.
SET statement is used to search a table. Searching is done through indexing. This statement is
used to assign a value to an index data-field. This statement is similar in function to the MOVE,
ADD, and SUBTRACTS statements. However, MOVE, ADD and SUBTRACT may not be used with
indexes.
93
The USAGE CLAUSE
We can specify that the usage of data-item is INDEX, so that the item can be used in
conjunction with SET, SEARCH, or PERFORM statements.
EXAMPLE:
DATA DIVISION.
FILE SECTION
FD INFILE
LABEL RECORD IS STANDARD
DATA RECORD IS EXAM-REC.
01 EXAM-REC.
02 STUD-NAME PIC X (20).
02 EXAM-SCORES.
10 SCORES-IN OCCURS 8 TIMES PIC 9 (3) V99.
WORKING-STORAGE SECTION.
01 WORK-AREAS.
04 EOFSW PIC 9 VALUE 0.
88 EOF VALUE IS 1.
05 M USAGE IS INDEX.
02 EXAM-TABLE.
06 STUDENT-DATA OCCURS 5 TIMES INDEXED BY S.
10 STUD-NAME PIC X (20).
10 EXAM-SCORES.
15 SCORE OCCURS 8 TIMES INDEXED BY Q
PIC 9 (3) V99.
PROCEDURE DIVISION.
MAIN-RTN.
OPEN INPUT INFILE, OUTPUT OUTFILE.
94
PERFORM READ-EXAM-REC.
PERFORM SCORE-RECORD VARYING S FROM1 BY 1 UNTIL
S > 5 OR EOF.
.SET S DOWN BY 1.
PERFORM CHECK-SCORES-AND-PRINT VARYING S FROM 1
BY I UNTIL S > M.
DISPLAY ‘END OF FILE’.
CLOSE INFILE, OUTFILE.
STOP RUN.
CHECK-SCORES-AND-PRINT.
SET Q TO 1.
SEARCH SCORE
WHEN SCORE (S, Q) = 100.00 PERFORM PRINT-SCORES
WHEN SCORE (S, Q) < 50.0 PERFORM 1 BY 1 UNTIL Q
PRINT-SCORES.
PERFORM MOVE SCORES VARYING Q FROM 1 BY 1 UNTIL Q
8.
MOVE STUD-NAME OF EXAM-TABLE ( S ) TO
STUD-NAME OF REPORT-LN.
WRITE PRT-REC FROM REPORT-LN AFTER 2.
MOVE-SCORES.
SET RTO Q.
MOVE SCORE ( S, Q ) TO SCORE-OUT ( R ).
READ-EXAM-REC.
READ INFILE AT END MOVE 1YO EOFSW.
[ { data-name-2 condition-name-2
{ IS EQUAL TO }
IS =
95
NEXT SENTENCE
Format 2 Is used with sorted tables, that is, table for which OCCURS clause contains a KEY in
addition to the INDEXED BY option. The search may be a binary search or any method included
in a particular compiler, however, as far as the programmer is concerned, only the instructions
included in format 2 are required.
Notice that in format 2 only one WHEN option is available, but multiple AND conditions
are allowed. Thus, all the conditions must be true in order for the search to be satisfied. In
contrast, whenever multiple WHEN statements are used in Format 1, any one of these
conditions being true constitutes a sufficient reason for search termination.
01 DATA-TABLE.
02 NAME-NUMBER OCCURS 400 TIMES ASCENDING KEY
IS NAME INDEXED BY WHICH-ONE.
03 NAME PIC X (16).
03 EMPL-NO PIC 9 (4).
PROCEDURE DIVISION.
MAIN-RTN.
…
SEARCH ALL NAME-NUMBER AT END PERFORM
CAN’T – FIND
WHEN NAME ( WHICH-ONE) TO EDIT-NUMBER.
Notice the ASCENDING KEY statement, which indicates that the item defined by the OCCURS
clause is sorted in ascending sequence. The INDEXED BY WHICH-ONE clause defines WHICH-
ONE as an index for NAME_NUMBER. It is a numeric field, normally binary whose length is
defined y the computer.
96
The instruction SEARCH ALL NAME-NUMBER indicates that all the entries in the NAME-
NUMBER table should be searched. Recall that in the DATA DIVISION the OCCURS clause defined
ASCENDING KEY IS NAME; therefore, the search is conducted with respect to the NAMEN field.
If no match is found, the AT END clause is executed. As the table is searched, the procedure is to
vary WHICH-ONE and to compare the resulting NMAE (WHICH-ONE) to EMPL-NAME. If the two
match, the MOVE statement that follows the WHEN is executed next and the search terminates.
If no match is found, WHICH-ONE is changed to a new value and the procedure is repeated until
the entire table has been searched.
EXERCISE
1. Write a COBOL program segment to perform a search in a sorted table called TABLE,
searching fore an entry that matches THIS-RECORD. If a match is found the program goes to the
paragraph MATCHED, otherwise, it goes to the paragraph NO-MATCH. Use I to hold the position
of the matching table entry, if there is a match. Assume the following data description.
2. How does COBOL differentiate between searching sorted and unsorted tables?
3. What is the difference between an index and subscript in COBOL?
4. What tasks are performed by the following statements?
SET ENTRY-COUNTER DOWN by 3
SET ENTRY-COUNTER UP BY 3
SET ENTRY-COUNTER TO 3
5. What is the difference between SEARCH and the SEARCH ALL statement? When would you
use one and not the other?
PROGRAMMING
Suppose a payroll report must be produced that contains the following data Employee
Name, Employee Number, Job Category and the Amount of Pay. The input data come from a file
having the following data: Employee Name, Employee Number, and Job Category.
97
3 2600.00
4 4000.00
5 5000.00
As the input data are read, the employee’s pay should be taken from the pay table,
based on the job category. If an employee’s job category exceeds 5, this record should be
written out with an error message.
APPENDUM
DISPLAY statement is a COBOL statement that is used for printing a low volume of output.
Format:
DISPLAY identifier-1 …
literal-1
DISPLAY identifier-1… LINE integer-value COLUMN integer-value.
literal-1
DISPLAY ( line-no. , column-no) identifier-1 … .
Literal-1
Examples:
DISPLAY “Average Grade is “ .
DISPLAY AVERAGE .
DISPLAY “Average Grade is: “, AVERAGE .
ACCEPT statement is a COBOL statement that request actual data from the keyboard.
Format:
ACCEPT identifier
ACCEPT identifier LINE integer-value COLUMN integer-value.
ACCEPT ( row, column ) literal-1
98
Example:
ACCEPT NAME.
ACCEPT NAME LINE 7 COLUMN 11.
ACCEPT (7, 11 ) NAME.
IDENTIFICATION DIVISION.
PROGRAM-ID. ACPTDSP1.
ENVIRONMENT DIVISION.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 NAME PIC X(25).
01 MIDGRD PIC 9V99.
01 FNGRD PIC 9V99.
01 AVE PIC 9.99.
01 ANS PIC X.
SCREEN SECTION.
01 CLRSCR.
05 BLANK SCREEN.
PROCEDURE DIVISION.
MAIN-RTN.
DISPLAY CLRSCR.
PERFORM PROCESS-RTN THRU PROCESS-END
UNTIL ANS = ‘N’ OR ANS = ‘n’.
STOP RUN.
PROCESS-RTN.
DISPLAY (5, 15) “Enter Name:”.
ACCEPT (5, 30) NAME.
DISPLAY (7, 15) “Enter Midterm Grade: “.
ACCEPT (7,40) MIDGRD
DISPLAY (9, 15) “Enter Final Grade:”.
ACCEPT (9, 40) FINGRD.
COMPUTE AVE = (MIDGRID + FINGRD)/2.
DISPLAY (11, 15) “Average Grade is: “ AVE.
DISPLAYS (15, 15) “ENTER ANOTHER [Y/N]? “.
99
ACCEPT ANS.
PROCESS-END.
Sample Run 1: Sample Run 2:
Enter Name: Rainah Casandra A. Nayre Enter Name: Mark Jezekiah A. Nayre
Enter Midterm Grade: 1.75 Enter Midterm Grade: 1.75
Enter Final Grade : 1.25 Enter Final Grade: 2.25
Average Grade is: 1.50 Average Grade is: 2.00
IDENTIFICATION DIVISION.
PROGRAM-ID. ACPTDSP1.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT GREDFILE ASSIGN TO ‘C:\COBOL\GRDFILE.TXT’.
DATA DIVISION.
FILE SECTION.
FD GRDFILE.
01 GRDREC.
05 FILLERPIC X (80).
WORKING-STORAGE SECTION.
* INPUT DATA USING *
* ACCEPT & DISPLAY *
01 NAME PIC X (25)
01 MIDGRD PIC 9V99.
01 FINGRD PIC 9V99.
01 AVE PIC 9V99.
01 ANS PIC X.
* OUTFILE *
01 HDG.
05 FILLER PIC X(32) VALUE SPACES
05 FILLER PIC X(25) VALUE “STUDENT GRADE”.
05 FILLER PIC X(33) VALUE SPACES.
01 COLHDG.
05 FILLER PIC X (14) VALUE SPACES.
05 FILLER PIC X (12) VALUE “STUDENT GRADE”.
05 FILLER PIC X(28) VALUE SPACES.
05 FILLER PIC X(12) VALUE “FINAL GRADE”.
100
01 GRDDTA
05 FILLER PIC X(32) VALUE SPACES.
05 NAME-OUT PIC X (25).
05 FILLER PIC X (20) VALUE SPACES.
05 AVE-OUT PIC 9.99.
SCREEN SECTION.
01 CLRSCR.
05 BLANK SCREEN.
PROCEDURE DIVISION.
MAIN-RTN.
DISPLAY CLRSCR.
OPEN OUTPUT GRDFILE.
WRITE GRDREC FROM HDG AFTER 1.
WRITE GRDREC FROM COLHDG AFTER 1.
PERFORM PROCESS-RTN TRHRU PROCESS-END
UNTIL ANS = ‘N’ OR ANS = ‘n’.
CLOSE GRDFILE.
STOP RUN.
PROCESS-RTN.
DISPLAY (5,15) “Enter Name: “.
ACCEPT (5,30) NAME.
DISPLAY (7,15) “ Enter Midterm Grade: “.
ACCEPT (7,40) MIDGRD
DISPLAY (9,15) “Enter Final Grade: “.
ACCEPT (9,40) FINGRD.
COMPUTE AVE = (MIDGRD = FINGRD )/2.
MOVE NAME TO NAME-OUT.
MOVE AVE TO AVE-OUT.
DISPLAY (11, 15) “Average Grade is: “ AVE_OUT.
WRITE GRDREC FROM GRDDATA AFTER 2.
DISPLAY (15,15) “ ENTER ANOTHER [Y/N]? “.
ACCEPT ANS.
PROCESS-END.
101
Enter Midterm Grade: 3.00 Enter Midterm Grade: 2.25
Enter Final Grade : 3.00 Enter Final Grade : 2.75
Average Grade is: 3.00 Average Grade is: 2.50
ENTER ANOTHER [Y/N]? Y ENTER ANOTHER [Y/N]? Y
Program Exercise:
REQUIRED:
Based on the input data, compute and display the total gross salary and the total
deductions for each employee. Compute also for the total net pay and store it in
102
an output file based on the given layout. Output also the Total Number of
Employees and Accumulated Salaries of all the employees.
PAYROLL REPORT
EMPLOYEE EMPLOYEE NET
NUMBER NAME PAY
X(5) X(25) ZZ,999.99
Note: If there are errors, correct the errors first before you proceed to Step #2.
103
c: \cobol> LINK filename. obj Enter key
OBJ file: Enter key
MAP file: Enter key
LIBRARIES AND PATHS: REALDOS Enter key
DEFINITION file: Enter key
104