Sie sind auf Seite 1von 104

LESSON 1

INTRODUCTION

Objectives:

At the end of the lesson, the students must be able to:

1. Know the history of COBOL program;


2. Know the features of COBOL language;
3. Understand the COBOL coding form and template.

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.

History and specification

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:

 William Selden and Gertrude Tierney of IBM

 Howard Bromberg and Howard Discount of RCA

 Vernon Reeves and Jean E. Sammet of Sylvania Electric Products


This subcommittee completed the specifications for COBOL in December 1959. The
specifications were to a great extent inspired by the FLOW-MATIC language invented by Grace
Hopper, commonly referred to as “the mother of the COBOL language”, and the IBM COMTRAN
language invented by Bob Bemer. The name COBOL was decided upon at a meeting of the
committee held on September 18 1959. The first compilers for COBOL were subsequently
implemented during the year 1960( the group that developed the first version of COBOL is
called CODASYL – Conference on Data Systems and Language, and the compiler is also called

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.

History of COBOL standards

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

COBOL provides an update-in-place syntax, for example


ADD YEARS TO AGE.
The equivalent construct in many procedural languages would be
Age= Age + Years
This syntax is similar to the compound assignment operator later adopted by C:
Age+= Years

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

An example of the “Hello, world” program in COBOL:

IDENTIFICATION DIVISION.
PROGRAM-ID. HELLO-WORLD.
PROCEDURE DIVISION.
MAIN.
DISPLAY ‘Hello, world.’.
STOP RUN.

Characteristics of COBOL applications


 Many COBOL applications consist of more than 1,000,000 lines of code- with 6,000,000+
line applications not considered unusually large in many shops.
 COBOL applications are also very long-lived. The huge investment in creating a software
application consisting of some millions of lines of COBOL code means that the
application cannot simply be discarded when some new programming language or
technology appears. As a consequence business applications between 10 and 30 years-
old are common. This accounts for the predominance of COBOL programs in the year
2000 problem (12,000,000 COBOL applications vs 375,000 C and C++ applications in the
US alone – [Capers Jones]). Twenty years ago when programmers were writing these
applications they just didn’t anticipate that they would last into millennium.

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.

Characteristics that contribute to COBOL’s success


 COBOL is self-documenting
One of the design goals for COBOL was to make it possible for non-programmers
such as supervisors, managers and users, to read and understand COBOL code. As a
result, COBOL contains such English-like structural elements as verbs, clauses,
sentences, sections and divisions. As it happens, this design goal was not realized.
Managers and users nowadays do not read COBOL programs. Computer programs
are just too complex for most laymen to understand them, however familiar the
syntactic elements. But the design goal and its effect on COBOL syntax has had one
important side-effect. It has made COBOL the most readable, understandable and
self-documenting programming language in use today. It has also made it the most
verbose.

It is easy for programmers unused to the business programming paradigm, where


programming with a view to ease of maintenance id very important, to dismiss the
advantage tat COBOL’s readability imparts. Not only does this readability generally
assist the maintenance process but the older a program gets the more valuable this
readability becomes.

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-

 User Defined Functions


 Object Orientation
 National Characters – Unicode
 Multiple Currency Symbols
 Cultural Adaptability (Locales)
 Dynamic Memory Allocation (pointers)
 Data Validation Using New VALIDATE Verb
 Binary and Floating Point Data Types
 User Defined Data Types

 COBOL is non-proprietary (portable)


The COBOL standard does not belong to any particular vendor. The vendor
independent ANSI COBOL committee legislates formal, non-vendor-specific syntax
and semantic language standards. COBOL has been ported to virtually every
hardware platform – from every favor of Windows, to every falser of UNIX, to
AS/400, VSE, OS/2, DOS, VMS, Unisys, DG, VM, and MVS.
 COBOL is Maintainable
COBOL has a 30 year proven track record for application maintenance, enhancement
and production support at the enterprise level. Early indications form the year 2000
problem are that COBOL applications were actually cheaper to fix than applications
written in more recent languages.[Capers Jones] [Kappleman] One reason for the
maintainability of COBOL programs has been given above – the readability of COBOL
code. Another reason is COBOL’s rigid hierarchical structure. In COBOL programs all
external references, such as to devices, files, command sequences, collating
sequences, the currency symbol and the decimal point symbol, are defined in the
Environment Division.

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.

IV. OVERALL STRUCTURE OF COBOL PROGRAMS (ELEMENTS)

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.

V. OVERVIEW OF THE FOUR DIVISIONS

Every COBOL program consists of for separate divisions, each with specific functions:

A. IDENTIFICATION DIVISION – it identifies the program to the computer. It also


provides the basic documentation about the program, its author, etc.
B. ENVIRONMENT DIVISION – it describes the specific computer equipment and device that
will be used by the program.
C. DATA DIVISION – it describes the input and output formats to be used by the program. It
also defines the records to be needed, the constants and variables it needs for the
processing of data.
D. PROCEDURE DIVISION – it contains the program statements needed for processing of
data.

VI. HIERARCHICAL STRUCTURES OF A COBOL PROGRAM

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:

Divisions Sections Paragraphs

IDENTIFICATION PROGRAM –ID


AUTHOR
INSTALLATION
DATE-WRITTEN
DATE-COMPILED
SECURITY

ENVIRONMENT CONFIGURATION SOURCE-COMPUTER


OBJECT-COMPUTER
SPECIAL-NAMES

INPUT-OUTPUT FILE-CONTROL

DATA FILE
WORKING-STORAGE

PROCEDURE Sections and paragraphs have user-defined names

VII. USE OF COBOL CODING FORM

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.

A. COLUMNS 1-6 (SEQUENCE AREA)


Columns 1 to 6 represent the sequence area. Every character represents one column.
Column 1-3 are for page number and columns 4-6 is for line number. The early part of COBOL
writing programs is done on the paper. If the paper is misplaced, then there would be difficulty
in locating its part. It is for this reason that it opted to create a column for the line and page.
Typing page and line number today is optional in writing COBOL programs since the days when
programs were punched on cards are over.
Fig. 1 Sample of Sequence Area

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.

Fig. 2 Sample of Indicator


Area

C. COLUMNS 8-72 (PROGRAM AREA)

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.

VII. TEMPLATE OF COBOL PROGRAM.

10
Fig. 5 Sample of COBOL Template

11
Review Questions

Name: ________________________________ Date: _____________


Year and Section: _______________________ Rating: ___________

1. Be able to compare the following programs, C++ and COBOL.

2. Give one advantage of COBOL program and be able to explain it.

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.

5. Be able to explain one characteristics of COBOL program.

6. Be able to differentiate the overall structure of COBOL program.

12
LESSON 2

STRUCTURE OF THE
LANGUAGE

Objectives:

At the end of the lesson, the students must be able to:

1. Know the basic character set used in COBOL program;

2. Know the types of COBOL words;

3. Understand basic COBOL program application.

13
I. COBOL CHARACTER SET

COBOL characters are comprise of the following:

CHARACTER MEANING

0,1,2,.….9 Digit

A,B,C,…Z Letter

Space (blank)

()“ = $ , ; Special symbols

+ - * / > <

II. TYPES OF COBOL WORD

A. USER-DEFINED WORD

This is given by the programmer of the language user. In the use of this word, certain rules are followed,

particularly in Choosing Names of Files, Records, and Data Fields:

1. A name must be constructed from the letters of the alphabet, the digits 0 through 9, and the hyphen. No other

characters are allowed.

2. A name must not be longer than 30 characters.

3. A name must not begin with a hyphen.

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, “

READ MASTERFILE AT END STOP RUN.”

E. Optional Word - Word that may be included in the COBOL statement to improve readability for users. For

example, “READ MASTERFILE RECORD AT END STOP RUN.”

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.

III. AN ILLUSTRATIVE EXAMPLE

This module will use an illustrative example of a running program. The sequence will be illustrated and discussed in

succeeding lessons according to division.

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:

STUDNO STUDNAME MIDGRADE FINGRADE

10 CHARS 10 CHARS 3 DIGITS 3 DIGITS

X(10) X(10) 9(3) 9(3)

OUTPUT FILE STUDREPORT

PUP

CCMIT

ENTER NAME: _________________

ENTER MIDTERM GRADE: _______

ENTER FINAL GRADE : ________

AVERAGE : ________

INPUT MORE? (Y/N) : ________

SAMPLE PROGRAM CODE

1-6 7 8-11 12 73-80

1 IDEN TIFICATION DIVISION.

15
2 PROG RAM-ID AVERAGE.

3 AUTH OR. CCMIT-FACULTY.

4 DATE -WRITTEN. NGAYON.

6 ENVI RONMENT DIVISION.

7 INPU T-OUTPUT SECTION.

8 FILE -CONTROL.

9 SELECT GRADEFILE ASSIGN TO “AVERAGE DAT”.

10

11 DATA DIVISION.

12 FILE SECTION.

13 FD GRADEFILE

14 LABEL RECORDS ARE OMITTED

15 DATA RECORD IS GRADE-REC.

16 01 GRADE-REC PIC X(80).

17 WORK ING-STORAGE SECTION.

18 01 NAME PIC X(35).

19 01 MIDTERM PIC 9V99.

20 01 FINALS PIC 9V99.

21 01 AVE PIC 9V99.

22 01 ANS PIC X.

23 01 P-AVE PIC Z.ZZZ.

24 01 GR-REP.

25 05 FILLER PIC X(20).

26 05 PRT-NAME PIC X(35).

27 05 PRT-AVE PIC Z.ZZ.

28 01 HDGI.

29 05 FILLER PIC X(37) VALUE SPACES.

30 05 FILLER PIC X(3) VALUE “PUP”.

31 05 FILLER PIC X(40) VALUE SPACES.

32 01 HDG2.

33 05 FILLER PIC X(36) VALUE SPACES.

16
34 05 FILLER PIC X(5) VALUE “CCMIT”.

35 05 FILLER PIC X(39) VALUE SPACES.

36 01 HDG3.

37 05 FILLER PIC X(20) VALUE SPACES.

38 05 FILLER PIC X(7) VALUE “STUDENTS”.

39 05 FILLER PIC X(22) VALUE SPACES.

40 05 FILLER PIC X(7) VALUE “AVERAGE”.

41 01 HDG4.

42 05 FILLER PIC X(21) VALUE SPACES.

43 05 FILLER PIC X(4) VALUE “NAME”.

44 05 FILLER PIC X(25) VALUE SPACES.

45 05 FILLER PIC X(5) VALUE “GRADE”.

46 05 FILLER PIC X(25) VALUE SPACES.

47 01 HDG5.

48 05 FILLER PIC X(80) VALUE SPACES.

49

50 SCRE EN SECTION.

51 01 SCRN.

52 05 BLANK SCREEN.

53

54 PROC EDURE DIVISION.

55 OPEN OUTPUT GRADEFILE.

56 PERFORM HDG-RTN.

57 PERFORM COMPGRADE UNTIL ANS = “N” OR ANS = “n”.

58 GO TO FIN-RTN.

59 HDG- RTN.

60 WRITE GRADE-REC FROM HDG1.

61 WRITE GRADE-REC FROM HDG2 AFTER 2.

62 WRITE GRADE-REC FROM HDG3 AFTER 3.

63 WRITE GRADE-REC FROM HDG4.

64 WRITE GRADE-REC FROM HDG5.

65 COMP GRADE.

17
66 DISPLAY SCRN.

67 DISPLAY “PUP” LINE 3 COLUMN 39.

68 DISPLAY “CCMIT” LINE 4 COLUMN 38.

69 DISPLAY “ENTER NAME : “ LINE 6 COLUMN 25.

70 ACCEPT NAME LINE 6 COLUMN 49.

71 DISPLAY “ENTER MIDTERM GRADE : “ LINE 8 COLUMN 25.

72 ACCEPT MIDTERM.

73 DISPLAY “ENTER FINAL GRADE : “ LINE 10 COLUMN 25.

74 ACCEPT FINALS.

75 ADD MIDTERM TO FINALS.

76 END-ADD.

77 DIVIDE FINALS BY 2 GIVING AVE.

78 MOVE AVE TO P-AVE.

79 MOVE AVE TO PRT-AVE.

80 DISPLAY “AVERAGE : “, P-AVE LINE 12 COLUMN 25.

81 MOVE NAME TO PRT-NAME.

82 WRITE GRADE-REC FROM GR-REP.

83 DISPLAY “INPUT MORE (Y/N)? : “ LINE 14 COLUMN 25.

84 ACCEPT ANS.

85 FIN- RTN.

86 CLOSE GRADEFILE.

87 STOP RUN.
Review Questions

Name: ________________________________ Date: _____________


Year and Section: _______________________ Rating: ___________

1. What are the types of COBOL character set?

18
2. Be able to differentiate the two types of COBOL Word.

3. How user-defined words are formed?

4. Be able to differentiate each type of Reserved word.

EXERCISES

1. Write Valid if the user-defined word is valid and Invalid if the user-defined word is
invalid.

a. _______________ CUST_REPORT f. ______________ SALES-AMT


b. _______________ SPACES g.______________ 3STUD-NAME
c. _______________ STUDCOURSE h.______________AMOUNT-DUE-
d. _______________ 143 i. ______________ ACCNTNA-ME
e. _______________ STUDENT ID j. ______________ SALES*REP

2. Complete the paragraph, sections and divisions of COBOL template.

19
IDENTIFICATION DIVISION.
__________________________

________________ DIVISION.

_________________ SECTION.

SOURCE-__________________
___________________________

_________________ SECTION.

SELECT {file name} _________________ TO {device name}

_________________ DIVISION.
_________________ SECTION.

_____ {file name}

LABEL ____________ ARE OMITTED.


RECORD ____________ {number} CHARACTERS.

_____ {record name}

WORKING- ___________________ SECTION.

__________________ DIVISION.

20
LESSON 3

IDENTIFICATION AND
ENVIRONMENT DIVISION

Objectives:

At the end of the lesson, the students must be able to:

1. Know the basic syntax of IDENTIFICATION and ENVIRONMENT DIVISION;


2. Know the different sections and paragraphs of IDENTIFICATION an ENVIRONMENT
DIVISION;
3. Use the COBOL language in I.T. applications.

I. RULES FOR INTERPRETING INSTRUCTION FORMATS

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.

II. FOUR DIVISIONS OF COBOL

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.

The following example includes optional paragraphs.

Fig. 6 Example of IDENTIFICATION DIVISION

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}….]

ENVIRONMENT DIVISION is the second division of COBOL program. It describes the


“computing environment” of the program. The “computing environment” refers to the type of
computer hardware on which the program is written and run. It is the only machine-dependent
division of a COBOL program. It is the only machine-dependent division of a COBOL program. It
supplies information about the computer equipment to be used in the program. That is, the

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.

SECTION OF THE ENVIRONMENT DIVISION

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.

 Assigned filename must be enclosed in double quotes.


Ex. SELECT WORKREC ASSIGN TO “WORKREC.DAT”

Fig. 8 Sample of INPUT-OUTPUT SECTION

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:

SELECT {filename} ASSIGN TO {DISK


Drive Letter:\sub-directory\filename
PRINTER

The drive Letter\sub-directory is the path where filename is located.

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

Name: __________________________________ Date: ______________


Year and Section: _________________________ Rating: ____________

1. Write the four (4) divisions of COBOL program in order.

2. Be able to enumerate the complete paragraphs/parts of IDENTIFICATION DIVISION in order.

3. Differentiate the two (2) sections of ENVIRONMENT DIVISION.

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).

1-6 7 8-11 12-72 73-80

28
LESSON 4

DATA DIVISION

Objectives:

At the end of the lesson, the students must be able to:

1. Know the paragraphs and clauses in DATA DIVISION.


2. Know the FILE SECTION and WORKING-STORAGE SECTION.
3. Learn the different types of data used in COBOL program.
4. Learn how to use the different PICTURE clauses.

I. RULES FOR FORMING USER-DEFINED DATA-NAMES

 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)

 The data-name must contain at least one alphabetic character.

 It must not begin or end with a hyphen.

29
 A name must not be a reserved COBOL word because reserved COBOL words have
pre-assigned meanings.

II. GUIDELINES FOR FORMING USER-DEFINED DATA-NAMES

 Use of Meaningful Names

The data-name should be meaningful and specific. This is to make it easier to


understand, follow the program logic or sometimes debug. It should describe the type
and content of data and in the field. Avoid person’s name or an acronym not related
to the program. For example, student identification number can be coded as STUD-ID
or STUDENT-NO instead of SID or SINO.

 Use Prefixes of Suffixes Where Appropriate

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.

III. TYPES OF DATA

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

Data are organized in COBOL in the following form

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.

FILE: STUDENT FILE


RECORD: Student Record which contains the following:
Personal information
Educational background
Honors/Awards Received

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.

I. TYPES OF DATA FIELD

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.

Rules for Forming Numeric Data Field


 Up to 1 to 18 digits

 No commas are allowed in numeric literals

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.

Valid Numeric Invalid Numeric Reasons why invalid


Literal Literal
10.50 10,000 Commas are not allowed
-387.58 $225 Dollar sign is not permitted
+10000 175- Plus or minus signs must not
appear to the right of the number

b. Alphabetic Data Field – A data field used to store alphabetic characters. It is


represented by A character in the data declaration. Examples are names of
individual, names of cities, states, or countries.

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.

2. SUBDIVISION OF DATA FIELD


A data field that is subdivided into two parts:
 Group Data Field – A data that can be divided into subordinate components. For
example, the data field “date of birth” can be subdivided into three subordinate
components: “day of birth”, “month of birth”, “year of birth”. In this case , “date of
birth” is a group data field; its components are elementary data field.

 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.

V. PROGRAM STRUCTURE OF DATA DIVISION

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.

THE TWO MAIN SECTIONS OF THE DATA DIVISION


A. FILE SECTION – Defines all input and output files including the records needed.

DATA DIVISION.

FILE SECTION.
FD filename
[LABEL RECORD IS STANDARD]
[LABEL RECORDS ARE OMMITED]
[RECORD CONTAINS ______ CHARACTERS]
[DATA RECORD IS _________________]
1 RECORD NAME.

I. FILE DESCRIPTION ENTRIES

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.

C. RECORDS CONTAINS clause – clause that indicates the number of characters in


record. Data entered on a terminal is typically specified with the clause
RECORD CONTAINS 80 CHARACTERS, although the number of character will
depend on how many characters can be stored on one line of the specific
terminal.

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.

E. DATA RECORD clause – pertains to the name of the designated record.

RULES FOR CODING DESCRPTION ENTRIES


 FD is coded in Area A.

 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 Sample of FILE SECTION


of DATA DIVISION

2. RECORD DESCRIPTION ENTRIES


We have earlier defined record as a collection of related data items within a file. After a
file is declared in FD clause, the record description entries follow. Record description specifies
the format of a record. There are various level numbers in a record. Record name takes the
value of 01. this is considered as the highest level of data in a file. Since record is divided in
fields, all other subordinate field is coded with any level number between 02 and 49. level 01 is

coded in Area A and all other levels are coded in Area B.

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.

Syntax: DATA DIVISION.


WORKING-STORAGE SECTION
01 [variable entry]
01 [variable entry]
01 [variable entry]
05 [variable entry]
05 [variable entry]

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.

I. RULES FOR USING WORKING-STORAGE 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.

2. USES OF WORKING STORAGE SECTION

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.

VI. DATA ITEM ENTRY AND CLAUSES

There are item entries and clauses which define the type of data that will be used in
variable declaration.

A. THE PICTURE CLAUSE FOR DATA DESCRIPTION

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.

RULES FOR CHOOSING PIC CLAUSE

 A group data field must not have a PIC clause.


 The word PIC can start in any column after the data field. However, for easy readability,
the word PIC for all data fields should start in the same column.

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.

1. The 9 PICTURE Character

In fig. 10 AMOUNT is of numeric type with a maximum digit of 7. The numeric 9


indicates that a storage position should only contain any of the numeric digits from 0 to 9. If the
input data is of numeric type, it cannot contain anything else other than numbers, not even a
decimal point. Leading spaces may however be allowed. Thus, a data value with decimal point
as in 1200.50 cannot be directly stored in a numeric data field. The following examples illustrate
how the letter V works in PIC clauses.

Data Value Stored Data Field’s PIC Clause Value Contained


12050 PIC 999V99 120.50
020050 PIC 9V999 1.200
125 PIC 99V9 12.5
Again, note that a numeric field can contain only the digits 0-9. Blanks are not numeric
characters. When a value does not fill a numeric 9 field completely, the value is justified to the
right, and the extra positions are filled with zeros. When entering data, you should be careful to
zero-fill a field with leading zeros, otherwise you may be in for some surprising results. Thus, in
a field of six positions the numeric value 143 should be entered as follows:
000143

2. The V PICTURE Character

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.

3. The X PICTURE Character

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.

4. The A PICTURE Character

The A PICTURE character is similar to the X character, except that it indicates only
alphabetic characters and blanks.

5. The P PICTURE Character

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.

Numeric Value Data Field’s PIC Clause Equivalent


12 PIC 99PPPV 1200^
1250 PIC VP(3)9(4) ^0001250

6. The S PICTURE Character

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.

Numeric Value Data Field’s PIC Clause Storage Value


250.25 PIC S9999V99 0250^25
-1250.25 PIC S9999V99 ^1250^25

B. THE FILLER CLAUSE

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.

Fig. 13 Example of Data Division


using FILLER command.

41
FILLER clause is also optional in record description. The following is acceptable:
Fig. 14 Example of Data Division without FILLER command.

C. THE VALUE CLAUSE

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.

Example of VALUE Clause Using Numeric Literals

05 WS-DISCOUNT PIC V99 VALUE .15.


05 WS-LABORATORY-FEE PIC 9(3) VALUE 350.
05 WS-TAX-DEDUCTION PIC 9(3)V9(3) VALUE 125.250.

Examples of Value Clause using Nonnumeric Literals

05 WS-TITLE PIC X(14) VALUE “MONTHLY REPORT”.


05 WS-MORE-RECORDS PIC X(3) VALUE “YES”.
05 WS-TITLE PIC X(24) VALUE “ALET’S FINANCIAL REPORT”.

D. THE PICTURE CLAUSE FOR DATA EDITING

FUNCTION OF DATA EDITING

 Printing of decimal points where decimal alignment is implied.


 Suppression of leading zeros.
 Printing of dollar signs and commas.

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.

1. The Decimal and the Comma PICTURE Insertion Characters

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.

Numeric Value Data Field’s PIC Clause Storage Value

2,500.25 PIC 9,999.99 2,500.25


250.25 PIC 9,999.99 0,250.25
25 PIC 9,999.99 0,025.000

2. The Z PICTURE Character

The Z PICTURE character is used to replace zeros by blanks. Zero-suppression terminates


when the firs non-zero digit or the ._ decimal character is encountered whichever occurs first.
The letter b in the following example represents a blank space.

Numeric Value Data Field’s PIC Clause Storage Value

2,500.25 PIC Z,ZZZ.ZZ b2,500.25

250.25 PIC Z,ZZ9.99 bb250.25

25 PIC ZZ.9 b25

3. The B PICTURE Character

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.

4. The 0 PICTURE Character

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.

5. The / PICTURE Character

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,

05 DATE OF BIRTH PIC 9(6) VALUE 011591

05 DOB PIC 99/99/99

Further processing as MOVE DATEOFBIRTH TO DOB will cause DOB to contain 01/15/91.

Summary of Characters Available for Use in PICTURE Clause

TYPE OF CHARACTER SYMBOL USE

Field Definition Characters 9 Numeric field


A Alphabetic field
X Alphanumeric field

Numeric Field Special Character V Assumed decimal point


P Decimal scaling
S Positive or negative sign

Editing Characters $ Insertion of dollar sign


Z Zero suppression
* Check protection
. . Decimal point
, Comma
+ Plus sign

44
- Minus sign
DB Debit sign
CR Credit sign
B Blank insertion
0 Zero insertion
/ Stroke insertion

Review Questions

Name: __________________________________ Date: ______________


Year and Section: _________________________ Rating: ____________

1. Differentiate FILE SECTION to WORKING-STORAGE SECTION.

2. Define the paragraph entries of FILE SECTION.

3. Define the compositions of WORKING-STORAGE SECTION.

4. Be able to compare the PICTURE CLAUSE and FILLER CLAUSE.

45
5. Write the appropriate statement for the following situations.

a. The beginning value of CTR is equal to Zero.


_

b. The length of the string variable NAME is 10 characters.


_

c. The integer numerical variable CTR-OUT with the length of four.


_

d. The sample layout of Total no of students is 999,999.


_

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

3. The character used in the PICTURE clause when:

_ a. the data-name contains numeric, alphanumeric and alphabetical characters


_ b. the data-name contains numeric characters only.
_ c. indicating the position of an assumed decimal point.
_ d. replacing leading zeros in a value with blanks.
_ e. the data-name contains alphabetic characters only.

4. Create a COBOL program (from ENVIRONMENT to DATA DIVISION only)

Given: A file of Student records


Requirements: Count the number of students with an average grade of less than 3.0. Print the
total number of students at the end of the file.

INPUT FILE: STUD-FILE-IN


Format: STUD-NO STUD-NAME MIDTERM FINAL
10 chars. 25 chars. 3 digits 3 digits

OUTPUT FILE: STUD-FILE-OUT

POLYTHECNIC UNIVERSITY OF THE PHILIPPINES

STUDENT RECORD

STUDENT STUDENT FINAL


NUMBER NAME GRADE

{record#1}
{record#2}

47
……………
……………
……………
{record#n}

No. of students with grade less than 3.0 : (2 digits)


No. of students : (3 digits)

LESSON 5

THE PROCEDURE DIVISION

Objectives:

48
At the end of the lesson, the students must be able to:

1. Know the different formats and uses of COBOL statements;


2. Write, compile and execute a COBOL program;
3. Use the COBOL language in various I.T. applications.

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:

OPEN INPUT STUDENT-FILE


OUTPUT REPORT-FILE

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.

READ filename AT THE END imperative statement.

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

READ STUDFILE AT END MOVE 1 TO EOFSW.

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

MOVE value TO data-field.

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.

Figurative Constants Meaning

SPACE(S) Fills the field with blank spaces.


ZERO(S) Fills the field with zeroes.
HIGH-VALUE(S) Fills the field with the highest binary value
The computer system being used is able to
represent it.
LOW-VALLUE(S) Fills the field with the lowest binary value
the computer system being used is able to
represent it.

If a record named REMARKS is defined as

05REAMRKS PIC X(10).

Its value can be initialized to 10 blank spaces using this MOVE statement.

MOVE SPACES TO REMARKS.

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:

Receiving Data Field

Name PIC clause MOVE statement Contents of Receiving


Data Field

REMARKS PIC X(10) MOVE “PASSED” TO REMARKS. PASSED

REMARKS PIC X(5) MOVE “FAILED” TO REMARKS. FAILED

COUNTER PIC 999 MOVE 20 TO COUNTER. 020

COUNTER PIC 99 MOVE 100 TO COUNTER. 00

COUNTER PIC 9 MOVE 123 TO COUNTER. 3

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.

The general format of the indirect MOVE statement is

MOVE data-field-1 TO data-field-2.

The following examples illustrate the indirect MOVE statement.

MOVE EMPNAME TO EMPNAME-OUT.

MOVE SALARY TO SALARY-OUT.

Contents of data fields before MOVE

PATRICK

53
EMPNAME EMPNAME-OUT

Contents of data fields after MOVE

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.

RULES FOR THE MOVE STATEMENT

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.

EFFECTS OF PIC CLAUSE ON DATA MOVES

Receiving Data field

54
Sending Data field Longer Shorter

Alphanumeric Pad on the right with blanks Truncate on the right

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

Integer Pad on the left with zeroes Truncate on the left

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

CLOSE filename-1, filename-2, … filename-n.

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

ARITHMETIC STATEMENTS perform arithmetic calculations. The basic arithmetic


statements are ADD, SUBTRACT, MULTIPLY, DIVIDE, and COMPUTE. The first four of these
statements can be used both with and without a COBOL feature called the GIVING clause.

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

ADD SALARY TO TOTAL-SALARY

SALARY TOTAL-SALARY

PIC 9(5) PIC 9(7)

Before Execution

50000 0

After Execution

50000 50000

ADD PRODUCTION TO TOTAL-PRODUCTION

PRODUCTION TOTAL_PRODUCTION

PIC 9(4) PIC 9 (6)

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:

ADD QUIZ1 QUIZ2 QUIZ3 TO TOTAL-QUIZ.

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.

ADD 100 TO SALARY.

RULES FOR THE ADD STATEMENT

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

SUBTRACT datafield-1 FROM datafield-2.

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:

SUBTRACT DISCONT FROM PRICE.

DISCOUNT PRICE

PIC 9(3) PIC 9(5)

Before execution

250 1000

After execution

250 750

SUBTRACT EXPENSES FROM INCOME.

EXPENSES INCOME

PIC 9(4) PIC 9(6)

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:

SUBTRACT WITH-TAX, MEDICARE FROM GROSS-INCOME.

The contents of WITH-TAX and MEDICARE remain unchanged, the contents of GROSS-
INCOME was changed.

It is possible to use a numeric literal in the SUBTRACT statement.

Example:

SUBTRACT 1000 FROM PRICE.

RULES FOR THE SUBTRACT STATEMENT

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.

4. As with ADD statements, numeric literals may be used in SUBTRACT statements.


However, the result must be stored in a data field. The last item in a SUBTRACT
statement must be a data field.

MULTIPLY Statement

The MULTIPLY statement multiplies the contents of two data fields.

The format of the MULTIPLY statement is

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:

MULTIPLY RATE BY PRICE.

RATE PRICE

PIC 9(3) PIC 9(5)

Before Execution

10 150

After Execution

10 1500

The result in product is stored in PRICE.

RULES FOR THE MULTIPLY STATEMENT

1. The contents of two data fields are multiplied together.

2. The result is always stored in the second data field. The other data field remains
unchanged.

3. A MULTIPLY statement can involve only two data fields.

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

DIVIDE datafield-1 BY datafield-2.

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.

The format of the second type is

DIVIDE datafield-1 INTO datafield-2.

In this statement, the dividend is datafield-2 and the divisor is datafield-1. The result of
division is stored in datafield-2.

Example:

DIVIDE 10 INTO AVE.

DIVIDE AVE BY 10.

DIVIDE SALES BY RATE.

DIVIDE RATES INTO SALES.

RULES FOR THE DIVIDE STATEMENT

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.

The GIVING clause

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.

The GIVING clause for the ADD statement:

ADD datafield-1 datafield-2 ... datafield-n GIVING datafield-x.

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:

ADD QUIZ1 QUIZ2 GIVING TOTAL-QUIZ.

In this example, the contents of QUIZ1 and QUIZ2 values did not changed, only
the content of the data field TOTAL-QUIZ was changed.

The GIVING clause for the SUBTRACT statement:

SUBTRACT datafield-1 FROM datafield-2 GIVING datafield-3.

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:

SUBTRACT 10 FROM COUNTER-1 GIVING COUNTER-2.

SUBTRACT DEDUCTION FORM GROSS-SAL GIVING NET-SAL.

SUBTRACT W-TAX, SAL-LOAN FROM GROSS-SAL GIVING


NET-SAL.

The GIVING clause for the MULTIPLY statement

The MULTIPLY statement with the GIVING option has the following format:

MULTIPLY datafield-1 BY datafield-2 GIVING datafield-3.

Examples:

MULTIPLY QTY BY PRICE GIVING SALES.

MULTIPLY SALARY BY 0.20 GIVING BONUS.

The GIVING clause for the DIVIDE statement

The format of the DIVIDE statement with the GIVING clause is

DIVIDE datafield-1 BY datafield-2 GIVING datafield-3.

Or

DIVIDE datafield-1 INTO datafield-2 GIVING datafield-3.

Both of these DIVIDE statements yield the same result.

Examples:

64
DIVIDE TOTAL-GRADE BY UNITS GIVING AVE-GRADE.

DIVIDE ANNUAL-SALES INTO 12 GIVING AVE-SALES.

The ROUNDED clause

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 REMAINDER clause

The REMAINDER clause is used in COBOL to store the remainder of a division


operation. The REMAINDER clause is used with the DIVIDE statement for this purpose.
When using the REMAINDER clause, the DIVIDE statement must use the GIVING clause.
The format of the REMAINDER clause is

DIVIDE datafield-1 BY datafield-2


GIVING datafield-3
REMAINDER datafield-4.

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.

The ON SIZE ERROR clause

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:

MULTIPLY SALES BY RATE

GIVING COMMISSION

ON SIZE ERROR

MOVE 1 TO ERROR-SW.

COMPUTE statement

The COMPUTE statement is used to determine the value of arithmetic


expressions. It has the following format:

COMPUTE data-field = arithmetic expression.

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:

COMPUTE TOTAL-GRADE = GRD1 + GRD2.

COMPUTE DISCOUNT = PRICE * DISC-RATE.

COMPUTE NET-SALES = GROSS-SALES – EXPENSES.

COMPUTE AVE-GRADE = TOTAL-GRADE / TOTAL UNITS.

COMPUTE SALARY = (HOURLY-RATE * 40) –


(NO-OF-HRS - 4) * OT-RATE.

66
RULES FOR ORDER OF ARITHMETIC OPERATIONS

Arithmetic operations are performed in the following order:

1. Anything in parentheses is calculated first. If parentheses are nested, they are


evaluated from the inside out.

2. Exponentiation.

3. Multiplication / Division.

4. Addition / Subtraction.

Note: Operations of equal priority are evaluated left to right.

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 GRADE > 74.00


MOVE “PASSED” TO REMARKS.

Format of IF-ELSE statement is

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

The IF statement is an example of a relation condition. In relation conditions, two


operands are compared. The IF statement determines how these operands are “related to” one
another. The outcome of the comparison will always be either true or false.

The relational operators are:

1. IS EQUAL TO (=)

2. IS NOT EQUAL TO (NOT =)

3. IS LESS THAN (<)

4. IS NOT LESS THAN (NOT <)

5. IS GREATER THAN (>)

6. IS NOT GREATER THAN (NOT >)

7. IS GREATER THAN OR EQUAL TO (> =)

8. IS LESS THAN OR EQUAL TO (< =)


The general format of the relation conditions is

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

It is possible to combine arithmetic operations with relation condition. If a statement


contains both arithmetic operations and relation conditions, the arithmetic operations are
always performed first.

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.

05 END-OD-FILE PIC X VALUE “N”.


88 NO-MORE-DATA VALUE “Y”.
88 MORE-DATA VALUE “N”.

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.

The format of a compound condition statement is

70
AND
IF condition-1 OR condition-2
NOT

Examples:

IF AGE > 50 OR AGE < 18


PERFORM ERROR-RTN.

IF COLLEGE-CODE = “CCMIT”
AND YR-LEVEL = 3
AND SEX-CODE = “M”
ADD 1 TO COUNTER.

IF NOT (EMPLOYEE-RATE IS GREATER THAN 125.00)


PERFORM COMPUTE-RTN.

RULES FOR EVALUATING MULTIPLE LOGICAL OPERATORS

The following order of priority enforced in evaluating multiple logical operators in a single
COBOL statement.

1. Logical operators within parentheses (from inner parenthesis to outer parentheses).


2. The logical operator NOT.
3. The logical operator AND.
4. The logical operator OR.

The PERFORM 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.

Classification of 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.

b. PERFORM paragraph-name integer TIMES.

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

c. PERFORM paragraph-name-1 THROUGH paragraph-name-2.

This statement transfers control to paragraph-name-1, executes all the


statements in paragraph-name-1 through paragraph-name-2, and then returns to the
statement immediately following the PERFORM statement. If there are two statements
in paragraph-name-1 and three statements in paragraph-name-2, the PERFORM

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.

This statement will perform all the statements between paragraph-name-


1 (BSIT-RTN) and paragraph-name-2 (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.

This statement represents an iteration control structure. It allows a specified paragraph


to be executed as many times as needed. The diagram below graphically illustrates how
the conditional PERFORM statement functions.

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.

b. PERFORM paragraph-name VARYING data-field FROM initial value BY increment value


UNTIL condition(s).

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

Data-field OCCURS integer TIMES.

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.

RULES FOR DEFINING A TABLE AND USING SUBSCRIPTS

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.

TABLE in COBOL is a one-dimensional array or a multi-dimensional array that holds similar


data items of fixed number of elements. PERFORM statement with VARYING option is a
statement used to execute a specified paragraph repeatedly with different values of a
subscript or index. The execution of this statement proceeds as follows:
1. Move the initial value to data-field.
2. Determine whether the condition is true.
3. If the condition is true, execute the statement following PERFORM statement; if the
condition is false, execute the specified paragraph-name.
4. Add the increment-value to data-field.
5. Go to step 2 and continue.

The diagram below illustrates how this PERFORM statement functions.

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

One of the requirements is to print the table in the output file.


01 DETAIL .
02 PRT-Q OCCURS 5 TIMES .

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.

c. PERFORM paragraph name VARYING data –field-1 FROM initial-value BY increment-value


UNTIL condition (s) AFTER data-field-2 FROM initial-value BY increment-vale UNTIL condition(s).

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

EXIT FROM MOVE INITIAL ADD INCREMENT


PERFORM VALUE TO VALUE TO
STATEMENTDATA-FIELD-2 DATA-FIELD-1

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.

RULES FOR DETERMINING TWO-LEVEL TABLES


1. In the definition f a two-level table, the OCCURS clause for the row is stated first,
followed by the OCCURS clause for the columns.
2. The PIC clause is listed with the second OCCURS clause.
3. To access an element of two-level table, two subscripts or indexes are needed. There
must be a blank space between the comma that appears after the first subscript and
before the second subscript.

Example:
CCMIT

YEAR BSIT BSCS


FRESHMEN 100 300
SOPHOMORE 200 200
JUNIOR 300 400
SENIOR 400 200

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.

YEAR BSIT BSCS TOTAL


FRESHMEN 100 300

79
SOPHOMORE 200 200
JUNIOR 300 400
SENIOR 400 200

SAMPLE PROGRAM USING TWO-DIMENSIONAL TABLE

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.

02 FILLER PIC X(5)


02 P-TSTUDYEAR PIC 99,999.
PROCEDURE DIVISION.
PERFORM INIT-RTN THRU INIT-RTN-END.
PERFORM PROCESS-RTN UNTIL EOFSW = 1.
STOP RUN.
INIT-RTN.
OPEN STUDENT, OUTPUT OUTFILE.
READ STUDENT AT END MOVE 1 TO EOFSW GO TO INIT-RTN-END.
PERFORM HEADING-RTN.
INIT-RTN-END.
PROCESS-RTN.
PERFORM ADD-RTN VARYING 1 FROM 1 BY 1 UNTIL I > 4 AFTER J FROM
1 BY 1 UNTIL J > 2.
PERFORM MOVE-RTN VARYINGFROM 1 BY UNTIL > 4.
PERFORM MOVE-RTN VARYING FROM 1 BY UNTIL I > 4.
READ STUDENT AT END MOVE 1 TO EOFSW.
ADD-RTN.
ADD COURSE ( I, J) TO TOATL-YEAR (I)
MOVE-RTN.
IF I= MOVE “FRESHMEN” TO P-YEAR. GO TO A.
IF I = 2 MOVE “SOPHOMORE” TO P-YEAR. GO TO A.
IF I = 3 MOVE “JUNIOR” TO P-YEAR. GO TO A.
IF I = 4 MOVE SENIOR TO P-YEAR.
A. PERFORM MOVE2-RTN VARYING FROM J FROM 1 BY 1 UNTIL J > 2.
MOVE TOTAL-YEAR (I) TO P-TSTUDYEAR.

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.

COMPLETE SAMPLE PROGRAM #1


GIVEN: SALESFILE
FORMAT:

AREA CODE NUMBER SALES SALESMAN NAME AMOUNT


X 9(5)-length X(25) 9(5)V99

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

SAN MIGUEL CORPORARATION


STA. MESA, MANILA17
(2 SPACES)
SALES REPORT12
(1 SPACE)

AREA4 SALESMAN8 SALESMAN8 AMOUNT6


CODE4 NUMBER6 NAME4
X 9(5) X(25) 99,999.99

TOTAL NO. OF SALESMAN:22 9,999


TOTAL ACCUMULATED AMOUNT: Php29 9,999,999.99

Sample Program

1-6 7 8-11 12 73-80


IDEN TIFICATION DIVISION.
PROG RAM-ID. SALES.
* AUTH OR. ALET.
* INST ALLATION. S-305.
* DATE -WRITTEN. NOVEMBER 19,2008.
* DATE -COMPILED. NOVEMBER 19,2008.
* SECU RITY. EXCLUSIVE FOR US.
* REMA RKS FIRST PROGRAM.
ENVI RONMENT DIVISION.
CONF IGURATION SECTION.
SOUR CE-COMPUTER. IBM-PC.
OBJE CT-COMPUTER IBM.-PC..
INPU T-OUTPUT SECTION.
FILE -CONTROL.
SELECT INFILE ASSIGN TO ‘SALES’.
SELECT OUTFILE ASIGN TO ‘BENTA’.
DATA DIVISION.
FILE SECTION.
FD INFILE
LABEL RECORD IS STANDARD
DATA RECORD IS INREC.
01 INREC.
02 AC PIC X.

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
_________________________

TO COMPLETE THE PROGRAM

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

 to set the system in the location of the COBOL compiler

C:\ REALCOB SAMPLE1.COB


SOURCE FILENAME[ .COB]: SAMPLE1.EXE
OBJECT FILENAME[ .OBJ]: SAMPLE1.OBJ
SOURCE LISTING [ .LST] SAMPLE1.LST press enter
PASS1
PASS1A
PAS2
:
END OF COMPILATION

TO LINK THE PROGRAM

86
C:\COBOL\ LINK

OBJ FILE [NUL.OBJ]: SAMPL1OBJ


OUTPUT FILE [SAMPLE1.EXE]:SAMPLE1.EXE.
MAPFILE [NULL.MAP]
LIBRARIES AND PATHS: REALDOS
DEFINITION FILE: press Enter

TO RUN THA PROGRAM

C:\ SAMPLE1.EXE

TO DISPLAY THE OUTPUT ILE

C:\COBOL\ TYPE BENTA

Problem Solving
A. This file will contain records that does not contain a multi-dimensional table
Input File: Studentfile
Input Format:

Year Course Code Student Student name


number
9 X(5) X(10) X(25)
Output layout (The same output layout with letter A.)

Polytechnic University of the Philippines


Sta. Mesa, Manila
2 spaces
Student Population
1 space
Year Level Course
BSCS BSIT Total
Freshmen 999 999 9,999
Sophomore 999 999 9,999
Junior 999 999 9,999
Senior 999 999 9,999
Total 9,999 9,999

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.

PERFORM MOVE1-RN VARYING SUB2 FROM 1 BY 1 UNTIL SUB2 >2.


MOVE TOT-YR (SUB1) TO P-TOT-YEAR(SUB1).
WRITE BAWAS FROM DETALYE AFTER 1.
MOVE2-TRN.
MOVE KURS(SUB1, SUB2) TO P-TAB (SUB2).
TOTAL-COUR-RTN.
MOVE TOT-CR (SUB2) TO P-TOTCO (SUB2)

*** 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.

B. Given: Transaction file


Input Layout/Format:
Account Account Name Transaction Amount
Number Code
X (10) X (25) X 9(7) V99

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

Total No. of Records printed:


Total Accumulated Balance: P Z,ZZZ,ZZZ,ZZ9.99

The following hardcopies must be submitted:


@ Program Listing, @ Input file, @ Output file, @ Structured Flowchart

EXERCISES

1. The output layout is:


Enrolment Report
First Semester, 2k9-2k10
1 space
BSA BSBA BSECE BSEM
900 200 300 400

Total no. of students: 99,999.99

The input file is


BSA BSBA BSECE BSEM
900 200 300 400

91
Write PERFORM… UNTIL statement that will read the input records and will prinit the required
output

THE SEARCH STATEMENT: An Alternate Method to Search a Table

The two principal formats of the SEARCH statements are :

1. SEARCH identifier-1 [ varying { index-name-1,


identifier-2 } ] [AT END imperative-statement-1]
;WHEN condition-1 { imperative statement-2 NEXT
SENTENCE }

; [ WHEN condition-2 { imperative-statement-2 NEXT


SENTENCE } ] …

In this format, identifier-1 is an item whose description in the DATA DIVISION


contains an OCCURS and an INDEX BY clause COBOL offers a feature called program.
Whereas a subscript refers to the location of a table element, an index contains a

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-1 OCCURS integer TIMES INDEXED BY data-field-1

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.

When the VARYING option is used, index-name-1 or identifier-2 is varied in the


same way as the index specified in the relevant INDEXED BY clause.identifier-2 must be
specified as USAGE IS INDEX, or defined in OCCURS statement. The AT END clause is
optional. If it is omitted, program control will pass to the next statement when the table
has been searched and no match has been found. If AT END is included and imperative-
sttement-1 does not terminate with GO TO, a branch to the next sentence will be made.
WHEN introduces another form of conditional expression. The first format can be also
used to search sorted and unsorted tables.

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.

Two formats are available as follows:


1. SET { index-name-1 [ index-name-2] … }
Identifier-1 [ identifier-2]…
TO { index-name-3 identifier-3 integer-1 }
2. SET index-name-1 [ index-name-2] { UP BY DOWN BY }
{ IDENTIFIER-1 INTEGER-1 }

In format 1, if we use index-name-1, we can set it equal to index-name-3, identifier-3, or


literal-1. It identifier-3 is used, it must be defined as an elementary integer item, if integer-1 is
used, it must be a positive integer. If we set identifier-1 and it has not been defined by a USAGE
IS INDEX clause, it can be set only to index-name-3.
In format 2, we can increase or decrease the value of index-name-1 either by a positive
integer (literal-1) or by the value of identifier-1, which must be a field that has not been defined
as USAGE IS INDEX. The effect of UP BY is to increase the value of indicated decrement.

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.

2. SEARCH ALL identifier-1 [AT END imperativr-statement-1]

; WHEN { data-name-1 condition name-1


{ IS EQUAL TO }
IS =
{ identifier-2 literal-1 arithmetic
expression-1 } }

[ { data-name-2 condition-name-2
{ IS EQUAL TO }
IS =

{ identifier-3 literal-2 arithmetic


expression-2 } } ]
{ imperative statement-2 }

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.

The OCCURS clause with format 2 is:

DATA-FIELD-1 OCCURS INTEGER TIMES


[ { ASCENDING }] KEY IS data-name-1
DESCENDING
[data-name-2] … ]

[ INDEXED BY index-name-1 [ index-name-2.] … ]


EXAMPLE:
DATA DIVISION.
FILE SECTION.
FD INPUP
LABEL RECORD IS STANDARD
DATA RECORD IS DATA-TABLE.

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.

01 THIS-RECORD PIC X (12) .


01 I PIC 9 (3) .
01 TABLE.
02 CELL PIC X (12) OCCURS 100 TIMES INDEXED BY N.

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.

The company maintains the following pay table.

Job Category Pay


1 1000.00
2 1800.00

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 & ACCEPT statement

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 .

DISPLAY “Average Grade is: “ LINE 5 COLUMN 15. .


DISPLAY AVERAGE .
DISPLAY “Average Grade is: “, AVERAGE LINE 5 COLUMN 15.

DISPLAY ( 5, 15 ) “Average Grade is “ .


DISPLAY ( 5, 40 ) AVERAGE .
DISPLAY ( 5, 15 ) “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.

Sample program #1:


* USING ACCEPT & DISPLAY *
* WITHOUT INPUT/OUTPUT FILES *

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

ENTER ANOTHER [Y/N]? Y ENTER ANOTHER [Y/N]? N

Sample Program #2:


* USING ACCEPT & DISPLAY *
* WITH OUTPUT FILE *

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.

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
ENTER ANOTHER [Y/N]? Y ENTER ANOTHER [Y/N]? Y
Sample Run 3: Sample Run 4
Enter Name: Angelie Natasha J. Atian Enter Name: Angel J. Atian

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

Output File: (GRDFILE.TXT)


STUDENT’S GRADE
STUDENT NAME FINAL GRADE

Rainah Cassandra A. Nayre 1.50


Mark Jezekiah A. Nayre 2.00
Angelie Natasha J. Atian 3.00
Angel J. Atian 2.50

Program Exercise:

GIVEN: Input data which are going to be inputted by the user.

INPUT & OUTPUT LAYOUT: (SCREEN LAYOUT)


ENTER EMPLOYEE NO.: X(5)
ENTER EMPLOYEE NAME: X(25)
RATE PER HOUR: 9(3)V99
NO. OF HOURS WORKED: 9(3)
GROSS SALARY: ZZ,999.99

GSIS CONTRIBUTION: 9(4)V99


PHILHEALTH: 9(3)V99
PAG-IBIG: 9(4)V99
WITHOLDING TAX: 9(4)V99
DEDUCTIONS: ZZ,999.99
NET PAY: ZZ,999.99

ENTER ANOTHER [YES / NO]: X (3)

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.

OUTPUT LAYOUT: (OUTPUT FILE LAYOUT)


POLYTECHNIC UNIVERSITY OF THE PHILIPPINES

PAYROLL REPORT
EMPLOYEE EMPLOYEE NET
NUMBER NAME PAY
X(5) X(25) ZZ,999.99

TOTAL NUMBER OF EMPLOYEES: ZZ,ZZ9


TOTAL ACUMULATED SALARIES: Z,ZZZ,999.99

HOW TO COMPLETE, LINK AND RUN THE COBOL PROGRAM DOSBOX

1. How to COMPILE the COBOL program


a. open the DOSbox program
Z:\>mount c: c:\  Enter key
Z:\> c: 
c: \> cd cobol 
c: \> REALCOB filename. cob  Enter key
SOURCE FILENAME:  Enter key
SOURCE LISTING:  Enter key
Pass 1
Pass 2
Pass 3
Pass 4
End of Compilation

Note: If there are errors, correct the errors first before you proceed to Step #2.

2. How to LINK the COBOL Program


a. from the DOSbox

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

3. How to RUN the COBOL Program


a. from the DOSbox
c: \ cobol> filename.exe  Enter key

104

Das könnte Ihnen auch gefallen