146
CONTENTS AT A GLANCE Importance of COBOL.............................................4 Chapter 1.......................................................5 Introduction to COBOL.........................................5 1.1 Introduction...........................................5 1.2 COBOL Coding Sheet.....................................5 1.3 Structure of a COBOL Program...........................6 1.4 IDENTIFICATION DIVISION................................6 1.5 ENVIRONMENT DIVISION...................................7 1.6 DATA DIVISION..........................................8 1.7 PROCEDURE DIVISION.....................................9 1.8 COBOL Character Set....................................9 1.9 COBOL Words...........................................10 1.10 Data names and Identifiers............................10 Chapter 2......................................................11 COBOL Data Structure.........................................11 2.1 The concept of LEVEL NUMBERS..........................11 2.2 The FILLER clause.....................................13 2.3 The DATA DESCRIPTION Entry............................14 2.4 The PICTURE Clause....................................14 2.5 The VALUE Clause......................................17 2.6 The LITERALS..........................................18 2.7 Figurative Constants..................................19 2.8 Compile and Link Edit COBOL Programs..................20 2.9 Procedure Division Structure..........................21 Chapter 3......................................................22 Basic COBOL Statements.......................................22 3.1 The DISPLAY statement.................................22 3.2 The MOVE statement....................................23 3.3 The STOP RUN statement................................23 3.4 Arithmetic Statements.................................24 3.4.3 The ROUNDED option..................................25 3.4.5 The DIVIDE statement................................26 3.4.6 The COMPUTE statement...............................26 3.5 ON SIZE ERROR clause..................................28 3.6 EDITING DATA ITEMS....................................29 3.7 The GO TO statement...................................35 3.8 The GO TO …. DEPENDING ON statement...................35 3.9 The ACCEPT statement..................................36 3.10 Using CONSOLE clause..................................37 3.11 Getting System Date and Time..........................37 SI Asia Pacific,, Singapore 1

Cobol Notes v01

Embed Size (px)

Citation preview

Page 1: Cobol Notes v01

CONTENTS AT A GLANCE

Importance of COBOL.......................................................................................4Chapter 1.........................................................................................................5

Introduction to COBOL..................................................................................51.1 Introduction.....................................................................................51.2 COBOL Coding Sheet.......................................................................51.3 Structure of a COBOL Program........................................................61.4 IDENTIFICATION DIVISION...............................................................61.5 ENVIRONMENT DIVISION.................................................................71.6 DATA DIVISION................................................................................81.7 PROCEDURE DIVISION.....................................................................91.8 COBOL Character Set......................................................................91.9 COBOL Words................................................................................101.10 Data names and Identifiers...........................................................10

Chapter 2.......................................................................................................11COBOL Data Structure................................................................................11

2.1 The concept of LEVEL NUMBERS...................................................112.2 The FILLER clause.........................................................................132.3 The DATA DESCRIPTION Entry.......................................................142.4 The PICTURE Clause......................................................................142.5 The VALUE Clause.........................................................................172.6 The LITERALS................................................................................182.7 Figurative Constants.....................................................................192.8 Compile and Link Edit COBOL Programs.......................................202.9 Procedure Division Structure.........................................................21

Chapter 3.......................................................................................................22Basic COBOL Statements............................................................................22

3.1 The DISPLAY statement.................................................................223.2 The MOVE statement....................................................................233.3 The STOP RUN statement..............................................................233.4 Arithmetic Statements..................................................................243.4.3 The ROUNDED option................................................................253.4.5 The DIVIDE statement...............................................................263.4.6 The COMPUTE statement...........................................................263.5 ON SIZE ERROR clause..................................................................283.6 EDITING DATA ITEMS.....................................................................293.7 The GO TO statement...................................................................353.8 The GO TO …. DEPENDING ON statement.....................................353.9 The ACCEPT statement.................................................................363.10 Using CONSOLE clause..................................................................373.11 Getting System Date and Time.....................................................37

Chapter 4.......................................................................................................39Conditions and Conditional Expressions.....................................................39

4.1 Introduction...................................................................................394.2 The IF statement...........................................................................394.3 The CONDITION NAMES.................................................................414.4 The Sign Condition........................................................................424.5 The Class Condition.......................................................................43

SI Asia Pacific,, Singapore 1

Page 2: Cobol Notes v01

4.6 The EVALUATE statement.............................................................444.7 The CONTINUE and NEXT SENTENCE............................................47

Chapter 5.......................................................................................................49Loop Control Statements............................................................................49

5.1 The PERFORM Statement..............................................................495.2 The Inline PERFORM statement.....................................................525.3 TEST BEFORE and TEST AFTER options.........................................535.4 The EXIT Statement......................................................................54

Chapter 6.......................................................................................................56More on Data Items....................................................................................56

6.1 The REDEFINES clause......................................................................566.2 The RENAMES clause....................................................................576.4 The INITIALIZE statement..............................................................58

Chapter 7.......................................................................................................59Table Handling............................................................................................59

7.1 Introduction...................................................................................597.2 What is a Table?............................................................................597.3 How to define Table?....................................................................597.4 MULTI-DIMENTIONAL TABLES (ARRAYS)........................................637.5 The INDEXED Tables.....................................................................667.6 The SET Verb.................................................................................677.7 Table of variable size....................................................................697.8 OCCURS with ASCENDING/DESCENDING clause............................70

Chapter 8.......................................................................................................71More on Table Handling..............................................................................71

8.1 Introduction...................................................................................718.2 The SEARCH Verb..........................................................................718.3 Searching a Multi-dimensional Table............................................758.4 BINARY SEARCH............................................................................75

Chapter 9.......................................................................................................77Handling Strings.........................................................................................77

9.1 Introduction...................................................................................779.2 The INSPECT VERB........................................................................779.3 STRING AND UNSTRING VERBS.....................................................81

Chapter 10.....................................................................................................86Subroutines................................................................................................86

10.1 Introduction...................................................................................8610.2 The CALL Statement.....................................................................86

Chapter 11.....................................................................................................88File Handling...............................................................................................88

11.1 Introduction...................................................................................8811.2 Sequential File Handling...............................................................8811.3 Processing Variable length record.................................................9311.4 Generating reports........................................................................94

Chapter 12.....................................................................................................97SORT and MERGE........................................................................................97

12.1 The SORT Statement.....................................................................9712.2 The MERGE Statement..................................................................99

Chapter 13...................................................................................................101Direct File Handling..................................................................................101

SI Asia Pacific,, Singapore 2

Page 3: Cobol Notes v01

13.1 INDEXED SEQUENTIAL and RELATIVE FILES................................10113.2 Handling INDEXED SEQUENTIAL Files (KSDS)..............................10113.3 Handling RELATIVE FILES (RRDS)................................................106Appendix A: Examples...........................................................................111Appendix B: VSAM File Status Codes.....................................................115Appendix C: References........................................................................117

SI Asia Pacific,, Singapore 3

Page 4: Cobol Notes v01

Importance of COBOL

COBOL (Common Business Oriented Language) is very powerful multi-purpose language. According to the COBOL experts, the number of lines of COBOL application code ranges from 200 billion to 5 trillion. "COBOL won't go away any time soon," Duggan says. He estimates that out of a group of approximately 2 million COBOL programmers worldwide, 100,000 per year will disappear through natural attrition. "Not many new people are entering that pool.".

"COBOL has a place," Nicholson says. "Companies can reduce their time to market by keeping their expertise in-house and reduce their risk by using proven COBOL applications." 

(http://www.cobolwebler.com/life_after.htm).

SI Asia Pacific,, Singapore 4

Page 5: Cobol Notes v01

Chapter 1

Introduction to COBOL

1.1 Introduction

COBOL is an acronym which stands for Common Business Oriented Language. As the name indicates, the target area of COBOL applications is for developing business applications. It is not designed for developing systems programs. You would not see any operating system or compiler developed in COBOL. It is a very powerful high-level language. It was developed in late 1950’s by a committee called CODASYL (Conference On Data System Language). COBOL is one of the oldest languages in use.

Today, the typical enterprise application consists of thousands of COBOL programs running on an IBM mainframe computer. Also, there are hundreds of programs run under a control system known as CICS (Customer Information Control System) to enable the workstations or PCs to use those applications.

COBOL, with its English-like structure, is a very easy language to develop applications. COBOL uses structural concepts normally associated with English prose such as division, section, paragraph, sentence and so on. As a result COBOL programs tend to be verbose. Some implementations require the program text to adhere to certain, archaic, formatting restrictions.

1.2 COBOL Coding Sheet

COBOL is a high-level language and therefore a COBOL source program must be written in a format acceptable to the COBOL compiler. Precisely for this reason, COBOL programs are written on COBOL coding sheets, which use a standard format. There are 80 characters positions on each line of the coding sheet and these positions are grouped into the following five fields:

Positions Field

1 – 6 Sequence7 Indicator8 – 11 Area A or Margin A12 – 72 Area B or Margin B73 – 80 Identification or Comment

Positions 8 to 72 actually contain the COBOL code. This area is divided into two fields – area A and area B (also known as margin A and margin B). COBOL requires that some of the entries must begin in area A and others must be confined to area B only. Area A entries can be continued into area B, if required.

The sequence field may be used to assign sequence numbers to the coding lines. This filed is optional and, if desired, may be left unused. When used, the sequences number must be in the ascending order but need not be consecutive. Usually, page number is writing in the first three positions (1 to 3) and line numbers are written in the remaining three positions (4 to 6).

SI Asia Pacific,, Singapore 5

Page 6: Cobol Notes v01

The COBOL compiler, in addition to its normal work, can optionally produce a printed copy of the source program being compiled. This copy is known as source listing. Anything written in the identification (comment) field will be ignored by the compiler but will appear in the source listing.

The indicator field may contain an asterisk (*), a slash (/), or a hyphen (-). An asterisk (*) or a slash (/) denotes that the line under consideration is a comment line. The comment line is ignored by the compiler, but it appears in the source listing. The programmer is free to write anything in a comment line, but generally notes indicating the intentions of the programmer are included as comment lines. A comment line can appear anywhere after the first line of the COBOL program. The difference between an asterisk (*) and slash (/) is that in the case of the latter, the comment line will be printed after page ejection (i.e., after skipping to the top of the next page). No such page ejection will take place in the case of an asterisk (*). The use of hyphen (-) indicates that the current line a continuation line.

1.3 Structure of a COBOL Program

COBOL programs are divided into:

a) Divisionsb) Section (s)c) Paragraph(s)d) Sentence(s)e) Statement(s)f) Word(s)

The DIVISIONS are used to identify the principal components of the application program. There are four DIVISIONS.

1) IDENTIFICATION DIVISION.2) ENVIRONMENT DIVISION.3) DATA DIVISION.4) PROCEDURE DIVISION.

Although some of the divisions may be omitted the sequence in which the DIVISIONS are specified is fixed and must follow the pattern shown above.

1.4 IDENTIFICATION DIVISION

The IDENTIFICATION DIVISION is used to supply information about the program to the programmer and to the compiler. In other words, it is used to identify the program. Most of the entries, except the PROGRAM-ID, in the IDENTIFICATION DIVISION are directed at the programmer and are treated by the compiler as comments. Every COBOL program must have a PROGRAM-ID. It is used to enable the compiler to identify the program.

The paragraphs other than PROGRAM-ID can be ignored. This division contains following paragraphs.

IDENTIFICATION DIVISION. PROGRAM-ID. NameOfProgram.[AUTHOR. ProgrammerName.][INSTALLATION. Entry.]

SI Asia Pacific,, Singapore 6

Page 7: Cobol Notes v01

[DATE-WRITTEN. Date1.][DATE-COMPILED. Date2.][SECURITY. Entry.][REMARK. Entry]

The paragraph name PROGRAM-ID is a keyword. It must be specified immediately after the division header. The program name can be up to 8 characters long.

Note: It is to be noted that this division does not contain any sections.

1.5 ENVIRONMENT DIVISION

It describes to the compiler the environment in which the program will run. It contains several sections. The most important sections are CONFIGURATION SECTION and INPUT-OUTPUT SECTION.

ENVIRONMENT DIVISIONCONFIGURATION SECTION.SOURCE-COMPUTER. source-computer-entry.OBJECT-COMPUTER. object-computer-entry.[SPECIAL NAMES. special-names-entry].[INPUT-OUTPUT SECTION.FILE-CONTROL. {file-control-entry }

1.5.1 CONFIGURATION SECTION

This section contains an overall specification of the computer used for the purpose of compilation and execution of the program. There are in all three paragraphs in this section.

(a) SOURCE-COMPUTER

This paragraph specifies the name of the computer used to compile the COBOL program. The following shows the syntax for this paragraph.

SOURCE-COMPUTER. computer-name.

(b) OBJECT-COMPUTER

The OBJECT-COMPUTER paragraph describes the computer on which the program is to be executed. The following shows the syntax for this paragraph.

OBJECT-COMPUTER. computer-name.

(c) SPECIAL-NAMES

This paragraph is used to relate some hardware names to user-specified mnemonic names. This paragraph is optional in all compilers. The following is the format of this paragraph.

SPECIAL-NAMES. [, CURRENCY SIGN IS literal-1]

SI Asia Pacific,, Singapore 7

Page 8: Cobol Notes v01

[, DECIMAL-POINT IS COMMA]

The CURRENCY SIGN is used to change the default currency sign from $ to any other character. The DECIMAL-POINT is used to change the default decimal point symbol from period to comma.

1.6 DATA DIVISION.

As the name suggests, the DATA DIVISION is used to provide the descriptions of most of the data to be processed by the program.

The DATA DIVISION is divided into three main sections;

FILE SECTION.WORKING-STORAGE SECTION.LINKAGE SECTION.

The FILE SECTION is used to describe most of the data that is sent to, or comes from, the computer’s peripherals.

The WORKING-STORAGE SECTION is used to describe the general variables used in the program.

The DATA DIVISION has the following structure:

DATA DIVISION.

FILE SECTION.

FD <file-name> <file descriptions>

WORKING-STORAGE SECTION

<Working storage section entries>

LINKAGE SECTION.

<Linkage section entries>

1.7 PROCEDURE DIVISION

The PROCEDURE DIVISION is where all the data described in the DATA DIVISION is processed and produced. It is here that the programmer describes his algorithm.

The PROCEDURE DIVISION is hierarchical in structure and consists of Sections, Paragraphs, Sentences and Statements.Only the Section is optional. There must be at least one paragraph, sentence and statement in the PROCEDURE DIVISION.

SI Asia Pacific,, Singapore 8

Page 9: Cobol Notes v01

In the PROCEDURE DIVISION paragraph and section names are chosen by the programmer. The names used should reflect the processing being done in the paragraph or section.

Sections

A section is a block of code made up of one or more paragraphs. A section begins with the section name and ends where the next section name is encountered or where the program text ends. A section name consists of a name devised by the programmer or defined by the language followed by the word SECTION followed by a full stop.

SalaryProcess SECTION.

Sentences and Statements.A paragraph consists of one or more sentences.

A sentence consists of one or more statements and is terminated by a full stop.

e.g. MOVE WS-NO TO WS-NO-E MOVE WS-I TO WS-INDEX.

A statement consists of a COBOL verb and an operand or operands.

e.g. MOVE WS-A TO WS-NO ADD 1 TO WS-NO SUBTRACT PF FROM SALARY

1.8 COBOL Character Set

Since COBOL is a language, we must begin its study with the alphabet. The alphabet of COBOL is called the character set. The following characters are available in COBOL.

0-9 (10 numerals)A-Z(26 English letters – only capital letters)

(Space or blank – sometimes denoted by b)- (Minus sign or hyphen)+ (Plus sign)* (Asterisk)/ (Slash)= (Equal)$ or £ (Currency sign), (Comma); (Semi colon). (Period or decimal point)“ (Quotation mark)( (Left parenthesis)) (Right parenthesis)> (Greater than symbol)< (Less than symbol)

The above characters are often grouped for convenience of reference. The characters 0-9 are called numeric characters or digits. The characters A-Z are called letters and the remaining characters are called special characters. Generally upper case and lower case letters are treated as the same.

SI Asia Pacific,, Singapore 9

Page 10: Cobol Notes v01

1.9 COBOL Words

A COBOL Word must be formed from A to Z, 0 to 9 and/or – (hyphen).

A word must conform to the following rules:

a) The maximum length of a word is 30.b) A word generally starts with an alphabet.c) No blank and special characters except a hyphen (-) allowed.d) A word cannot begin or end with a hyphen.

Examples

Valid Word Invalid WordGROSS-SALARY -SALARY (as it starts with a hyphen)

PAYEMENT-AMOUNT PAYEMENT AMOUNT (There is a blank space)

AGE-OF-THE-STUDENT 1-2-3 (No letter)

A COBOL word can be either a user-defined word or reserved word. These reserved words are used in COBOL statements and entries for specific purposes.

1.10 Data names and Identifiers

A data name is nothing but a variable in COBOL. A data name gives reference to the storage space in the memory where the actual value is stored. This value takes part in the operation when that particular data name s used in the program. In certain cases a data name has to be qualified by another data name or can be indexed or subscripted. A data name must be a user-defined word and cannot be a reserved word.

Examples

Valid Data Names Invalid Data Names

TOTAL-HOURS DIVISION (Reserved word)EMPLOY-NUMBER EMPLOY NAME (Space in between)AGE1 102 (No letter)

Chapter 2

COBOL Data Structure

2.1 The concept of LEVEL NUMBERS

The concept of level number is used to declare data items in COBOL. The available level numbers are 01 through 49, 66, 01 and 88. You can use any or all of these level number as when required.

Why level numbers are used?

SI Asia Pacific,, Singapore 10

Page 11: Cobol Notes v01

The data to be processed are internally stored in a specific area in the memory location in a computer. The area corresponding to a particular data item is referenced by the data name (variable) specified in the description. The data names are user-defined words and not reserve words. Reserve words are nothing but the COBOL key words such as DISPLAY, ACCEPT, OPEN, IN etc. It is to be noted that while the data name actually stands for a particular area in the memory, it is the content of the area that takes part in the operation when referred to by the specified data name in the PROCEDURE DIVISION statements.

In COBOL there is a difference between elementary and group item. In order to declare both elementary and group item, you will have to use level numbers. Usually a few elementary data items will be combined to form a group item. For example, DAY, MONTH and YEAR may be three elementary data items. These may be combined to form a group data named DATE. The organization may be shown pictorially as follows:

DATE

DAY MONTH YEAR

It may be noted that the memory space referred to by the group item is the combined memory space taken by the elementary data items. Therefore the memory space required for the DATE is the combined memory space required for DAY, MONTH and YEAR. The advantage of such a grouping is that the programmer can refer to the individual elementary items, say DAY, MONTH, and YEAR or to the group item DATE.

To describe the data structure described above, the concept of level number is used in COBOL. A level number is a two-digit number starting from 01 and it is highest-level number in the level structure. Single digit numbers are usually written as a two-digit number by prefixing with a 0. Thus the level number 1 (one) is used as 01, 2 is used as 02, etc. The higher most group must have the level number 01. The first subdivisions can have any level number between 02 and 49. Note that the lowest level number this level structure is 49 and not 01. If you define a data item with level number 02 that will consider as the sub element of the data item defined with the level number 01, and that defined with level number 03 will consider as the sub element of the data item specified with level number 02 and so on. From this it is clear that subdivisions should follow the same range with the restriction that an item cannot have a level number less than or equal to the level numbers of the group that may include it. Thus a group includes all elementary data or smaller groups beneath it until a level number equal to or less than the level number of the said group is encountered.

Examples:

The above mentioned element structure can be defined as follows.

01 DATE02 DAY02 MONTH02 YEAR

Here, the group element DATE is declared with level number 01 and the sub elements with 02. The sub elements DAY, MONTH and YEAR have the same level

SI Asia Pacific,, Singapore 11

Page 12: Cobol Notes v01

number. There is no restriction that you must use the next level number for sub elements. You can use 03, 04 etc also. For example, the above level structure can be rewritten as follows:

01 DATE05 DAY05 MONTH05 YEAR

Let us see another example, where we want to define a data structure to store the details of all employees.

01 EMPLOY-DETAILS.03 EMPLOY-ID03 EMPLOY-NAME

05 EMPLOY-FIRST-NAME05 EMPLOY-LAST-NAME

03 EMPLOY-BIRTH-DATE03 EMPLOY-JOIN-DATE03 EMPLOY-SALARY

In the above example, the EMPLOY-DETAILS is the group data item. The fields EMPLOY-FIRST-NAME and EMPLOY-LAST-NAME are the sub elements of EMPLOY-NAME. The above data structure can be further expanded to include more details. Consider the following example.

01 EMPLOY-DETAILS.03 EMPLOY-ID03 EMPLOY-NAME

05 EMPLOY-FIRST-NAME05 EMPLOY-LAST-NAME

03 EMPLOY-BIRTH-DATE03 EMPLOY-JOIN-DATE03 EMPLOY-SALARY

05 EMPLOY-BASIC05 EMPLOY-DA05 EMPLOY-HRA

03 EMPLOY-DEDUCTIONS 05 EMPLOY-PF 05 EMPLOY-ITAX

In the above data structure the highest level is EMPLOY-DETAILS and it has 6 sub elements (those specified with level number 03). The data item EMPLOY-NAME and EMPLOY-DEDUCTIONS have two sub elements each. The data item EMPLOY-SALARY has three sub elements.

It is very important to note that COBOL does not require this type of level structure unless you would like to declare record structure like this. You may also define individual elementary data item by using level number 01. i.e. the level number 01 can be used to declare both elementary and group data items. Consider the following example.

01 EMPLOY-ID.01 EMPLOY-NAME.01 EMPLOY-SALARY.

SI Asia Pacific,, Singapore 12

Page 13: Cobol Notes v01

The above defined data items are individual elementary data items and not group item. This is because we have used the same level number 01 here. However you cannot use other level numbers, 02 to 49, to declare elementary data items. i.e. the following declaration is wrong.

02 EMPLOY-ID.02 EMPLOY-NAME.02 EMPLOY-SALARY.

Besides 01 through 49, we have other level numbers like 66, 77 and 88. The level number 77 is used to define elementary data item. Where as the numbers 66 and 88 has separate uses. It is explained in this note later. The level number 77 can be used as follows.

77 EMPLOY-ID.77 EMPLOY-NAME.77 EMPLOY-SALARY.

Note that you cannot use 77 to define group data items.

2.2 The FILLER clause

Sometimes, in a hierarchical data structure such as explained above, the programmer might not require a data item to be referred to in the PROCEDURE DIVISION. Such a situation usually arises when a group and only some of its subdivisions are to be used in the program. The remaining subdivisions need not be used explicitly. In such situations the word FILLER may be used to name the elementary data to which the programmer does not wish to assign a specific name. The advantage of FILLER clause is that it can be used as many times as is required.

Example:

01 EMPLOY-DETAILS.03 EMPLOY-ID03 EMPLOY-NAME

05 EMPLOY-FIRST-NAME05 EMPLOY-LAST-NAME

03 FILLER03 EMPLOY-JOIN-DATE03 FILLER

05 EMPLOY-BASIC05 FILLER05 EMPLOY-HRA

2.3 The DATA DESCRIPTION Entry

In the previous section we have seen how to declare data items, both elementary and group. Now we need to describe the data item. The description of the data item includes its size, type, initial value etc. You can describe a data item in the data description entry. It consists of a level number, data name (or FILLER) followed

SI Asia Pacific,, Singapore 13

Page 14: Cobol Notes v01

by a number of other clauses terminated by a period. The purpose of an individual clause is to specify certain characteristics of the data item being described. The important clauses that are used to describe a data item are the PICTURE clause and the VALUE clause.

2.4 The PICTURE Clause

The PICTURE clause describes the general characteristics of an elementary data item. These characteristics include the size and type of the data item. These characteristics are described below.

(a) Class

COBOL is not so popular for data classes. It has only three classes – numeric, alphabetic or alphanumeric. As indicated by these names, the numeric items consist only of digits 0 to 9 and the alphabetic items consist only of the letters A to Z and the space (blank) character. The alphanumeric items may consist of digits, letters as well as special characters.

(b) Sign

A numeric data item can be signed or unsigned. Implicitly, a numeric data is considered as unsigned data items and is treated as positive quantities. However, an operational sign can be specified in the PICTURE clause to describe a signed data item. It is important to note that internally, the operational sign is not stored as the zone bits of the leftmost or rightmost digit position of the data item.

(c) Point Location

The position of the decimal point is another characteristic that can be specified in the case of numeric data items. If the point location is not specified, the item is considered to be an integer. In order to store number with decimal places you will have to specify the point location while declaring the data item. It is also very important to note that in COBOL the decimal point is not explicitly included in the data. The position of the decimal point is merely an assumed position. The compiler at the time of compilation only makes a note of this assumed decimal point. It generates the object code in such a way that the data items before taking part in the operations are aligned according to their assumed decimal points. So, obviously the decimal point will increase the actual size of the data item.

(d) Size

Size is another characteristic, which specify the number of characters or digits required to store the data item in the memory. The four general characteristics of the data item described above can be specified through a PICTURE clause. So generally we can say that the size and type of the data item is specified by using the PICTURE clause. You may use either the word PICTURE or its shot form PIC while defining the data item.

Format:

PICTURE[ IS ] character-string

PIC

SI Asia Pacific,, Singapore 14

Page 15: Cobol Notes v01

The character string can consist of 1 to 30 code characters that define the above-mentioned attributes of the elementary item. The word IS is optional. The code characters and their interpretations are given below.

Code character Meaning

9 Each occurrence of this code in the picture string indicates that the corresponding character position in the data itemcontains a numeral.

X Each occurrence of this code indicates that the corresponding character position in the data item contains any allowable character from the COBOL character set.

A Each occurrence of this code indicates that the corresponding character position in the data item contains only a letter or space character.

V The occurrence of this in a picture stringindicates the position of the assumed decimal point.

P The occurrence of this indicates the position of the assumed decimal point when the point lies outside the data item.

S The occurrence of this indicates that the data item is signed.

There is no special code to indicate the size. The total number of occurrences of 9, X or A in the picture string indicates the size. The occurrences of V, P and S are not counted in determining the size of an item.

The allowable combinations are governed by the following rules:

a) In the case of an alphabetic item the picture may contain only the symbol A.b) In the case of a numeric item the picture may contain only the symbols 9, V, P

and S. These are called operational characters. It must contain at least one 9. The symbols V and S can appear only once and S, if it is included, must be the leftmost character of the picture string. The symbol P can be repeated on the right or on left (but not on the left of S) as many times as is required to indicate the position of the assumed decimal point.

c) In the case of an alphanumeric item, the picture may contain all Xs or a combination of 9, A and X (except all 9 or all A). in the latter case the item is considered as if the string consists of all Xs.

The PICTURE clause is only to be specified for elementary items; it cannot be used for a group item. The size of a group item is equal to the total of the sizes of all subordinate elementary items. The class of a group item is alphanumeric.

SI Asia Pacific,, Singapore 15

Page 16: Cobol Notes v01

The following examples illustrate the PICTURE specification.

Example1:

01 EMPLOY-SALARY PICTURE IS S999V99

01 EMPLOY-SALARY PICTURE S999V99

01 EMPLOY-SALARY PICTURE IS S9(3)V99

01 EMPLOY-SALARY PICTURE S9(3)V9(2)

01 EMPLOY-SALARY PIC S9(3)V99

Example2:

77 EMPLOY-DEPT PIC XXXXX.

Means that the data is alphanumeric with a size of 5 characters.

Example3:

01 EMPLOY-DETAILS.03 EMPLOY-ID PIC 9(5).03 EMPLOY-NAME

05 EMPLOY-FIRST-NAME PIC X(15).05 EMPLOY-LAST-NAME PIC X(15).

03 FILLER PIC X(4).03 EMPLOY-JOIN-DATE PIC 9(8).03 FILLER

05 EMPLOY-BASIC PIC S9(5)V99.05 FILLER PIC X(5).05 EMPLOY-HRA PIC S9(4)V99.

In the above data structure the actual size of the record EMPLOY-DETAILS is the total size of all its subordinate elements.

2.5 The VALUE Clause

The VALUE clause defines the initial value of a data item. Normally the initialization is done just before the first statement in the PROCEDURE DIVISION is executed.

Format:

VALUE [ IS ] literal

The literal can be any numeric value, a nonnumeric string of characters included within quote (single or double) or any figurative constant. However, the class of the literal must be compatible with that of the data item as specified through the PICTURE clause.

Examples:

SI Asia Pacific,, Singapore 16

Page 17: Cobol Notes v01

VALUE IS 120.70.VALUE IS “INDIA”.VALUE ‘COBOL TRAINING’.VALUE ZERO.

The above examples illustrate how a numeric, numeric or figurative constant can be specified as a value. Note that the non-integer numeric literals must appear with a decimal point (.).

Usually, the value clause is used in the WORKING-STORAGE SECTION to define the initial value of a data item. If a VALUE clause is used at a group level, it should not be used for any item within the group. Only nonnumeric literals and figurative constants can be used to specify the value of a group item. The VALUE clause must not be used for items defined in the file section except in the case of condition names. We will discuss condition names later.

Examples:

05 WS-NUMBER PIC S9(5)V99 VALUE -300.50.

The following example shows the declaration of the data items in a COBOL program.

000001 IDENTIFICATION DIVISION. 000002 PROGRAM-ID. LAB01. 000003 ENVIRONMENT DIVISION. 000004 DATA DIVISION. 000005 WORKING-STORAGE SECTION. 000006 01 WS-EOF PIC X VALUE 'N'. 000007 01 WS-EMP-PAN-NO PIC X(5). 000008 01 WS-FSTAT PIC X(2) VALUE ‘00’. 000009 PROCEDURE DIVISION. 000010 0000-MAIN. 000011 <Procedure division statements….>

2.6 The LITERALS

Instead of a data name sometimes the actual values can also appear in the program. Such values are known as literals. For example, the statement MOVE 7500.00 TO WS-TOTAL-AMOUNT indicates that the value 7500.00 will be moved to WS-TOTAL-AMOUNT. Here the constant 7500.00 is a literal. A data name may have different values at different points of time whereas a literal means the specific value which remains unchanged throughout the execution of the program. For this reason a literal is often called constant. There are two types of literals; numeric and nonnumeric.

(a) Numeric

SI Asia Pacific,, Singapore 17

Page 18: Cobol Notes v01

A numeric literal can be formed with the help of digits only. There may also be a sign (plus or minus) and/or a decimal point. If there is a sign, it must appear as the leftmost character of the literal and there must not be any blank space between the sign and the first digit. If a decimal point is used, it must not be the last character of a literal as a decimal point (or period) is also used to mark the end of a COBOL statement. If there is no decimal point, it is assumed to be an integer. If the sign is not mentioned, the literal is treated as positive. The maximum number of digits allowed in a numeric literal varies from compiler to compiler. Generally a numeric literal can have a maximum of 18 digits.

(b) Nonnumeric

In general, a nonnumeric literal is used to output messages or headings. A nonnumeric literal is composed of characters which are enclosed within quotation marks. The restriction on nonnumeric literal is that within two quotation marks there can be any character except another quotation mark. The maximum number of characters that are allowed within two quotation marks is again compiler dependent. Generally the maximum number of characters in a nonnumeric literal is 120. You may use single or double quotes.

Examples:

(i) Valid Numeric Literal (ii) Invalid Numeric Literals

0.12 “12345” (invalid as numeric literal)

525.75 - 500 (there is a blank space)

-150.2 232467821546789.234568923 (the total number of digits is more than the acceptable number)

(iii) Valid Nonnumeric Literal

‘INDIA’“PROCEDURE DIVISION”‘EMPLOY NAME’“4500.50”‘PERFORM’

(iv) Invalid Nonnumeric Literal

10 MOVE”‘125.90‘EMPLOY

2.7 Figurative Constants

There is another type of literal in COBOL known as the figurative constant. These are literals representing values that may be frequently used by most programs. These are given some fixed names and when the compiler recognizes these names it sets up the corresponding values in the object program.

SI Asia Pacific,, Singapore 18

Page 19: Cobol Notes v01

There are numeric and nonnumeric representation of figurative constants.

Figurative Constants MeaningZEROZEROSZEROES

Represents the value 0 (zero). Depends on the context one or more 0s.

SPACESPACES

Represents one more spaces or blanks.

HIGH-VALUEHIGH-VALUES

Represents the highest value in the collating sequence (X’FF’).

LOW-VALUELOW-VALUES

Represents the lowest value in the collating sequence (X’00’).

QUOTEQUOTES

Represents one or more quotes (‘).

ALL literal Represents one or more character string.

Examples:

77 EMPLOY-ID PIC 9(5) VALUE ZEROS.01 EMPLOY-NAME PIC X(20) VALUE SPACES.01 WS-LOW-VAL PIC X(10) VALUE LOW-VALUES.77 WS-LINE PIC X(5) VALUE ALL ‘-‘.2.8 Compile and Link Edit COBOL Programs

Since COBOL is a high level language it needs compilation and link edit before execution. To compile a COBOL program, there are a number of compilers available. Generally we will use IGYCRCTL to compile the COBOL program and IEWL to link edit. Usually an application developer need not write the compilation JCLs. All installations will have their own standard JCLs to compile the programs A sample COBOL compilation JCL is given below.

****** ***************************** Top of Data ******************************000001 //SGTRG03A JOB (SGTR),'COBOL COMPILATION',CLASS=A,MSGCLASS=X, 000002 // NOTIFY=SGTRG03 000003 //STEP1 EXEC CBLMVS, 000004 // LOADLIB='SGTRG03.BATCH.LOADLIB', 000005 // LKEDLIB1='SGTRG03.BATCH.LOADLIB', 000006 // MEMBER='COBPGM' 000007 //SYSIN DD DSN=SGTRG03.BATCH.SRC(COBPGM),DISP=SHR ****** **************************** Bottom of Data ****************************

In the above JCL, the procedure CBLMVS is called to compile and link edit the COBOL program. The source program is passed through the SYSIN DD statement as a member of partitioned dataset. Here, COBPGM is the source program. Internally this procedure is calling IGYSRCTL and IEWL programs to compile and link edit the COBOL program. The expanded version of CBLMVS procedure is given below.

XXCBLMVS PROC SYSOUT='*', XX LKEDLIB1='PROJ2.LOADLIB', XX LKEDLIB2='PROJ2.LOADLIB', XX LKEDLIB3='PROJ2.LOADLIB', XX LKEDLIB4='PROJ2.LOADLIB', XX COPYBK1='SIGS.COBOL.SPS.COPYBOOK', XX COPYBK2='NULLFILE', XX LOADLIB=, XX DEBUGDSN='NULLFILE', XX APPLLOAD='PROJ2.LOADLIB',

SI Asia Pacific,, Singapore 19

Page 20: Cobol Notes v01

XX COBPARM=, XX MEMBER= XXMVSCOB EXEC PGM=IGYCRCTL, XX PARM=(APOST,C,LC(57),BUF(12288),LIB,RENT,DATA(31), XX TRUNC(BIN)&COBPARM) IEFC653I SUBSTITUTION JCL - PGM=IGYCRCTL,PARM=(APOST,C,LC(57),BUF(1228XXSTEPLIB DD DSN=IGY.V1R2M0.SIGYCOMP,DISP=SHR XXSYSPRINT DD SYSOUT=&SYSOUT IEFC653I SUBSTITUTION JCL - SYSOUT=* XXSYSLIB DD DISP=SHR,DSN=&COPYBK1 IEFC653I SUBSTITUTION JCL - DISP=SHR,DSN=SIGS.COBOL.SPS.COPYBOOKXX DD DISP=SHR,DSN=&COPYBK2 IEFC653I SUBSTITUTION JCL - DISP=SHR,DSN=NULLFILE XXSYSUT1 DD DSN=&&WORK01,UNIT=SYSDA,SPACE=(CYL,(5,2)) XXSYSUT2 DD DSN=&&WORK02,UNIT=SYSDA,SPACE=(CYL,(5,2)) XXSYSUT3 DD DSN=&&WORK03,UNIT=SYSDA,SPACE=(CYL,(5,2)) XXSYSUT4 DD DSN=&&WORK04,UNIT=SYSDA,SPACE=(CYL,(5,2)) XXSYSUT5 DD DSN=&&WORK05,UNIT=SYSDA,SPACE=(CYL,(5,2)) XXSYSUT6 DD DSN=&&WORK06,UNIT=SYSDA,SPACE=(CYL,(5,2)) XXSYSUT7 DD DSN=&&WORK07,UNIT=SYSDA,SPACE=(CYL,(5,2)) XXSYSLIN DD DSN=&&WORK08,UNIT=SYSDA,DISP=(,PASS), XX DCB=BLKSIZE=80,SPACE=(CYL,(10,4)) XXSYSPUNCH DD DUMMY //SYSIN DD DSN=SGTRG03.BATCH.SRC(COBPGM),DISP=SHR X/SYSIN DD DDNAME=SYSIN XX*====================================================== XXLKED EXEC PGM=IEWL,COND=(5,LT,MVSCOB), XX PARM='LET,LIST,MAP,XREF,SIZE=(384K,96K),RMODE=ANY,AMODE=31XXSYSPRINT DD SYSOUT=&SYSOUT IEFC653I SUBSTITUTION JCL - SYSOUT=* XXSYSUT1 DD DSN=&&WORK09,UNIT=SYSDA,SPACE=(CYL,(10,4)) XXSYSLMOD DD DISP=SHR,DSN=&LOADLIB(&MEMBER) IEFC653I SUBSTITUTION JCL - DISP=SHR,DSN=SGTRG03.BATCH.LOADLIB(PGM1)

2.9 Procedure Division Structure

The procedure division consists four categories of statements: Imperative statement, Conditional statement, Compiler-directing statement and Delimited scope statements.

(a) Imperative Statements

An imperative statement specifies that an unconditional action is to be taken. The imperative statements are used along with AT END, NOT AT END clauses. Also, an arithmetic statement without ON SIZE ERROR is an imperative statement.

Example: READ EMP-FILE AT END MOVE ‘Y’ TO WS-EOF.

In the above example the statement MOVE ‘Y’ TO WS-EOF is an imperative statement.

(b) Conditional Statements

A conditional statement is either a simple conditional statement (IF, EVALUATE, SEARCH) or a conditional statement made up of an imperative statement that includes a conditional phrase or option.

SI Asia Pacific,, Singapore 20

Page 21: Cobol Notes v01

For example, an arithmetic statement with the conditional option ON SIZE ERROR and without a scope terminator is a conditional statement.

(c) Compiler-Directing Statements

A compiler-directing statement is not part of the program logic. Compiler-directing statements inform the compiler about the program structure, copy processing, listing control, and control flow. For example COPY statement is a compiler-directive statement.

(d) Delimited Scope Statements

In general, a delimited scope statement uses an explicit scope terminator to turn a conditional statement into an imperative statement; the resulting imperative statement can then be nested. Explicit scope terminators may also be used, however, to terminate the scope of an imperative statement and clearly end the statement.

For example END-IF, END-PERFORM, END-READ, etc. are scope terminators.

SI Asia Pacific,, Singapore 21

Page 22: Cobol Notes v01

Chapter 3

Basic COBOL Statements

3.1 The DISPLAY statement

The DISPLAY statement is used to display the value of an identifier or literal. Usually the output will be displayed on the system output queue.

Format:

DISPLAY id1 [id2 lit1 lit2 …]

Example:

DISPLAY ‘HELLO’.

DISPLAY WS-AMT WS-NAME.

DISPLAY 100.

The following program will display the sentence “THIS IS MY FIRST COBOL PROGRAM”.

000001 IDENTIFICATION DIVISION. 000002 PROGRAM-ID. LAB02. 000003 ENVIRONMENT DIVISION. 000004 DATA DIVISION. 000005 PROCEDURE DIVISION. 000006 00000-MAIN. 000007 DISPLAY 'THIS IS MY FIRST COBOL PROGRAM'. 000008 STOP RUN.

Use the following JOB to compile the above program.

000001 //INTRG02A JOB (LAB01),'COBOL COMPILATION',CLASS=A,MSGCLASS=X, 000002 // NOTIFY=&SYSUID,TIME=(0,20) 000003 //* THIS IS COBOL COMPILE JCL 000004 //STEP1 EXEC CBLMVS, 000005 // LOADLIB='INTRG02.BATCH.LOADLIB', 000006 // MEMBER='LAB01’ 000007 //SYSIN DD DSN=INTRG02.COBOL.SAMPLE(SAM1),DISP=SHR

The following JOB will run the above program.

000001 //INTRG02B JOB (LAB02),'COBOL RUN',CLASS=A,MSGCLASS=X, 000002 // NOTIFY=&SYSUID,TIME=(0,10) 000003 //* THIS IS RUN JCL 000004 //STEP1 EXEC PGM=SAM1 000005 //SYSOUT DD SYSOUT=* 000006 //STEPLIB DD DSN=INTRG02.BATCH.LOADLIB,DISP=SHR 000007 // DD DSN=CEE.SCEERUN,DISP=SHR The output of the above program is given below. You will see the output in sysout

SI Asia Pacific,, Singapore 22

Page 23: Cobol Notes v01

THIS IS MY FIRST COBOL PROGRAM

3.2 The MOVE statement

The MOVE statement is used to assign a value to an identifier. You may move the value of an identifier or literal to one or more identifier(s).

Format:

MOVE id1 [lit1] TO id2 [id3 id4 …]

Example:

MOVE 100 TO WS-AMT.

MOVE WS-AMT TO WS-BAL.

MOVE 0 TO WS-AMT1 WS-AMT2.

Note that you cannot move value to a literal, i.e. the target must be a variable.

The following MOVE statement is invalid:

MOVE WS-AMT TO 1000.

You may use figurative constants in the move statement.

MOVE SPACES TO WS-NAME.

3.3 The STOP RUN statement

This statement is used to terminate a COBOL program. This should be the last executable statement in every COBOL program.

Format:

STOP RUN.

Note that STOP RUN will not be coded in sub-programs.

SI Asia Pacific,, Singapore 23

Page 24: Cobol Notes v01

What is the output of the following program?

000001 IDENTIFICATION DIVISION. 000002 PROGRAM-ID. LAB03. 000003 ENVIRONMENT DIVISION. 000004 DATA DIVISION. 000005 WORKING-STORAGE SECTION. 000006 01 WS-A PIC 9(2). 000007 01 WS-B PIC 9(2). 000008 01 WS-C PIC 9(2). 000009 PROCEDURE DIVISION. 000010 0000-MAIN. 000011 MOVE 10 TO WS-A. 000012 MOVE WS-A TO WS-B WS-C. 000013 MOVE 26 TO WS-B. 000014 MOVE WS-B TO WS-A. 000015 DISPLAY 'WS-A = ' WS-A. 000016 DISPLAY 'WS-B = ' WS-B. 000017 DISPLAY 'WS-C = ' WS-C. 000018 STOP RUN. 000019 0000-EXIT.

WS-A = ___ WS-B = ___WS-C = ___

3.4 Arithmetic Statements

COBOL provides various statements to perform arithmetic operations. They are ADD, SIBTRACT, MULTIPLY, DIVIDE and COMPUTE.

3.4.1 The ADD statement

It is used to add two or more numbers.

Format:

ADD id1 [id2.. lit1 lit2 ..] TO id3 [id4 id5 ..]

ADD id1 id2 [id3.. lit1 lit2 ..] GIVING id4

In the first format, the numbers will be added to the values in the target variable whereas in the second format the result will be stored in the target variable.

Example:

WS-AMT = 50.ADD 10 TO WS-AMT, will give the result 60.

ADD 10 20 GIVING WS-AMT, will give the result 30.

What is the output of the following program?

SI Asia Pacific,, Singapore 24

Page 25: Cobol Notes v01

000001 IDENTIFICATION DIVISION. 000002 PROGRAM-ID. LAB04. 000003 ENVIRONMENT DIVISION. 000004 DATA DIVISION. 000005 WORKING-STORAGE SECTION. 000006 01 WS-A PIC 9(3). 000007 01 WS-B PIC 9(2). 000008 01 WS-C PIC 9(3). 000009 PROCEDURE DIVISION. 000010 0000-MAIN. 000011 MOVE 10 TO WS-A. 000012 MOVE 15 TO WS-B. 000013 ADD WS-A TO WS-B. 000014 DISPLAY 'WS-A = ' WS-A, 'WS-B = ' WS-B. 000015 000016 ADD WS-A WS-B GIVING WS-C. 000017 DISPLAY 'WS-C = ' WS-C. 000018 STOP RUN. 000019 0000-EXIT.

WS-A = ___ WS-B = ___WS-C = ___

3.4.2 The SUBTRACT statement

It is used to subtract a number from another.

Format:

SUBRACT id1 [lit1] FROM id2 [id3 id4 ….]

SUBTRACT id1 [lit1] FROM 1d2 [id3 id4 lit2 …] GIVING id5.

Example:

SUBTRACT 10 FROM WS-AMT.SUBTRACT 20 FROM 50 GIVING WS-AMT.SUBTRACT 15 FROM WS-AMT GIVING WS-NUM.

3.4.3 The ROUNDED option

You can use the ROUNDED option to round a number. It is usually used in the arithmetic operations when the resulting field has less number of fractional parts than the actual result. For instance, consider the following variables:

01 WS-A PIC 9(3)V99 VALUE 250.75.01 WS-B PIC 9(2)V99 VALUE 50.52.01 WS-C PIC 9(3)V9.……….ADD WS-A WS-B GIVING WS-C.

SI Asia Pacific,, Singapore 25

Page 26: Cobol Notes v01

In the above example, the result should be 301.27. But the resulting field contains only one fractional part, the result will be truncated. So the actual result would be 301.2. In this situation we can use ROUNDED option to round the number.

ADD WS-A WS-B GICING WS-C ROUNDED.

In this case the result would be 301.3.

3.4.4 The MULTIPLY statement

It is used to multiply two or more numbers.

Format:

MULTIPLY id1 [lit1] BY id2.MULTIPLY id1 [lit1] BY id2 [lit2..] GIVING id3 [ROUNDED].

The ROUNDED option is used to round the result to the nearest value.

Example:

MULTIPLY WS-A BY WS-B.MULTIPLY 0.25 BY WS-AMT.MULTIPLY 0.15 BY WS-AMT GIVING WS-BP.MULTIPLY WS-A BY WS-B WS-C GIVING WS-D WS-F.MULTIPLY WS-AMT BY 0.25 GIVING WS-TOTAL ROUNDED.

3.4.5 The DIVIDE statement

It is used to divide a number by another number.

Format:

DIVIDE id1 [lit1] INTO id2 [id3 id4 …] REMAINDER id5.

DIVIDE id1 [lit1] BY id2 [lit2] GIVING id3 [ROUNDED] REMAINDER id4 .

Example:

DIVIDE 5 INTO WS-NO.DIVIDE 0.25 INTO WS-AMT1 WS-AMT2.DIVIDE WS-AMT BY 0.15 GIVING WS-DA REMAINDER WS-R.DIVIDE WS-A BY WS-B GIVING WS-C.DIVIDE WS-AMT BY 0.75 GIVING WS-SAL ROUNDED.

3.4.6 The COMPUTE statement

So far we have discussed various arithmetic statements to perform computations in COBOL. They are ADD, SUBTRACT, MULTIPLY and DIVIDE. You can perform all these operations by using the COMPUTE statement. You can use the following arithmetic operators with COMPUTE statement.

Operator Meaning+ Addition

SI Asia Pacific,, Singapore 26

Page 27: Cobol Notes v01

- Subtraction* Multiplication/ Division

** Exponentiation( ) Grouping

Format:

COMPUTE id1 [ROUNDED] = <expression>.

Example:

COMPUTE WS-AMT = WS-BP + (WS-BP * 0.25).COMPUTE WS-SQR = WS-NO ** 2.COMPUTE WS-SAL ROUNDED = WS-BP + WS-DA + (WS-BP * 0.15).

Note that you must leave at least one blank space before and after the arithmetic operators and equal sign. The order of preference will be parenthesis (brackets), exponentiation, multiplication and division from left to right and addition and subtraction from left to right.

What is the output of the following program?

000001 IDENTIFICATION DIVISION. 000002 PROGRAM-ID. LAB05. 000003 ENVIRONMENT DIVISION. 000004 DATA DIVISION. 000005 WORKING-STORAGE SECTION. 000006 01 WS-SAL PIC 9(5) VALUE 100. 000007 01 WS-BP PIC 9(3) VALUE 20. 000008 PROCEDURE DIVISION. 000009 0000-MAIN. 000010 COMPUTE WS-SAL = WS-SAL + WS-BP + WS-BP * 0.1. 000011 DISPLAY ‘WS-SAL = ‘ WS-SAL. 000012 000013 COMPUTE WS-SAL = (WS-SAL + WS-BP) * 0.1. 000014 DISPLAY ‘WS-SAL = ‘ WS-SAL. 000015 STOP RUN. 000016 0000-EXIT. 000017 EXIT.

WS-SAL = ____WS-SAL = ____

Complete the following program. The purpose of the program is to accept 3 numbers from SYSIN and find the sum and average.

000001 IDENTIFICATION DIVISION. 000002 PROGRAM-ID. LAB06. 000003 ENVIRONMENT DIVISION. 000004 DATA DIVISION. 000005 WORKING-STORAGE SECTION. 000006 01 WS-NUM1 PIC 9(2). 000007 01 WS-NUM2 PIC 9(2).

SI Asia Pacific,, Singapore 27

Page 28: Cobol Notes v01

000008 01 WS-NUM3 PIC 9(2). 000009 01 WS-SUM PIC 9(3). 000010 01 WS-AVG PIC 9(2). 000011 000012 PROCEDURE DIVISION. 000013 00000-MAIN. 000014 *ACCEPT THREE NUMBERS FROM SYSIN 000015 _____________________________ 000016 _____________________________ 000017 _____________________________ 000018 000019 *ADD THREE VALUES 000020 000021 ___________________________________________ 000022 000023 *USING COMPUTE TO FIND THE AVG 000024 __________________________________________________ 000025 *DISPLAY THE RESULT 000026 DISPLAY 'SUM =' WS-SUM. 000027 DISPLAY 'AVG=' WS-AVG. 000028 STOP RUN.

3.5 ON SIZE ERROR clause

You can use ON SIZE ERROR clause along with all arithmetic statements if trap size error that may occur during computation. i.e. it will prevent the error that can be occurred due to overflow.

Format:

<arithmetic operation> ON SIZE ERROR <error routine>

Example:

01 WS-A PIC 9(2) VALUE 50.01 WS-B PIC 9(2) VALUE 60.01 WS-C PIC 9(2).

ADD WS-A WS-B GIVING WS-C ON SIZE ERROR DISPLAY ‘SIZE ERROR DURING ADDITION’.

In the above example you will get the message “SIZE ERROR DURING ADDITON” as the resulting variable, WS-C, can only store two digits. The output value would be 10 instead of 110 as the variable WS-C has the picture 9(2). To correct this error you must define WS-C with picture 9(3).

What is the output of the following program?

000001 IDENTIFICATION DIVISION. 000002 PROGRAM-ID. LAB07. 000003 ENVIRONMENT DIVISION. 000004 DATA DIVISION. 000005 WORKING-STORAGE SECTION. 000006 01 WS-A PIC 9(2) VALUE 75. 000007 01 WS-B PIC 9(2) VALUE 50.

SI Asia Pacific,, Singapore 28

Page 29: Cobol Notes v01

000008 01 WS-C PIC 9(2). 000009 PROCEDURE DIVISION. 000010 0000-MAIN. 000011 ADD WS-A WS-B GIVING WS-C ON SIZE ERROR 000012 DISPLAY 'SIZE ERROR'. 000013 DISPLAY 'WS-C = ' WS-C. 000014 STOP RUN. 000015 0000-EXIT. 000016 EXIT.

If you change the value of WS-A and WS-B to 25 and 15 respectively, what would be the new output?

3.6 EDITING DATA ITEMS

Some time you may require reformatting the numeric data items before printing the report. In COBOL, you cannot reformat the number directly. In order to print any number in a specified format you must another variable with numeric editing characters and move the actual value to this new variable and print it. The characters used to edit (reformat) numbers are called numeric editing characters. COBOL support a number of editing characters, each has its own use. The important editing characters are given below. It is to be noted that the edited data names are of type character and not numeric. So you will not be able to use the numeric edited variable in arithmetic calculations.

3.6.1 Edit Characters for Numeric Data

The following characters can be used in the picture clause to indicate editing.

Z $ * - + CR DB . , B 0 (Zero) /

The numeric edit characters are explained below.

Z (Zero Suppression)

The edit character Z has the same meaning as that of a 9 in the picture except that the leading zeros in the source data, if any, in the digit positions indicated by Z will be suppressed (i.e. replaced by space characters). Note that Z cannot appear to the right of any 9.

Examples:

The following examples illustrate the use of Z editing characters. The character b is used to indicate a space character and the character ^ is used to indicate the assumed decimal point.

_______________________________________________________________

Picture of the Field Numeric Value Moved Edited Value To the Field

_______________________________________________________________

SI Asia Pacific,, Singapore 29

Page 30: Cobol Notes v01

ZZ999 01234 b1234ZZ999 00022 bb022ZZ999 1 ^ 60 bb001ZZV99 0 ^ 57 bbb57ZZZZVZZ 0 ^ 05 bbbb05ZZZZVZZ 0 bbbbbb

_______________________________________________________________

$ (Currency Sign)

A single currency sign can appear at the leftmost position of a picture. The $ character is inserted during edit.

Examples:_______________________________________________________________

Picture of the Field Numeric Value Moved Edited Value To the Field

_______________________________________________________________

$99999 123 $00123$ZZ999 921 $bb921$ZZ999 65432 $65432$**999 901 $**901

_______________________________________________________________

You may repeat the currency sign, if you want. In that case COBOL will prefix one $ sign at the left most non-zero digits. All other $ symbols will be suppressed.

Example:

$$$$$ 250 b$250

* (Asterisk)

The edit character * (asterisk) is identical to Z except that he leading zeros are replaced by asterisks instead of space characters.

Examples:_______________________________________________________________

Picture of the Field Numeric Value Moved Edited Value To the Field

_______________________________________________________________

*9999 01234 *1234

SI Asia Pacific,, Singapore 30

Page 31: Cobol Notes v01

**999 00073 **073 ______________________________________________________________

- (Minus Sign)

A minus sign can appear either at the leftmost or rightmost position of a picture. If the value of an item is negative, a minus sign will be inserted in the specified position. If the item is positive, a space character will be inserted.

Examples:_______________________________________________________________

Picture of the Field Numeric Value Moved Edited Value To the Field

_______________________________________________________________

- 9999 - 123 - 0123- 9999 123 b0123 9999 - - 123 0123 – 9999 - 123 0123b- ZZZV99 - 12 ^ 34 - b1234

_______________________________________________________________

+ (Plus Sign)

A plus sign has the same meaning as that of a minus sign except that when the item is positive a plus sign will be inserted instead of the space character. If the item is be negative, a minus sign will be inserted although there is a plus sign in the picture.

Examples:_______________________________________________________________

Picture of the Field Numeric Value Moved Edited Value To the Field

_______________________________________________________________+ 999 - 123 - 0123- 9999 123 + 0123

_______________________________________________________________

CR & DB (Credit and Debit Sign)

The two characters CR or DB symbol may appear only at the rightmost position of the picture. They are identical to the minus sign edit character. If the value is negative the symbols CR or DB will appear in the rightmost position. If the value is positive CR or DB will be replaced by two space characters.

Examples:_______________________________________________________________

Picture of the Field Numeric Value Moved Edited Value To the Field

_______________________________________________________________

9999CR -1234 1234CR

SI Asia Pacific,, Singapore 31

Page 32: Cobol Notes v01

9999CR 1234 1234bb9999DB -1234 1234DB9999DB 1234 1234bb

_______________________________________________________________

. (Decimal Point)

A period may be used to insert a decimal point and may not appear more than once. Both the period and V cannot appear in the same picture. If the data item to be edited has a V specified in its picture, then an alignment of V with the specified period takes place. As a result, zeros may be inserted in the resultant edited data. If zero suppression is also specified, the period stops zero suppression on its right.

Examples:_______________________________________________________________

Picture of the Field Numeric Value Moved Edited Value To the Field

_______________________________________________________________

999.99 123 ^ 45 123.45Z99.99 12 ^ 3 bb12.30ZZ99.99 123 b123.00ZZZZ.ZZ 0 bbbbbbb****.** 0 ****.**

_______________________________________________________________

, (Comma)

A comma is treated as an insertion character and inserted wherever it appears. You may use more than one comma in a picture. However, if zero suppression (including zero suppression by asterisk (*)) takes place to the right of any comma, the specified comma will also be suppressed and a space character will take its position. A comma cannot appear either as the rightmost or leftmost character in a picture.

SI Asia Pacific,, Singapore 32

Page 33: Cobol Notes v01

Examples:_______________________________________________________________

Picture of the Field Numeric Value Moved Edited Value To the Field

_______________________________________________________________

9,999 1234 1,23499,999 123 00,123ZZ,Z99 123 bbb123**,*** 12 ****12

_______________________________________________________________

B (Blank Insertion)

This character is used to insert a space (blank) character in the edited data. There can be more than one B in a picture.

Examples: _______________________________________________________________

Picture of the Field Numeric Value Moved Edited Value To the Field

_______________________________________________________________

99B99B99 123456 12b34b5699B99B99 1234 00b12b34

_______________________________________________________________

0 (Zero Insertion)

A zero appearing in a picture will be treated in the same way as a B except that 0 will be inserted instead of a space character.

Examples:_______________________________________________________________

Picture of the Field Numeric Value Moved Edited Value To the Field

_______________________________________________________________

09900 12 0120009990 123 01230

_______________________________________________________________

/ (Slash Insertion)

The edit character slash (/) may appear anywhere in the picture. If used, it will be inserted in the specified position. There can be more than one slash in the picture. Usually it is used to print

Examples: _______________________________________________________________

Picture of the Field Numeric Value Moved Edited Value To the Field

SI Asia Pacific,, Singapore 33

Page 34: Cobol Notes v01

_______________________________________________________________

99/99/99 181203 18/12/039999/99/99 20031218 2003/12/18

_______________________________________________________________

3.6.2 BLANK WHEN ZERO

BLANK WHEN ZERO is an editing clause which may be used along with a picture. This will set the entire data item to blanks if its value is equal to zero. Note that you should not use the edit character asterisk (*) along with BLANK WHEN ZERO.

Format:

BLANK WHEN ZERO

Examples:_______________________________________________________________

Picture of the Field Numeric Value Moved Edited Value To the Field

_______________________________________________________________

ZZZZ.99 BLANK WHEN ZERO 12^34 bb12.34 ZZZZ.99 BLANK WHEN ZERO 0 bbbbbb 9999.99 BLANK WHEN ZERO 0 bbbbbb_______________________________________________________________

3.6.3 Floating Insertion

The currency symbol ($), plus (+) and minus (-) can appear in multiples on the left-hand side of a picture. In this case it will be treated in the same way as the Z character and only one symbol will be inserted immediately to the left of the first non-zero digit of the data.

Examples:_______________________________________________________________

Picture of the Field Numeric Value Moved Edited Value To the Field

_______________________________________________________________

$$$$9.99 123 ^ 45 b$123.45$$$$9.99 12 bb$12.00++++.99 - 123 ^ 45 - 123.45+++.99 12 +12.00

_______________________________________________________________

You may use the edit characters together, but the following rules are applied.

a) Symbols + - CR DB and the operational character S (to indicate sign) are mutually exclusive and only one of these may appear in a picture.

b) As floating-insertion characters, $ + - * and Z are mutually exclusive.

SI Asia Pacific,, Singapore 34

Page 35: Cobol Notes v01

c) In addition to the edit characters, the picture may contain the operational characters 9 and V. However, both V and period (.) should not appear in the same picture.

d) All edit characters and the operational character 9 specified in a picture should be taken into consideration to determine the size of the edited item.

3.7 The GO TO statement

It is an unconditional branching statement. When used it will transfer the control to the specified paragraph and execute the statements within that paragraph. After the execution of all the statements in the specified paragraph the process will continue to the next statement, if not transferred to elsewhere in the program.

Format:

GO TO <paragraph-name>

Example:

GO TO 2000-READ.

3.8 The GO TO …. DEPENDING ON statement

It is used to transfer the control to a paragraph based on the value of an identifier.

Format:

GO TO <paragraph-name1, paragraph-name2, paragraph-name3, …> DEPENDING ON id1.

Example:

GO TO 1100-JAN 1200-FEB 1300-MAR 1400-APR 1500-JUN DEPENDING ON WS-MONTH.

In the above example, the control will transferred to 1100-JAN if the value of WS-MONTH is 1, 1200-FEB if the value of WS-MONTH is 2, 1300-MAR if the value of WS-MONTH is 3 and so on.

Find out the output of the following program.

000001 IDENTIFICATION DIVISION. 000002 PROGRAM-ID. LAB07. 000003 ENVIRONMENT DIVISION. 000004 DATA DIVISION. 000005 WORKING-STORAGE SECTION. 000006 01 WS-NO PIC 9(2) VALUE 2. 000007 PROCEDURE DIVISION. 000008 0000-MAIN. 000009 GO TO 1000-DISP 1100-DISP 1200-DISP 1300-DISP 000010 DEPENDING ON WS-NO. 000011 STOP RUN. 000012 0000-EXIT.

SI Asia Pacific,, Singapore 35

Page 36: Cobol Notes v01

000013 EXIT. 000014 1000-DISP. 000015 DISPLAY 'ONE'. 000016 STOP RUN. 000017 1100-DISP. 000018 DISPLAY 'TWO'. 000019 STOP RUN. 000020 1200-DISP. 000021 DISPLAY 'THREE'. 000022 STOP RUN.

3.9 The ACCEPT statement

It is used to accept (retrieve) current date and current time from the system. It can also be used to accept data from input stream.

Format:

ACCEPT id1 FROM DATE [TIME] [SYSIN]

Example:

01 WS-DATE PIC 9(6).01 WS-TIME PIC 9(6)01 WS-NAME PIC X(50).……….……….ACCEPT WS-DATE FROM DATE.ACCEPT WS-TIME FROM TIME.ACCEPT WS-NAME FROM SYSIN.

Note that the format of date is YYMMDD and time is HHMMSS.

Find out the output of the following program.

000001 IDENTIFICATION DIVISION. 000002 PROGRAM-ID. LAB08. 000003 ENVIRONMENT DIVISION. 000004 DATA DIVISION. 000005 WORKING-STORAGE SECTION. 000006 01 WS-DATE PIC 9(6). 000007 01 WS-TIME PIC 9(6). 000008 PROCEDURE DIVISION. 000009 0000-MAIN. 000010 ACCEPT WS-DATE FROM DATE. 000011 ACCEPT WS-TIME FROM TIME. 000012 DISPLAY 'DATE = ' WS-DATE. 000013 DISPLAY 'TIME = ' WS-TIME. 000014 STOP RUN. 000015 0000-EXIT. 000016 EXIT.

3.10 Using CONSOLE clause

SI Asia Pacific,, Singapore 36

Page 37: Cobol Notes v01

You can use CONSOLE clause along with DISPLAY and ACCEPT to display a value on console and accept value from console.

Format:

DISPLAY id1 [lit1] UPON CONSOLE.

ACCEPT id1 FROM CONSOLE.

Example:

DISPLAY ‘Do you want to continue [Y/N]?’ UPON CONSOLE.ACCEPT WS-REPLY FROM CONSOLE.

Note that you should not try this statement as the reply is expected from the mainframe console and is not available during a batch execution.

3.11 Getting System Date and Time

You can get the current date and time from the system. Refer to the previous topic (ACCEPT). Besides the ACCEPT statement, you can use a function called CURRENT-DATE to retrieve the system date and time.

Format:

MOVE FUNCTION CURRENT-DATE TO id1.

Example:

01 WS-SYS-DATE PIC X(8).…….MOVE FUNCTION CURRENT-DATE TO WS-SYS-DATE.

What is the output of the following program?

000001 IDENTIFICATION DIVISION. 000002 PROGRAM-ID. LAB09. 000003 ENVIRONMENT DIVISION. 000004 DATA DIVISION. 000005 WORKING-STORAGE SECTION. 000006 01 WS-DATE PIC X(8). 000007 PROCEDURE DIVISION. 000008 0000-MAIN. 000009 MOVE FUNCTION CURRENT-DATE TO WS-DATE. 000010 DISPLAY 'DATE = ' WS-DATE. 000011 STOP RUN. 000012 0000-EXIT. 000013 EXIT.

DATE = ____

SI Asia Pacific,, Singapore 37

Page 38: Cobol Notes v01

Chapter 4

Conditions and Conditional Expressions

4.1 Introduction

COBOL has various types of conditions which can bed used to derive various conditional expressions. We have sign condition, class condition, conditional names and compound conditions. Usually we will use an IF statement of EVALUATE to check a condition in COBOL.

4.2 The IF statement

The IF statement is used to evaluate a condition. During the execution of this statement if the condition is evaluated to true the statements between IF and ELSE (represented by <statement1>) will be executed, otherwise the statements between ELSE and END-IF or the associated period (represented by <statement2>) will be executed.

Format:

IF <condition> <statement1>ELSE <statement2>END-IF.

Example:

IF WS-AMT > 1500.00 ADD 100 TO WS-BALELSE ADD 250 TO WS-BALEND-IF.

All relational operators are valid here. You could also use the following options.

IS [NOT] GREATER THAN IS [NOT] LESS THANIS [NOT] EQUAL TO

IF WS-AMT IS GREATER THAN 1500.00 ADD 100 TO WS-BALELSE ADD 250 TO WS-BALEND-IF.

You can combine more than one conditions by using AND OR and NOT.

IF (WS-AGE <= 25 AND WS-AGE <= 50) OR WS-SALARY > 4500 DISPLAY ‘Eligible’

SI Asia Pacific,, Singapore 38

Page 39: Cobol Notes v01

END-IF.

IF WS-FALG NOT = ‘Y’ GO TO 3000-EXITEND-IF.

You can also code nested-if statement as given in the following example.

IF WS-AGE >= 25 AND WS-AGE <= 50 IF WS-SALARY > 3500.00 IF WS-SEX = ‘M’ GO TO 3500-PROCESS-MALE-RECORD ELSE GO TO 3600-PROCESS-FEMALE-RECORD END-IF ELSE DISPLAY ‘NOT ELIGIBLE’ END-IFELSE DISPLAY ‘INVALID AGE’END-IF.

Note that the period (full stop) is very powerful. So you may use the scope terminator (END-IF) or period or even both. But if you put a full stop (period), the remaining scope terminator will not have any impact. Also this will cause a compilation error.

The following IF statement is invalid.

IF WS-AGE >= 25 IF WS-SALARY > 3500.00 GO TO 2300-PROCESS. This period will terminate the scope of all IF ELSE GO TO 2500-DELETE END-IFEND-IF.

What if the output of the following program?

000001 IDENTIFICATION DIVISION. 000002 PROGRAM-ID. LAB10. 000003 ENVIRONMENT DIVISION. 000004 DATA DIVISION. 000005 WORKING-STORAGE SECTION. 000006 01 WS-I PIC 9(2) VALUE 60. 000007 01 WS-J PIC 9(2) VALUE 50. 000008 01 WS-K PIC 9(2) VALUE 75. 000009 PROCEDURE DIVISION. 000010 0000-MAIN. 000011 IF WS-I > WS-J AND WS-I > WS-K 000012 DISPLAY 'LARGEST = ' WS-I 000013 ELSE 000014 IF WS-J > WS-I AND WS-J > WS-K 000015 DISPLAY 'LARGEST = ' WS-J 000016 ELSE

SI Asia Pacific,, Singapore 39

Page 40: Cobol Notes v01

000017 DISPLAY 'LARGEST = ' WS-K 000018 END-IF 000019 END-IF. 000020 STOP RUN. 000021 0000-EXIT. 000022 EXIT.

LARGEST = __

4.3 The CONDITION NAMES

The Condition Name is an entity which itself is a condition. It can have either a true or false value. Condition names are defined by using the level number 88. You cannot define a condition name independently. Always a condition name must associate with a data name called conditional data name. You may define one or more condition name associated with one conditional data name. A condition name entry represents a single value or set (range) of values. The condition name becomes true whenever the conditional data name assume these value(s).

Format:

88 <condition-name> VALUE id1 [Lit1] [THRU <id2> [Lit2]]

Example:

01 WS-AGE PIC 9(2). 88 MINOR VALUE 01 THRU 10. 88 TEEN VALUE 11 THRU 19. 88 ADULT VALUE 20 THRU 99.

Your program can be coded as follows:

IF MINOR ……..ELSE IF ADULT ….. END-IFEND-IF.

The above sentence is equivalent to the following sentence.

IF WS-AGE >= 01 AND WS-AGE <= 10 ……..ELSE IF WS-AGE >= 20 AND WS-AGE <= 99 ….. END-IFEND-IF.

You may also use the NOT operator to indicate the negative condition.

IF NOT MINOR …..

SI Asia Pacific,, Singapore 40

Page 41: Cobol Notes v01

…..END-IF.

Find out the output of the following program.

000001 IDENTIFICATION DIVISION. 000002 PROGRAM-ID. LAB12. 000003 ENVIRONMENT DIVISION. 000004 DATA DIVISION. 000005 WORKING-STORAGE SECTION. 000006 01 WS-ELG PIC X VALUE 'N'. 000007 88 ELIGIBLE VALUE 'Y'. 000008 01 WS-SAL PIC 9(5) VALUE 5000. 000009 PROCEDURE DIVISION. 000010 0000-MAIN. 000011 IF WS-SAL >= 5000 000012 MOVE 'Y' TO WS-ELG 000013 END-IF. 000014 IF NOT ELIGIBLE 000015 DISPLAY 'NOT ELIGIBLE' 000016 ELSE 000017 DISPLAY 'ELIGIBLE' 000018 END-IF. 000019 STOP RUN. 000020 0000-EXIT.

Change the value of WS-SAL to 3500 and see what is the output.

4.4 The Sign Condition

The sign condition determines whether or not the algebraic value of an operand is positive, negative or zero. The operand can be either a numeric identifier or an arithmetic expression.

Format:

POSITIVEIdentifier

IS [ NOT] NEGATIVEArithmetic-expression

ZERO

The POSITIVE option determines the value of the condition to be true only if the value of the operand is positive. When arithmetic expression is used, it must contain at least one identifier. Note that the value zero is not treated as positive.

Examples:

01 WS-BALANCE PIC S9(6)V99

. .

SI Asia Pacific,, Singapore 41

Page 42: Cobol Notes v01

IF WS-BALANCE IS ZERO GO TO 2500-ZERO-BAL END-IF.

The above IF statement is equivalent to the following statement that makes use of a relational condition.

IF WS-BALANCE = 0 GO TO 2500-ZERO-BALEND-IF.

IF WS-BALANCE IS POSITIVE GO TO 3100-COMPUTEEND-IF.

IF WS-BALANCE IS NEGATIVE GO TO 3500-ERROREND-IF.

In general, any sign condition can be replaced by an equivalent relational condition. The use of the sign condition is convenient in certain cases and its use may also increase the readability of the statement that uses it.

4.5 The Class Condition

The class condition is used to evaluate the class of a data item, whether it is numeric, alphabetic etc. The available classes are given below.

(a) NUMERIC

It is used to check whether the data name contains all numbers or not. If the data item contain any no-numeric value, the condition will not satisfy.

Format:

<data-name>[IS] [NOT] NUMERIC

Example:

IF WS-AMT NOT NUMERICMOVE ZEROS TO WS-AMT

END-IF.

(b) ALPHABETIC

To check if the data item contains alphabetic characters. It includes A through Z, a through z and spaces. i.e. both upper and lower case letters and spaces.Format:

<data-name> [IS] [NOT] ALPHABETIC

Example:

IF WS-NAME IS ALPHABETICMOVE WS-NAME TO WS-NAME-REPT

SI Asia Pacific,, Singapore 42

Page 43: Cobol Notes v01

ELSEMOVE SPACES TO WS-NAME-DEPT

END-IF.

(c) ALPHABETIC-UPPER

To check if the data item contains upper case characters. i.e. the entire item must contain A through Z or spaces.

Format:

<data-name> [IS] [NOT] ALPHABETIC-UPPER

Example:

IF WS-NAME IS ALPHABETIC-UPPERMOVE WS-NAME TO WS-NAME-REPT

ELSEMOVE SPACES TO WS-NAME-DEPT

END-IF.

(d) ALPHABETIC-LOWER

To check if the data item contains lower case characters. i.e. the entire item must contain a through z or spaces.

Format:

<data-name> [IS] [NOT] ALPHABETIC-LOWER

Example:

IF WS-NAME IS ALPHABETIC-LOWERMOVE WS-NAME TO WS-NAME-REPT

ELSEMOVE SPACES TO WS-NAME-DEPT

END-IF.

4.6 The EVALUATE statement

The EVALUATE statement is an expanded form of the IF statement. It is used to evaluate a condition. The nested-if statement can be replaced with singe EVALUATE statement. (When an IF statement has another IF statement as one of its possible processing branches, these IF statements are said to be nested IFs). With the EVALUATE statement, you can test any number of conditions in a single statement and have separate actions for each.

When evaluated, each pair of selection-subjects and selection-objects must belong to the same class (numeric, character, CONDITION TRUE or FALSE). You can code up to 255 evaluate subjects and objects in an EVALUATE statement. There is no limit to the number of WHEN clauses you can code in an EVALUATE statement, but one page is a practical guideline.

Format1:

SI Asia Pacific,, Singapore 43

Page 44: Cobol Notes v01

EVALUATE Id1 WHEN Lit1 [THRU Lit2] <Statements> WHEN Lit3 [THRU Lit 4] <Statements> WHEN Lit5 [THRU Lit6] <Statements> WHEN OTHER <statements> END-EVALUATE

Examples:

EVALUATE WS-FALG WHEN ‘A’ GO TO 2000-PROCESS-A WHEN ‘B’ GO TO 3000-PROCESS-B WHEN ‘B’ GO TO 4000-PROCESS-C WHEN OTHER GO TO 5000-ERROR END-EVALUATE.

EVALUATE WS-AGE WHEN 01 THRU 19 GO TO 4000-BELOW-AGE WHEN 20 THRU 45 GO TO 5000-VALID-AGE WHEN 46 THRU 70 GO TO 6000-ABOVE WHEN OTHER GO TO 7000-REJECT END-EVALUATE.

Note that THRU or THROUGH is an option, which is used to specify a range of values.

If you want to evaluate a condition in the WHEN clause you must use the following format.

Format2:

EVALUATE TRUE (or FALSE) WHEN <expression1> <Statements> WHEN <expression2> <Statements> WHEN <expression2> <Statements> WHEN OTHER <Statements>END-EVALUATE.

SI Asia Pacific,, Singapore 44

Page 45: Cobol Notes v01

Example:

EVALUATE TRUE WHEN AGE > 50 ADD 500 TO PAYEMNT-AMT WHEN AGE > 30 ADD 300 TO PAYEMNT-AMT WHEN AGE > 20 ADD 100 TO PAYEMNT-AMTEND-EVALUATE.

The following format will allow you to evaluate two identifiers.

Format3:

EVALUATE TRUE ALSO TRUE WHEN <expression1> ALSO <expression2> <Statements> WHEN <expression3> ALSO <expression4> <Statements> WHEN OTHER <Statements>END-EVALUATE.

Example:

EVALUATE TRUE ALSO TRUE WHEN AGE > 50 ALSO SALARY < 5000 ADD 500 TO PAYEMNT-AMT WHEN AGE > 30 ALSO SALARY < 4000 ADD 300 TO PAYEMNT-AMT WHEN AGE > 20 ALSO SALARY < 3000 ADD 100 TO PAYEMNT-AMTEND-EVALUATE.

Find out the output of the following program.

000001 IDENTIFICATION DIVISION. 000002 PROGRAM-ID. LAB12. 000003 ENVIRONMENT DIVISION. 000004 DATA DIVISION. 000005 WORKING-STORAGE SECTION. 000006 01 WS-DATE PIC X(8) VALUE '20031201'. 000007 01 WS-DATE-O. 000008 03 WS-YYYY PIC 9(4). 000009 03 WS-MM PIC 9(2). 000010 03 WS-DD PIC 9(2). 000011 PROCEDURE DIVISION. 000012 0000-MAIN. 000013 MOVE WS-DATE TO WS-DATE-O. 000014 EVALUATE WS-MM 000015 WHEN 01 THRU 03 000016 DISPLAY 'FIRST QUARTER' 000017 WHEN 04 THRU 06 000018 DISPLAY 'SECOND QUARTER'

SI Asia Pacific,, Singapore 45

Page 46: Cobol Notes v01

000019 WHEN 07 THRU 09 000020 DISPLAY 'THIRD QUARTER' 000021 WHEN OTHER 000022 DISPLAY 'FORTH QUARTER' 000023 END-EVALUATE. 000024 STOP RUN. 000025 0000-EXIT. 000026 EXIT.

4.7 The CONTINUE and NEXT SENTENCE

The CONTINUE statement is used to transfer control to the next statement and the scope terminator; whereas the NEXT SENTENCE is used to transfer control to the next statement. i.e. after the period. It is usually used in nested if statements.

Example1:

IF WS-AGE > 25 AND WS-AGE < 50 IF WS-AMT > 4500 MOVE ‘ACCEPTED’ TO WS-SEL ELSE CONTINUE END-IF DISPLAY ‘INVALID’ENDIF.DISPLAY ‘OVER’.

In the above example, if the ELSE part is executed, you will get the output ‘INVALID’ and ‘OVER’.

Example2:

IF WS-AGE > 25 AND WS-AGE < 50 IF WS-AMT > 4500 MOVE ‘ACCEPTED’ TO WS-SEL ELSE NEXT SENTENCE END-IF DISPLAY ‘INVALID’ENDIF.DISPLAY ‘OVER’.

In the above example if the else part is executed, you will get the output ‘OVER’.

SI Asia Pacific,, Singapore 46

Page 47: Cobol Notes v01

Chapter 5

Loop Control Statements

5.1 The PERFORM Statement

The PERFORM statement is used to execute a paragraph or a range of paragraph, which is written anywhere in a COBOL program. It is also acted as a conditional branching statement. After the execution of all the statements in the specified paragraph the control will come back to the next statement following PERFORM.

The major difference between GO TO and PERFORM is that in case of GO TO, the control will not come back.

There are a number of formats available with PERFORM. They are given below.

Format1:

PERFORM <procedure1> [THRU <procedure2>].

If used, this perform will transfer control to the specified procedure or range of procedures.

Examples:

PERFORM 3000-PROCESS.PERFORM 3000-PROCESS THRU 5000-CLOSE.

Format2:

PERFORM <procedure1> [THRU <procedure2>] id1 TIMES.

If used, this perform will transfer control to the specified procedure or range of procedures and repeat the execution. The number of repetition will depend on the value specified in id1.

Examples:

PERFORM 3000-PROCESS 10 TIMES.PERFORM 3000-PROCESS THRU 3000-EXIT 5 TIMES.

Format3:

PERFORM <procedure1> [THRU <procedure2>] UNTIL <Condition>.

If used, this perform will transfer control to the specified procedure or range of procedures and repeat the execution until the specified condition is satisfied.

Examples:

SI Asia Pacific,, Singapore 47

Page 48: Cobol Notes v01

PERFORM 3000-PROCESS UNTIL WS-I > 100.PERFORM 3000-PROCESS THRU 3000-EXIT UNTIL WS-EOF-FLAG = ‘Y’.

Format4:

PERFORM <procedure1> [THRU <procedure2>] VARYING id1 FROM id2 [Lit1] BY id2 [Lit2] UNTIL <Condition>.

If used, this perform will transfer control to the specified procedure or range of procedures and repeat the execution until the specified condition is satisfied. At the same time it will initialize the value of an identifier and keep modifying it.

Examples:

PERFORM 3000-PROCESS VARYING WS-I FROM 1 BY 1 UNTIL WS-I > 100.

PERFORM 3000-PROCESS THRU 3000-EXIT VARYING WS-I FROM WS-NO BY 1 UNTIL WS-I > 50.

PERFORM 4000-COMPUTE THRU 4000-EXIT VARYING WS-I FROM 100 BY -1 UNTIL WS-I < 1.

Format5:

PERFORM <procedure1> [THRU <procedure2>] VARYING id1 FROM id2 [Lit1] BY id3 [Lit2] UNTIL <Condition1> AFTER id4 FROM id5 [Lit2] BY id6 [Lit3] UNTIL <Condition2>.

This is a nested-perform statement. Each time when the value of id1 got changed, the value of id4 will initialize to id5 or Lit2 and modified by the given step (id6 or Lit3) till the condition2 is satisfied.

Examples:

PERFORM 3000-PROCESS VARYING WS-I FROM 1 BY 1 UNTIL WS-I > 10AFTER WS-J FROM 1 BY 1 UNTIL WS-J > 4.

PERFORM 3000-PROCESS THRU 4000-COMPUTE VARYING WS-I FROM WS-NO BY 1 UNTIL WS-I > 10 AFTER WS-J FROM 1 BY 1 UNTIL WS-J > 5.

PERFORM 3000-PROCESS THRU 4000-COMPUTE VARYING WS-I FROM 1 BY 1 UNTIL WS-I > 5 1 AFTER WS-J FROM WS-K BY 1 UNTIL WS-J > WS-NO.

Study the following program segments and find out the output.

(a)01 WS-COUNT PIC 9(2) VALUE 0.………..PERFORM 2000-PROCESS THRU 2000-EXIT VARYING WS-COUNT FROM 1 BY 1 UNTIL WS-COUNT > 50.

SI Asia Pacific,, Singapore 48

Page 49: Cobol Notes v01

(b)01 WS-COUNT PIC 9(2) VALUE 0.………..PERFORM 2000-PROCESS THRU 2000-EXIT VARYING WS-COUNT FROM 1 BY 1 UNTIL WS-COUNT > 150.

The purpose of the following program is to print the even number numbers between 1 and 100. Fill up the blanks.

IDENTIFICATION DIVISION. PROGRAM-ID. LAB12. ENVIRONMENT DIVISION. DATA DIVISION. WORKING-STORAGE SECTION.

______________________________________________ PROCEDURE DIVISION. 0000-MAIN. PERFORM 1000-DISPLAY THRU 1000-EXIT UNTIL WS-COUNT > 100. STOP RUN. 0000-EXIT. EXIT. 1000-DISPLAY. DISPLAY WS-COUNT. ______________________________________________ 1000-EXIT. EXIT.

The following program will print a multiplication table of any given number. Complete the program with required statements.

000001 IDENTIFICATION DIVISION. 000002 PROGRAM-ID. LAB13. 000003 ENVIRONMENT DIVISION. 000004 DATA DIVISION. 000005 WORKING-STORAGE SECTION. 000006 01 WS-NUM PIC 9 VALUE 1. 000007 01 WS-I PIC 99 VALUE 1. 000008 01 WS-VAL PIC 99 VALUE 0. 000009 PROCEDURE DIVISION. 000010 0000-MAIN. 000011 PERFORM 1000-ACCEPT. 000012 PERFORM 2000-TABLE VARYING WS-I FROM 1 000013 ____________________________________. 000014 STOP RUN. 000015 1000-ACCEPT. 000016 ACCEPT WS-NUM FROM SYSIN. 000017 2000-TABLE. 000018 _________________________________________________000019 000020 DISPLAY WS-I ' * ' WS-NUM ' = ' WS-VAL.

SI Asia Pacific,, Singapore 49

Page 50: Cobol Notes v01

5.2 The Inline PERFORM statement

The traditional out-of-line PERFORM statement (PERFORM PROC-1 THRU PROC-2) requires an implicit branch to a separate paragraph and an implicit return. If the performed paragraph is in the subsequent sequential flow, it will be executed one more time. To avoid this additional execution, the paragraph is placed outside the normal sequential flow.

In structured programming, using an in-line PERFORM statement, the paragraph performs one logical function. The subject of an in-line PERFORM must be an imperative statement. Therefore, statements other than imperative statements within an in-line PERFORM must be coded with their scope terminators.

Format:

PERFORM UNTIL <Condition><Statement 1><Statement 2>…….…….

END-PERFORM.

Example:

MOVE ‘N’ TO WS-EOF.READ EMP-FILE AT END MOVE ‘Y’ TO WS-EOF.PERFORM UNTIL WS-EOF = ‘Y’ PERFORM 3100-PROCESS THRU 3100-EXIT IF NO-ERRORS PERFORM 3200-UPDATE THRU 3200-EXIT ELSE PERFORM 4000-PRINT-ERROR THRU 4000-EXIT END-IF READ EMP-FILE AT END MOVE ‘Y’ TO WS-EOF.END-PERFORM.

SI Asia Pacific,, Singapore 50

Page 51: Cobol Notes v01

The following program is meant to generate a multiplication table of 5, starting from 1 to 10. Include the required steps.

IDENTIFICATION DIVISION. PROGRAM-ID. LAB14. ENVIRONMENT DIVISION. DATA DIVISION. WORKING-STORAGE SECTION. ______________________________________________ ______________________________________________ PROCEDURE DIVISION. 0000-MAIN. PERFORM UNTIL WS-COUNT > 10 COMPUTE WS-RESULT = WS-COUNT * 5 _______________________________ _______________________________ END-PERFORM. STOP RUN. 0000-EXIT. EXIT.

5.3 TEST BEFORE and TEST AFTER options

The normal PERFORM statement allowed just one type of test. The condition to terminate the ‘loop’ was always tested before the loop was entered. If the test condition was false, the loop was not executed even once. In structured programming terminology, this is equivalent to a "do-while" loop.

Because you can now use the TEST BEFORE or TEST AFTER phrase with the PERFORM statement, you can choose to have your test either before the loop entry or after it. With TEST AFTER, the loop is executed the first time--regardless of the condition. TEST BEFORE corresponds to "do-while." TEST AFTER corresponds to "do-until."

Format:

PERFORM . . . WITH TEST AFTER . . . UNTIL . . .PERFORM . . . [WITH TEST BEFORE] . . . UNTIL . . .

Example:

MOVE ‘Y’ TO WS-FLAG.PERFORM WITH TEST BEFORE UNTIL WS-FLAG = ‘Y’ ……. …….END-PERFORM.

The above PERFORM statement will not execute as the value of WS-FLAG is already ‘Y’.

MOVE ‘Y’ TO WS-FLAG.

SI Asia Pacific,, Singapore 51

Page 52: Cobol Notes v01

PERFORM WITH TEST AFTER UNTIL WS-FLAG = ‘Y’ ……. …….END-PERFORM.

The above PERFORM statement will execute once even if the value of WS-FLAG is ‘Y’.

What is the output of the following programs?

000001 IDENTIFICATION DIVISION. 000002 PROGRAM-ID. LAB15. 000003 ENVIRONMENT DIVISION. 000004 DATA DIVISION. 000005 WORKING-STORAGE SECTION. 000006 01 WS-COUNT PIC 9(2) VALUE 11. 000007 PROCEDURE DIVISION. 000008 0000-MAIN. 000009 PERFORM WITH TEST BEFORE UNTIL WS-COUNT > 10 000010 DISPLAY WS-COUNT 000011 ADD 1 TO WS-COUNT 000012 END-PERFORM. 000013 DISPLAY 'PROGRAM OVER'. 000014 STOP RUN. 000015 0000-EXIT. 000016 EXIT.

000001 IDENTIFICATION DIVISION. 000002 PROGRAM-ID. LAB16. 000003 ENVIRONMENT DIVISION. 000004 DATA DIVISION. 000005 WORKING-STORAGE SECTION. 000006 01 WS-COUNT PIC 9(2) VALUE 11. 000007 PROCEDURE DIVISION. 000008 0000-MAIN. 000009 PERFORM WITH TEST AFTER UNTIL WS-COUNT > 10 000010 DISPLAY WS-COUNT 000011 ADD 1 TO WS-COUNT 000012 END-PERFORM. 000013 DISPLAY 'PROGRAM OVER'. 000014 STOP RUN. 000015 0000-EXIT. 000016 EXIT.

5.4 The EXIT Statement

The EXIT verb indicates a no operation, and when executed, no action takes place. In general, it is used as the last statement in the last paragraph of a PERFORM range.

Format:

EXIT

SI Asia Pacific,, Singapore 52

Page 53: Cobol Notes v01

If used, this must be the only statement in the paragraph. Some time you may want to transfer control to end of a PERFORM range. In this case you can use EXIT statement.

Example:

2000-PROCESS.

<Statements ………>IF WS-AMT IS NOT NUMERIC MOVE ZERO TO WS-AMT GO TO 2000-EXITEND-IF.<Statements ………>

2000-EXIT.

EXIT.

SI Asia Pacific,, Singapore 53

Page 54: Cobol Notes v01

Chapter 6

More on Data Items

6.1 The REDEFINES clause

The REDEFINES clause is used to refer to the same memory location by using different variables with different size and type. Sometimes it may be found that two or more storage areas defined in the DATA DIVISION need not to be referred simultaneously. In such situation you can define a data name and redefine it into new data name(s) so that you will have two or more data names with different structures. But, it is to be noted that all these data names are referring to the same memory location.

Format:

Level-number Id1 REDEIFINES Id2.

The following rules are applied to REDEFINES clause.

a) The level number of Id1 and Id2 must be identical.b) The REDEFINES clause must immediately follow Id1.c) Entries in the new description cannot have value clause except in 88 level

number.d) This clause cannot be used in level numbers 66 and 88.e) It cannot be used in level number 01 in FILE SECTION. Note that you can use

REDEFINES clause with level number 01 in other sections of DATA DIVISION.f) Multiple redefinitions are allowed. The entries in the new definition must

immediately follow the REDEFINES entry.g) You are free to determine the size of the new entries. i.e. you can redefine a

small item to large item also.

Examples:

01 WS-DATE PIC 9(8) VALUE 20031205.01 WS-DATE-R REDEFINES WS-DATE. 03 WS-YYYY PIC 9(4). 03 WS-MM PIC 9(2). 03 WS-DD PIC 9(2).

In the above example, the data names WS-DATE and WS-DATE-R are referring to the same memory location. If you change the value of any date name, it will reflect in other.

The output of the following statements are same. Both will give 20031205.

DISPLAY WS-DATE.DISPLAY WS-DATE-R.

Suppose, we move the value 2002 to WS-YYYY, what will happen the value of WS-DATE? The value of WS-DATE too becomes 20021205. So any changes made to the original as well as the redefined field, it will reflect on both.

SI Asia Pacific,, Singapore 54

Page 55: Cobol Notes v01

Find out the output of the following program.

000001 IDENTIFICATION DIVISION. 000002 PROGRAM-ID. LAB17. 000003 ENVIRONMENT DIVISION. 000004 DATA DIVISION. 000005 WORKING-STORAGE SECTION. 000006 01 WS-TEXT PIC X(5) VALUE 'ABCDE'. 000007 01 WS-NEW-TEXT REDEFINES WS-TEXT. 000008 03 WS-TEXT1 PIC X. 000009 03 WS-TEXT2 PIC X(2). 000010 03 WS-TEXT3 PIC X(2). 000011 PROCEDURE DIVISION. 000012 0000-MAIN. 000013 DISPLAY WS-TEXT. 000014 MOVE 'PQ' TO WS-TEXT2. 000015 DISPLAY WS-TEXT. 000016 STOP RUN. 000017 0000-EXIT. 000018 EXIT.

6.2 The RENAMES clause

The RENAMES clause is used to re-group elementary data items in a record so that the data items will be available in original as well as in new group. In order to use RENAMES clause you must use the level number 66.

Format:

66 data-name1 RENAMES data-name2 [THRU data-name3]

Example:

01 WS-EMP-REC.03 WS-EMP-NO PIC 9(5).03 WS-EMP-NAME PIC X(30).03 WS-FIXED-PAY. 05 WS-BP PIC 9(5). 05 WS-HRA PIC 9(3). 05 WS-DA PIC 9(3).03 WS-ALLOWANCES. 05 WS-MEDICAL PIC 9(3). 05 WS-TRANS PIC 9(4).03 WS-DEDUCTIONS. 05 WS-PF PIC 9(4). 05 WS-I-TAX PIC 9(3).

66 WS-DA-AND-ALLOWANCES RENAMES WS-DA THRU WS-TRANS.66 WS-FIXED-AND-MEDICAL RENAMES WS-BP THRU WS-MEDICAL.

A few important rules that are applied to RENAMES clause are given below.

a) RENAMES clause must be used along with 66 level only.b) It must be written after the last record description.

SI Asia Pacific,, Singapore 55

Page 56: Cobol Notes v01

c) Dataname-2 and data-name3 (refer to the format) can be either elementary or group items.

d) You cannot include the data names defined with level number 01, 66, 01 or 88 in the RENAMES clause.

e) Data-name2 and data-name3 should not be specified with OCCURS clause.f) Data-name3, if specified must follow data-name2 in the record description.

6.4 The INITIALIZE statement

This statement is used to initialize an elementary or group variable. When used to initialize a group variable, the initialization is based on the type of the elementary variables.

Format:

INITIALIZE identifier-1.

Example:

01 WS-REC. 03 WS-NO PIC 9(5). 03 WS-NAME PIC X(20). 03 WS-AMT PIC S9(7)V99 COMP-3. INITIALIZE WS-REC.

How INITIALIZE works?

Id1 (Picture) Id1 (Before) Id1 (After)9(5) 12345 00000X(5) ABCDE 5 Blanks

99XX99 25AB90 6 BlanksA(5) 10/03 5 Blanks

9(5)V99 1234575 0000000

SI Asia Pacific,, Singapore 56

Page 57: Cobol Notes v01

Chapter 7

Table Handling7.1 Introduction

In COBOL an array is referred to as tables. So tables are nothing but arrays. COBOL will allow you to create single-dimensional and multi-dimensional tables. The declaration and use of tables are given below.

7.2 What is a Table?

A table or an array is nothing but chronologically ordered values stored in same data item with different locations. Suppose there are five different department codes, which are to be stored in the form of a table named DEPT-CODE. In order to handle this table in a COBOL program, you must know how to declare the table in the DATA DIVISION, how to store that values into the table and how to refer to the individual data items (here department codes) in the PROCEDURE DIVISION.

In order to store the names of five department names you can declare five different data names as given below:

01 DEPT-CODES. 03 DEPT-CODE1 PIC X(4). 03 DEPT-CODE2 PIC X(4). 03 DEPT-CODE3 PIC X(4). 03 DEPT-CODE4 PIC X(4). 03 DEPT-CODE5 PIC X(4).

The difficulty in using the above data names is that you need to refer to individual data names, which is different from one another. Now suppose you want to store 50 department codes you will have to declare and use 50 separate data names. Practically this is very inconvenient. To avoid this problem you can declare a single data name which can store multiple values. This is called a table or array.

7.3 How to define Table?

To declare a table (array) in COBOL, you can use OCCURS clause.

Format:

OCCURS integer TIMES

Example:

01 DEPT-CODE-TABLE. 03 DEPT-CODE PIC X(4) OCCURS 5 TIMES.

In the above example, we have defined a table that can store 5 department codes. Each department code is identified by its position in the table. The position of the each item in the table is known as its subscript. So the subscript of the first item in the array will be 1 and that of second item will be 2 and so on.

SI Asia Pacific,, Singapore 57

Page 58: Cobol Notes v01

Note that you will not be able to use the data name defined with the OCCURS without using subscript. But you may refer to the group data name under which the OCCURS clause is defined directly. i.e. the data name DEPT-CODE-TABLE can be referred directly without using subscript.

The following MOVE statements are correct:

MOVE DEPT-CODE-TABLE TO WS-DEPT-CODE-TABLE.

MOVE DEPT-CODE (1) TO WS-DEPT-CODE1.

MOVE DEPT-CODE (WS-COUNT) TO WS-DEPT-CODE1. (Assuming WS-COUNT is a numeric variable and contains a value ranging from 1 through 5.

The following MOVE statement is wrong, as the subscript is not specified.

MOVE DEPT-CODE TO WS-DEPT-CODE1.

The following rules are applied to the OCCURS clause and the subscripts.

a) The integer in the OCCURS clause must be a positive integer.

b) The OCCURS clause can be specified for an elementary item or for a group item. The clause causes contiguous area holding the elements to be set up internally. The number of elements is equal to the integer in the OCCURS clause.

c) The OCCURS clause cannot be specified for an item whose level number is 01, 66, 01 or 88.

d) The highest value that a subscript can take is the one specified by the integer in the OCCURS clause. The lowest value of a subscript is implicitly assumed to be 1. A subscript can assume a value between 1 and the highest values defined in the range (inclusive).

e) When a data name is described with the OCCURS clause, the data name as well as any of its subordinate items cannot be referred to in the PROCEDURE DIVISION without a subscript.

f) The subscript must be enclosed within a pair of parentheses.

g) A data name used as a subscript cannot be another subscripted data name. This means that if you are using WS-I as the subscript, it should be declared with OCCURS clause.

h) When an entry is defined with OCCURS clause, the VALUE clause cannot be specified for the associated data name or any data name subordinate to it.

i) The REDEFINES clause cannot appear in the same data description entry which contains an OCCURS clause. However, REDEFINES clause can appear for a group item whose subordinate items are defined with the OCCURS clause.

j) The OCCURS clause can appear in the data description entry in any position after the level number and the data name.

Consider the following examples:

01 WS-STUDENT-TABLE. 03 WS-STUDENT-NO PIC 9(5) OCCURS 10 TIMES.

SI Asia Pacific,, Singapore 58

Page 59: Cobol Notes v01

03 WS-STUDENT-NAME PIC X(30) OCCURS 10 TIMES. 03 WS-STUDENT-MARK PIC 9(3) OCCURS 10 TIMES.

The above array declaration can be modified as follows:

01 WS-STUDENT-TABLE. 03 WS-STUDENT OCCURS 10 TIMES. 05 WS-STUDENT-NO PIC 9(5). 05 WS-STUDENT-NAME PIC X(30). 05 WS-STUDENT-MARK PIC 9(3).

The above example shows that you can specify the OCCURS clause in either group level or elementary level, except 01, 66, 01 and 88.

Note that if you are using OCCURS clause at the group level, you should not use picture clause. In this case the picture clause must be used at the elementary level.

The following program will accept 3 numbers from SYSIN and display it?

000001 IDENTIFICATION DIVISION. 000002 PROGRAM-ID. LAB18. 000003 ENVIRONMENT DIVISION. 000004 DATA DIVISION. 000005 WORKING-STORAGE SECTION. 000006 01 WS-I PIC 9(2) VALUE 0. 000007 01 WS-NUM-TABLE. 000008 03 WS-NUMBERS PIC 9(3) OCCURS 3 TIMES. 000009 PROCEDURE DIVISION. 000010 0000-MAIN. 000011 PERFORM 1000-ACCEPT THRU 1000-EXIT VARYING WS-I 000012 FROM 1 BY 1 UNTIL WS-I > 3. 000013 000014 PERFORM 2000-DISPLAY THRU 2000-EXIT VARYING WS-I 000015 FROM 1 BY 1 UNTIL WS-I > 3. 000016 000017 STOP RUN. 000018 0000-EXIT. 000019 EXIT. 000020 1000-ACCEPT. 000021 ACCEPT WS-NUMBERS(WS-I). 000022 1000-EXIT. 000023 EXIT. 000024 2000-ACCEPT. 000025 DISPLAY WS-NUMBERS(WS-I). 000026 2000-EXIT. 000027 EXIT. Complete the following program. The purpose of the program is to accept 3 numbers from SYSIN and find its sum and average.

000001 IDENTIFICATION DIVISION. 000002 PROGRAM-ID. LAB19. 000003 ENVIRONMENT DIVISION. 000004 DATA DIVISION. 000005 WORKING-STORAGE SECTION. 000006 01 WS-I PIC 9(2) VALUE 0.

SI Asia Pacific,, Singapore 59

Page 60: Cobol Notes v01

000007 01 WS-SUM PIC 9(4) VALUE 0. 000008 01 WS-AVG PIC 9(3) VALUE 0. 000009 01 WS-NUM-TABLE. 000010 03 WS-NUMBERS PIC 9(3) OCCURS 3 TIMES. 000011 PROCEDURE DIVISION. 000012 0000-MAIN. 000013 PERFORM 1000-ACCEPT THRU 1000-EXIT VARYING WS-I 000014 FROM 1 BY 1 UNTIL WS-I > 3. 000015 PERFORM 2000-COMPUTE THRU 2000-EXIT VARYING WS-I 000016 FROM 1 BY 1 UNTIL WS-I > 3. 000017 000018 ____________________________________________. 000019 000020 DISPLAY 'SUM = ' WS-SUM. 000021 DISPLAY 'AVERAGE = ' WS-AVG. 000022 000023 STOP RUN. 000024 0000-EXIT. 000025 EXIT. 000026 1000-ACCEPT. 000027 ACCEPT WS-NUMBERS(WS-I). 000028 1000-EXIT. 000029 EXIT. 000030 2000-COMPUTE. 000031 000032 _____________________________________________. 000033 000034 2000-EXIT. 000035 EXIT.

The following program is used to get 5 numbers from SYSIN and sort it in ascending order.

000001 IDENTIFICATION DIVISION. 000002 PROGRAM-ID. LAB20. 000003 *--- SORTING 5 NUMBERS ---* 000004 ENVIRONMENT DIVISION. 000005 DATA DIVISION. 000006 WORKING-STORAGE SECTION. 000007 01 WS-I PIC 9(2) VALUE 0. 000008 01 WS-J PIC 9(2) VALUE 0. 000009 01 WS-K PIC 9(2) VALUE 0. 000010 01 WS-SUM PIC 9(4) VALUE 0. 000011 01 WS-AVG PIC 9(3) VALUE 0. 000012 01 WS-TEMP PIC 9(3) VALUE 0. 000013 01 WS-NUM-TABLE. 000014 03 WS-NUMBERS PIC 9(3) OCCURS 5 TIMES. 000015 PROCEDURE DIVISION. 000016 0000-MAIN. 000017 PERFORM 1000-ACCEPT THRU 1000-EXIT VARYING WS-I 000018 FROM 1 BY 1 UNTIL WS-I > 5. 000019 PERFORM 2000-SORT THRU 2000-EXIT VARYING WS-I 000020 FROM 1 BY 1 UNTIL WS-I > 4. 000021 PERFORM 3000-DISP THRU 3000-EXIT VARYING WS-I 000022 FROM 1 BY 1 UNTIL WS-I > 5. 000023 STOP RUN.

SI Asia Pacific,, Singapore 60

Page 61: Cobol Notes v01

000024 000025 0000-EXIT. 000026 EXIT. 000027 1000-ACCEPT. 000028 ACCEPT WS-NUMBERS(WS-I) FROM SYSIN. 000029 1000-EXIT. 000030 EXIT. 000031 2000-SORT. 000032 COMPUTE WS-K = WS-I + 1. 000033 PERFORM 2100-SWAP THRU 2100-EXIT VARYING WS-J 000034 FROM WS-K BY 1 UNTIL WS-J > 5. 000035 2000-EXIT. 000036 EXIT. 000037 2100-SWAP. 000038 IF WS-NUMBERS(WS-I) > WS-NUMBERS(WS-J) 000039 MOVE WS-NUMBERS(WS-I) TO WS-TEMP 000040 MOVE WS-NUMBERS(WS-J) TO WS-NUMBERS(WS-I) 000041 MOVE WS-TEMP TO WS-NUMBERS(WS-J) 000042 END-IF. 000043 2100-EXIT. 000044 EXIT. 000045 3000-DISP. 000046 DISPLAY WS-NUMBERS(WS-I). 000047 3000-EXIT. 000048 EXIT.

Change the above program to use bubble sort method.

7.4 MULTI-DIMENTIONAL TABLES (ARRAYS)

The tables that we have used so far are called single-dimensional tables, also known as one-dimensional tables. Now we will see how to create two-dimensional tables. Two-dimensional tables are a table with its elements in turn is a table of one dimension. Consider the following example:

01 PRODUCT-TABLE. 03 PRODUCT-CODE OCCURS 10 TIMES.

05 PART-NUMBERS PIC X(5) OCCURS 5 TIMES.

The above table is assumed to store 5 part numbers of each product. This is a two-dimensional table because the PRODUCT-CODE is itself a table having 10 elements. It may be noted that a reference to an element of a two-dimensional table requires two subscripts. We must specify the PRODUCT-CODE as well as the PART-NUMBERS so that the desired element is identified. Thus PART-NUMBERS (1, 1) means the first part number of the first product, where as the PART-NUMBERS (7, 4) means that the 4th part number of 7th product.

In the above table, you will be able to store 50 elements, each represent one part number of each product code. This table can be easily extended to tables having three or more dimensions. The following rules are applied to multi-dimensional tables.

a) Multi-dimensional tables are to be defined as records with OCCURS clauses at various levels. As we go down the hierarchy, each lower level item with an

SI Asia Pacific,, Singapore 61

Page 62: Cobol Notes v01

OCCURS clause specifies an additional dimension. Consider the following table.

01 MULTI-TABLE. 02 PRODUCT-DETAILS OCCURS 50 TIMES.

03 PRODUT-NAME PIC X(15).03 PRODUCT-CODE OCCURS 10 TIMES. 04 PART-NUMBERS PIC X(5) OCCURS 5 TIMES.

In the above table, the data name PRODUCT-NAME is a single dimensional table where as the data name PART-NUMBERS is a multi-dimensional table. The PART-NUMBERS has 3 levels. In order to get one element in PART-NUMBERS you will have to use the following subscripting:

PART-NUMBERS (1, 1, 1).

b) A table is stored in such a way that a subscript on the right of another subscript changes more frequently rapidly than the latter.

c) Multiple subscripts should be separated from one another either by a comma or space. It may be noted that if you are using a comma you must leave one space after it.

The following program will store the numbers in a 3X3 matrix and print it.

000001 IDENTIFICATION DIVISION. 000002 PROGRAM-ID. LAB21. 000003 *--- 3X3 MATRIX ---* 000004 ENVIRONMENT DIVISION. 000005 DATA DIVISION. 000006 WORKING-STORAGE SECTION. 000007 01 WS-I PIC 9(2) VALUE 0. 000008 01 WS-J PIC 9(2) VALUE 0. 000009 01 WS-MATRIX. 000010 02 WS-ROW OCCURS 3 TIMES. 000011 03 WS-COL OCCURS 3 TIMES. 000012 04 WS-NUM PIC 9(3). 000013 PROCEDURE DIVISION. 000014 0000-MAIN. 000015 PERFORM 1000-ACCEPT THRU 1000-EXIT VARYING WS-I 000016 FROM 1 BY 1 UNTIL WS-I > 3 AFTER WS-J 000017 FROM 1 BY 1 UNTIL WS-J > 3. 000018 PERFORM 2000-DISP THRU 2000-EXIT VARYING WS-I000019 FROM 1 BY 1 UNTIL WS-I > 3. 000020 STOP RUN. 000021 000022 0000-EXIT. 000023 EXIT. 000024 1000-ACCEPT. 000025 ACCEPT WS-NUM(WS-I, WS-J). 000026 1000-EXIT. 000027 EXIT. 000028 2000-DISP. 000029 DISPLAY WS-NUM(WS-I, 1) ' ' WS-NUM(WS-I, 2) ' ' 000030 WS-NUM (WS-I, 3).

SI Asia Pacific,, Singapore 62

Page 63: Cobol Notes v01

000031 2000-EXIT. 000032 EXIT.

Complete the following program. The purpose of the program is to get values into two matrices and find the sum.

000001 IDENTIFICATION DIVISION. 000002 PROGRAM-ID. LAB22. 000003 *--- 3X3 MATRIX ADDITION ---* 000004 ENVIRONMENT DIVISION. 000005 DATA DIVISION. 000006 WORKING-STORAGE SECTION. 000007 01 WS-I PIC 9(2) VALUE 0. 000008 01 WS-J PIC 9(2) VALUE 0. 000009 01 WS-MATRIX1. 000010 02 WS-ROW1 OCCURS 3 TIMES. 000011 03 WS-COL1 OCCURS 3 TIMES. 000012 04 WS-NUM1 PIC 9(3). 000013 01 WS-MATRIX2. 000014 02 WS-ROW2 OCCURS 3 TIMES. 000015 03 WS-COL2 OCCURS 3 TIMES. 000016 04 WS-NUM2 PIC 9(3). 000017 ______________________________________________________ 000018 000019 ______________________________________________________ 000020 000021 ______________________________________________________ 000022 000023 ______________________________________________________ 000024 000025 PROCEDURE DIVISION. 000026 0000-MAIN. 000027 PERFORM 1000-GET-MATRIX1 THRU 1000-EXIT VARYING WS-I 000028 FROM 1 BY 1 UNTIL WS-I > 3 AFTER WS-J 000029 FROM 1 BY 1 UNTIL WS-J > 3. 000030 PERFORM 2000-GET-MATRIX2 THRU 1000-EXIT VARYING WS-I 000031 FROM 1 BY 1 UNTIL WS-I > 3 AFTER WS-J 000032 FROM 1 BY 1 UNTIL WS-J > 3. 000033 PERFORM 3000-ADD THRU 3000-EXIT VARYING WS-I 000034 FROM 1 BY 1 UNTIL WS-I > 3 AFTER WS-J 000035 FROM 1 BY 1 UNTIL WS-J > 3. 000036 ____________________________________________________ 000037 ____________________________________________________ 000038 STOP RUN. 000039 000040 0000-EXIT. 000041 EXIT. 000042 1000-GET-MATRIX1. 000043 ACCEPT WS-NUM1(WS-I, WS-J). 000044 1000-EXIT. 000045 EXIT. 000046 2000-GET-MATRIX2. 000047 ___________________________ 000048 2000-EXIT. 000049 EXIT. 000050 3000-DISP.

SI Asia Pacific,, Singapore 63

Page 64: Cobol Notes v01

000051 000052 ________________________________________________ 000053 000054 3000-EXIT. 000055 EXIT. 000056 4000-DISP. 000057 DISPLAY WS-SUM(WS-I, 1) ' ' WS-SUM(WS-I, 2) ' ' 000058 WS-SUM (WS-I, 3). 000059 4000-EXIT. 000060 EXIT.

7.5 The INDEXED Tables

So far we have seen tables (arrays) with subscripts. COBOL has an alternative to subscripting, known as indexing. An index is a data item which is associated with a table or a particular dimension of a table through the use of INDEXED BY phrase of an OCCURS clause. The following example illustrates how to declare and use index tables.

Format:

OCCURS <integer> TIMES INDEXED BY index-name-1 [, index-name-2] . .

Example:

01 STUDENT-TABLE.

02 STUDENT-DETAILS OCCURS 10 TIMES INDEXED BY INDEX1.

03 MARKS OCCURS 6 TIMES INDEXED BY INDEX2.

04 SUBJECT PIC 9(3).

In the above example, INDEX1 and INDEX2 are index names associated with this table. These need not be defined separately in the DATA DIVISION. An element of the above table can be referenced as SUBJECT (INDEX1, INDEX2).

Conceptually, an index is similar to a subscript but the internal value of an index is quite different from that of a subscript. A subscript is any integer data item and its value denotes the position or occurrence of the element within a table. On the other hand, the internal value of an index is such that the element can be referenced in a more efficient manner. More precisely an index denotes a displacement of the element from the beginning of the table. So SUBJECT (0) means the first element in the table, as the displacement of the first element is zero.

In the above definition, the first element in SUBJECT is SUBJECT (0) and the second element is SUBJECT(1). But internally the displacement for the first element is zero, that for the second element is 3 (as the size of the element is 3). It is to be noted that this is the way that COBOL handles indexes. But to a COBOL programmer, the knowledge of internal representation of an index is of no importance. The programmer sets the value of an index by specifying the occurrence number and not the internal value. Because of this, the value of an index can only be set or altered by special statements like PERFORM, SET and SEARCH statements and not by other statements like MOVE or ADD.

SI Asia Pacific,, Singapore 64

Page 65: Cobol Notes v01

The following rules apply when apply when INDEXED BY phrase is used.

a) If indexing is done for any one level of a table, then indexing must be used for all levels.

b) Index names cannot be used in combination with subscripts. Thus a reference as SUBJECT (INDEX1, S1) will be treated as an error as INDEX1 is an index name but S1 is a data name. However, index names can be used in combination with numeric positive integral literals. Therefore reference SUBJECT(INDEX1, 3) is valid.

c) Indexes are valid only for the tables where they have been specified. I.e. Indexes for one table cannot be used for another table.

d) The index names must be unique. The same index name must not be used for different levels of a table.

e) The indexes must not appear (or declared) anywhere in the DATA DIVISION except in the INDEXED BY phrase of the OCCURS clause.

f) The value of an index can be manipulated only by the SET, SEARCH and PERFORM statements.

g) An index can be coded plus or minus an integer literal for the relative addressing of the table elements. For example, SUBJECT(INDEX1 + 1, INDEX2 – 1) is valid.

h) There can be more than one index for each level. I.e. INDEX BY INDEX1, INDEX2, INDEX3, … is valid.

7.6 The SET Verb

The SET verb is used to set and modify the value of the indexes.

Format1:

SET index-name-1 [, index-name-2] … TO Id1 [Int1] [Indexname1] ….

Example:

The following statement is used to set the value of the index name INDEX1 to 1.

SET INDEX1 TO 1

The following statement is used to set the value of the index name INDEX1 to the current value of WS-I.

SET INDEX1 TO WS-I.

The following statement is used to set the value of the index name INDEX1 to the current value of INDEX2.

SET INDEX1 TO INDEX2.

SI Asia Pacific,, Singapore 65

Page 66: Cobol Notes v01

Format2:

SET index-name-1 [, index-name2] UP BY Id1 [Int1]DOWN BY

The above format is used to increase or decrease the value of an index name. The phrase UP BY is used to increment the values of the indexes and the phrase DOWN BY is used to decrement their values.

Example:

The statement example is used to increment the value of the index name INDEX1 by 1.

SET INDEX1 UP BY 1.

The statement example is used to decrement the value of the index name INDEX1 by 1.

SET INDEX1 DOWN BY 1.

The following program is meant to accept 5 numbers from SYSIN and display it.

000001 IDENTIFICATION DIVISION. 000002 PROGRAM-ID. LAB23. 000003 *--- 3X3 MATRIX ADDITION ---* 000004 ENVIRONMENT DIVISION. 000005 DATA DIVISION. 000006 WORKING-STORAGE SECTION. 000007 01 WS-NUMBERS. 000008 02 WS-NUM PIC 9(3) OCCURS 5 TIMES INDEXED BY INDEX1. 000009 PROCEDURE DIVISION. 000010 0000-MAIN. 000011 PERFORM 1000-ACCEPT THRU 1000-EXIT VARYING 000012 INDEX1 FROM 1 BY 1 UNTIL INDEX1 > 5. 000013 PERFORM 2000-DISP THRU 2000-EXIT VARYING000014 INDEX1 FROM 1 BY 1 UNTIL INDEX1 > 5. 000015 STOP RUN. 000016 000017 0000-EXIT. 000018 EXIT. 000019 1000-ACCEPT. 000020 ACCEPT WS-NUM(INDEX1). 000021 1000-EXIT. 000022 EXIT. 000023 2000-DISP. 000024 DISPLAY WS-NUM(INDEX1). 000025 2000-EXIT. 000026 EXIT.

Note the, since INDEX1 is an index name it is not necessary to declare it in data division.

SI Asia Pacific,, Singapore 66

Page 67: Cobol Notes v01

7.7 Table of variable size

Some time you may require creating a table of variable size. In such situation you can use the OCCURS DEPENDING clause while declaring the table.

Format:

OCCURS <integer1> TO <integer2> TIMES DEPENDING ON <Id1>.

Example:

01 WS-COUNTPIC 9(3).01 STUDENT-TABLE. 02 STUDENT-REC OCCURS 1 TO 100 TIMES DEPENDING ON WS-COUNT.

03 STUDENT-NO PIC 9(5).03 STUDENT-NAME PIC X(20).03 STUDENT-MARK PIC 9(3).

In the above example, depending on the value of the data name WS-COUNT

the size of SUDENT-REC will be decided. The size of STUDENT-TABLE can be anything between 1 and 100, inclusive. It may be noted that even though this is a dynamic table, the size is still has some limits. The maximum limit depends on the value of integer2. i.e. the minimum value that can be assigned to WS-COUNT is 1 and the maximum value is 100.

The following rules apply for the OCCURS DEPENDING clause.

(i) Both <integer1> and <integer2> must be positive integers, and <integer1> must have a value less than <integer2>.

(ii) Id1 must be defined in DATA DIVISION. It can even appear in the same record with the data item having this clause, but it must not be subordinate to the entry whose description includes the DEPENDING clause. The following declaration is valid.

01 WS-STUDENT-REC.02 WS-COUNT PIC 9(3).02 WS-STUD-NO PIC 9(5) OCCURS 1 TO 50 TIMES

DEPENDING ON WS-COUNT.

However, the following declaration is invalid.

01 WS-STUDENT-REC.02 WS-STUD-NO PIC 9(5) OCCURS 1 TO 50 TIMES

DEPENDING ON WS-COUNT.

03 WS-COUNT PIC 9(3).

7.8 OCCURS with ASCENDING/DESCENDING clause

Sometimes you may require arranging the column in a table in the ascending or descending order. In such situation you can use ASCENDING or DESCENDING clause along with OCCURS. This generally required for using binary search.

SI Asia Pacific,, Singapore 67

Page 68: Cobol Notes v01

Format:

OCCURS <integer> TIMES ASCENDING [DESCENDING] KEY IS data name1, data name2… INDEXED BY index name1, index name2…

Example:

01 ACCOUNT-RECORD.02 ACCOUNT-TABLE OCCURS 100 TIMES ASCENDING KEY IS AC-NO

INDEXED BY INDEX1.03 AC-NO PIC 9(5).03 AC-NAME PIC X(30).03 AC-BAL PIC 9(5)V99.

It is to be noted that the data name specified in the ASCENDING/DESCENDING clause must be a data item declared in the table itself.

SI Asia Pacific,, Singapore 68

Page 69: Cobol Notes v01

Chapter 8

More on Table Handling

8.1 Introduction

You can use tables to store multiple elements in one data name and search for any data element within the table. The SEARCH statement is explained below.

8.2 The SEARCH Verb

The SEARCH verb is used to locate elements in one-dimensional tables.

Format:

Identifier-2SEARCH Identifier-1 VARYING

Index-name-1

; AT END imperative-statement-1

imperative-statement-2; WHEN Condition-1

NEXT SENTENCE

Imperative-statement-3; WHEN Condition-2 . . .

NEXT SENTENCE

Let us consider the following example. Assume that we have stored 50 pin postal codes and corresponding place name in an array. Now we want to supply one postal code and get the corresponding place name from the table. The table definition looks like:

DATA DIVISION.WORKING STORAGE SECTION.01 WS-PIN-TABLE. 03 WS-PIN OCCURS 50 TIMES INDEXED BY INDEX1.

05 WS-PIN-CODE PIC 9(6).05 WS-PLACE PIC X(30).

The following PROCEDURE DIVISION statements can be used to solve the above problem.

PROCEDURE DIVISION.

SI Asia Pacific,, Singapore 69

Page 70: Cobol Notes v01

SET INDEX1 TO 1SEARCH WS-PIN AT END DISPLAY ‘PIN CODE NOT FOUND’

WHEN WS-PIN-CODE (INDEX1) = WS-PIN DISPLAY WS-PLACE (INDEX1).

In the above SEARCH statement, there are two parts – the AT END part and the WHEN part. If the condition WS-PIN = WS-PIN-CODE (INDEX1) is satisfied for any value of the index name INDEX1, the statement DISPLAY WS-PLACE (INDEX1) is executed. The AT END part is executed only when the entire table is searched and the condition is not satisfied for any value of INDEX1. The value of INDEX1 is initialized by using the SET verb and the increment of INDEX1 is taken care of by the SEARCH verb.

The search operation will be stopped when either a match found or all elements searched. It is possible to continue the search operation even after a matching value found. In such case you will have to increment the value of the index name and repeat the search. To illustrate this, let us look at the following example. Assume that the details of all account holders are stored in a table.

01 WS-AC-DETAILS. 02 WS-AC-TABLE OCCURS 100 TIMES INDEXED BY INDEX1.

03 WS-AC-NOPIC 9(5). 03 WS-AC-NAME PIC X(20). 03 WS-AC-BAL PIC 9(7)V99.

Suppose, we want to search the above table to extract the account number and name of all persons with account balance > 7500.00. In this case we can use the following procedure division statements.

SET INDEX TO 1.PERFORM 3000-SEARCH THRU 3000-EXIT.…………3000-SEARCH.

SEARCH WS-AC-TABLE AT END GO TO 3000-EXIT WHEN WS-AC-BAL (INDEX1) > 7500.00 DISPLAY WS-AC-NO (INDEX1) ‘ ‘ WS-AC-NAME (INDEX1) SET INDEX 1 UP BY 1 GO TO 3000-SEARCH.

3000-EXIT. EXIT.

Usually the search operation will stop when the condition specified in WHEN clause is evaluated to true. In the above example a loop has been designed by using the GO TO 3000-SEARCH statement so that the entire table is searched. It is to be noted that before the execution of the GO TO statement, the current value of the index name INDEX1 is incremented by 1 to point to the next element of the table.

We can use more that one WHEN clause in the SEARCH statement if required. For example, suppose we want to find out the number of persons with account balance greater than 7500.00 and number of persons with account balance greater than 5000.00 and less than 7500.00. In this case we can extend the above SEARCH statement as follows.

SI Asia Pacific,, Singapore 70

Page 71: Cobol Notes v01

MOVE ZERO TO WS-5000-COUNT, WS-7500-COUNT.SET INDEX TO 1.PERFORM 3000-SEARCH THRU 3000-EXIT.…………

3000-SEARCH.

SEARCH WS-AC-TABLE AT END GO TO 3000-EXIT WHEN WS-AC-BAL (INDEX1) > 7500.00 ADD 1 TO WS-7500-COUNT WHEN WS-AC-BAL (INDEX1) > 5000.00 ADD 1 TO WS-5000-COUNT.

SET INDEX 1 UP BY 1. GO TO 3000-SEARCH.

3000-EXIT. EXIT.

In the above SEARCH statement there are two WHEN clauses. If any one of the WHEN clause is evaluated to true, all statements between that WHEN and the next WHEN will be executed and the control will be transferred to the next sentence. Due to the GO TO statement, the search will be performed with the next value of INDEX1 and this will be repeated till there is no element in the table. When there is no element in the table, the AT END part will be executed and the control will be transferred to the paragraph named 3000-EXIT.

The following rules apply for the SEARCH verb.

a) The SEARCH verb can only be applied to a table which has the OCCURS clause and INDEXED BY phrase.

b) Before the use of the SEARCH verb, the index must have some initial value. The initial value must not exceed the size of the table. If it exceeds, the search is terminated immediately. Then if the AT END clause is specified, statements after AT END will be executed, other wise the control passes to the next sentence.

c) If AT END is not used and the end of the table is reached, the control will be automatically transferred to the next sentence.

d) The SEARCH verb starts with the initial value of the index and tests whether the conditions stated in the WHEN clauses have been satisfied or not. If none of the conditions are satisfied the index is incremented automatically by 1. The process is continued until the index value exceeds the size of the table and the search is terminated. When one of the conditions is satisfied before the index value crosses the size of the table, the statements following the condition in the relevant WHEN clause are executed. If these statements do not transfer the control elsewhere, after their execution, it is transferred to the next sentence. The value of the index remains set at the point where the condition has been satisfied.

SI Asia Pacific,, Singapore 71

Page 72: Cobol Notes v01

e) The INDEXED by phrase for a table can include more than one index names, in such cases the index named first is implicitly incremented by the SEARCH verb.

f) When the SEARCH terminates without finding the particular element then the index of the table has no predictable value.

The following program is used to get the capital of a country by providing the country name as the input.

000001 IDENTIFICATION DIVISION. 000002 PROGRAM-ID. LAB24. 000003 ENVIRONMENT DIVISION. 000004 DATA DIVISION. 000005 WORKING-STORAGE SECTION. 000006 01 CCT-REC. 000007 05 CCP-TABLE OCCURS 10 TIMES 000008 INDEXED BY INDEX1. 000009 10 COUNTRY PIC X(10). 000010 10 CAPITAL PIC X(10). 000011 01 WS-CNT PIC 9(2) VALUE 1. 000012 01 WS-COUNTRY PIC X(10). 000013 PROCEDURE DIVISION. 000014 0000-MAIN. 000015 PERFORM 1000-ACCEPT THRU 1000-EXIT 10 TIMES000016 ACCEPT WS-COUNTRY FROM SYSIN. 000017 PERFORM 2000-FIND THRU 2000-EXIT. 000018 STOP RUN. 000019 0000-EXIT. 000020 EXIT. 000021 1000-ACCEPT. 000022 ACCEPT CCP-TABLE(WS-CNT) FROM SYSIN. 000023 ADD 1 TO WS-CNT. 000024 1000-EXIT. 000025 2000-FIND. 000026 SET INDEX1 TO 1. 000027 SEARCH CCP-TABLE 000028 AT END DISPLAY "THE PASSED COUNTRY IS NOT LISTED." 000029 WHEN COUNTRY(A1) = WS-COUNTRY 000030 DISPLAY COUNTRY(A1) " ---> " CAPITAL(A1). 000031 2000-EXIT. 000032 EXIT.

SI Asia Pacific,, Singapore 72

Page 73: Cobol Notes v01

8.3 Searching a Multi-dimensional Table

Although the SEARCH verb is to be used only for one-dimensional tables, it can also be applied for a single dimension of a multi-dimensional table. The following is an example of such use of the SEARCH verb. Suppose, in a class there are 100 students and each student appears in 6 subjects. Each element of the table contains the registration number, name of the student and the names of the subjects and marks obtained in these subjects. Consider the following DATA DIVISION statements.

01 STUDENT-TABLE.02 STUDENT-DTLS OCCURS 100 TIMES INDEXED BY IDX1.

03 REG-NO PIC 9(5).03 STUDENT-NAME PIC X(30).

03 RESULT-TABLE OCCURS 6 TIMES INDEXED BY IDX2.

04 SUBJECT PIC X(15).04 MARKS PIC 9(3).

Now our requirement is to search the marks of all the 6 subjects of each student. If it is greater than 70, we want to display the registration number, name of the student, name of the subject and the corresponding marks. To solve this problem, we can write the following PROCEDURE DIVISION statements.

PERFORM 3100-CHECK-MARKS THRU 3100-EXITVARYING IDX1 FROM 1 BY 1 UNTIL IDX1 > 100.

3100-CHECK-MARKS.SET IDX2 TO 1.

3100-SEARCH.SEARCH RESULT-TABLE AT END GO TO 3100-EXIT

WHEN MARKS (IDX1, IDX2) > 70DISPLAY REG-NO (IDX1), STUDENT-NAME (IDX1),

SUBJECT (IDX1, IDX2), MARKS (IDX1, IDX2)SET IDX2 UP BY 1GO TO 3100-SEARCH.

3100-EXIT.EXIT.

8.4 BINARY SEARCH

The search statement that you have learned is known us linear search (or serial search). Now we will see how to use binary search. Normal search verb is applicable for the any tables either sorted or non-sorted. It will begin searching of elements by the starting value of an index and proceeds in a linear fashion. In the case of binary search it will work only on sorted table. So the table must be defined with OCCURS clause and ASCENDING/DESCENDING option. In order to declare a table like this, you can use the following format.

Format:

<data name> OCCURS <integer> TIMES

SI Asia Pacific,, Singapore 73

Page 74: Cobol Notes v01

ASCENDING KEY IS data name1, data name2…INDEXED BY index name1, index name2…

Format for binary search is with OCCURS clause along with ASCENDING OR DESCENDING KEY. If more than one data name is used, the first is the major key and the second is the next major key.

The format of Binary Search statement is given below:

SEARCH ALL <Id1> [AT END <imperative statement>]WHEN <condition1> [NEXT SENTENCE]WHEN <condition2> [NEXT SENTENCE]……..

Example:

Suppose you have the following tables and you wish to search an account number in the table, you can use the following statements.

The table declaration in DATA DIVISION is as follows:

01 SAVING-BANK-ACCT.02 ACCT-TABLE OCCURS 100 TIMES ASCENDING KEY IS AC-NO

INDEXED BY INDEX1.03 AC-NO PIC 9(6).03 NAME-OF-THE-PERSON PIC X(20).03 AMOUNT PIC 9(6)V99.

The PROCEDURE DIVISION which is used to search the above table will be as follows:

SEARCH ALL ACCT-TABLE AT END DISPLAY ‘ACCOUNT NUMBER IS NOT PRESENT’ WHEN AC-NO (INDEX1) = WS-AC-NO

DISPLAY WS-AC-NO, NAME-OF-THE-PERSON (INDEX1), AMOUNT (INDEX1).

It is to be noted that there is a difference in the search statement. In the case of linear search the format is SEARCH and in the case of binary search the format is SEARCH ALL. In binary search process, first the table is divided into two halves and determines in which half the search item is present. The half to which the item belongs is again divided and the same process is continued. This type of search is called a Binary Search. Note that SET verb is not needed for initializing the index.

Chapter 9

Handling Strings

SI Asia Pacific,, Singapore 74

Page 75: Cobol Notes v01

9.1 Introduction

A string is a collection of characters. All the identifiers having a DISPLAY usage can be considered to be a string. String manipulations includes comparing two strings, replacing characters, searching or counting for occurrences of characters, concatenation of two or more strings and splitting a string to one or more strings.

9.2 The INSPECT VERB

The INSPECT verb enables the programmer to tally and/or replace the occurrences of a single character or groups of characters in a data field. There are three formats of INSPECT which are described below:

Format 1:

INSPECT identifier-1 TALLYING

ALL identifier-3Literal-1

, identifier-2 FOR , LEADING

CHARACTERS

. . . BEFOREINITIAL identifier-4 . . .

AFTER literal-2

The following rules may be noted when this option is used.

a) All identifiers must be elementary items with usage DISPLAY. Identifier-1 can, however, be a group item having its subordinate items with usage DISPLAY.

b) The contents of identifier-1 are scanned for the occurrence of the specified characters in a left-to-right manner.

c) Unlike the EXAMINE statement, there is no special register called TALLY. Identifier-2 is the field where the count will be stored.

d) In the case of the ALL phrase, the characters specified by identifier-3 or literal-1 are matched against the characters of identifier-1 and for each match the value of the identifier-2 is increased by 1.

e) In the case of the LEADING phrase, only the contiguous occurrence of identifier-3 or literal-1 starting from the leading position of identifier-1 are examined, and for each match, identifier-2 is increased by 1. the search terminates as soon as no match occurs.

f) If the CHARACTERS phrase is specified, identifier-2 is increased by 1 for each character in identifier-1.

g) The BEFORE or AFTER phrase only limits the length of identifier-1 to be searched. BEFORE means that the leading portions of identifier-1 up to (but not including) the first occurrence of identifier-4 or literal-2 is searched. AFTER means that the trailing portions of identifier-1 after the first occurrence of literal-4 or literal-2 is searched.

SI Asia Pacific,, Singapore 75

Page 76: Cobol Notes v01

Example 1:

Let us consider the following PROCEDURE DIVISION statement.

INSPECT MY-STRING TALLYING TALLY-COUNT FOR ALL “S”.

Let the picture of MY-STRING be X(26) and suppose its content before the execution of the above statement is as follows:

“SPORE CONSULTANCY SERVICES”

If TALLY-COUNT (whose picture is say, 99) originally contains 08, then after the execution of the statement, TALLY-COUNT will contain 12 as there are a total of 4 ‘S’ in MY-STRING. On the other hand, if ALL in the statement is changed to LEADING, TALLY-COUNT will be increased to 09 as there is only one leading ‘S’. If CHARACTERS

is specified instead of ALL “S”, TALL-COUNT will be increased to 34 as there are a total of 26 characters in MY-STRING.

Example 2:

The following the is the PROCEDURE DIVISION statement

INSPECT WS-STRING TALLYING TALLY-1 FOR ALL “ABC”BEFORE INITIAL “.” AFTER INITIAL “Z”

If before the execution of this statement, WS-STRING whose picture is X(20) contains

“ BACDABCZPABCABCP.Q”

TALLY-1 whose picture is 99 contains 02, and then after the execution of the statement TALLY-1 will contain 04. This is because the group ABC occurs twice after the first occurrence of Z in WS-STRING.

Example 3:

Let us consider the following DATA DIVISON entries01 WS-CNT1 PIC 9 VALUE IS ZERO.01 WS-CNT2 PIC 9 VALUE IS ZERO.01 WS-A PIC 9(5).99.

Now, to separately find how many zeros there are in WS-A to the left and right of the decimal point, the following statement may be specified.

INSPECT A TALLYING WS-CNT1 FOR ALL “0”BEFORE INITIAL “.” WS-CNT2 FOR ALL “0”AFTER INITIAL “.” .

Format 2:

INSPECT identifier-1 REPLACING

SI Asia Pacific,, Singapore 76

Page 77: Cobol Notes v01

Identifier-5BEFORE identifier-6CHARACTERS BY INITIAL

Literal-3 AFTER literal-4

ALL identifier-7 identifier-8

, LEADING , BY literal-5 literals-6

FIRST

BEFORE identifier-9INITIAL . . . . . .

AFTER literal –7

The following are the rules for this option.

a) This option of the INSPECT verb allows the user to replace matched characters by the specified characters mentioned by the identifier or literal after the word BY.

b) If the CHARACTERS phrase is specified, identifier-5 or literal-3 must refer to a single character.

c) The ALL and LEADING phrases have the same meaning as in option 1 except hat no count is increased. Instead, the matched characters are replaced by the specified characters.

d) When the FIRST phrase is used, the leftmost occurrence of identifier-7 or literal-5 matched within the contents of identifier-1 is replaced by identifier-8 or literal-6.

e) The BEFORE and AFTER phrases have the same meaning as in option 1.f) The size of identifier-7/literal-5 must be equal to that of identifier-8/literal-

6. if literal-5 is a figurative constant, identifier-8/literal-6 must denote a single character. If literal-6 is a figurative constant, its size is considered equal to that of identifier-7/literal-5.

Example 4:

Frequently, we need to replace the leading blanks in a field by zeros. For example, let WS-AMOUNT described with picture 9(5), be a field in the record description for an input file. If the field contains leading blanks, its contents will be treated as non-numeric. In order to replace the leading blanks by zeros, we can use the statement.

INSPECT WS-AMOUNT REPLACING LEADING “ ” BY “0”.

SI Asia Pacific,, Singapore 77

Page 78: Cobol Notes v01

Example 5:

Let WS-STRING be an alphanumeric field. We wish to replace all occurrences of the characters “*”, “/” and “ ” (space) in WS-STRING by “-“, “\” and “+” respectively. The following statement will serve the purpose.

INSPECT WS-STRING REPLACING ALL“*” BY “-“, “/” BY “\”, “ “ BY “+”

Format 3:

INSPECT identifier-1 TALLYING< tallying part as in option 1>REPLACING< replacing part as in option 1>

This option is a combination of the previous two options.

Example 6:

In example 5, if we also want to find the total number of replaced characters, the following statement will serve the purpose.

INSPECT WS-STRING TALLYING WS-CNT REPLACING ALL “*” BY “-“

“/” BY “\” “ “ BY “+”

In this case WS-CNT will contain the total number of such replaced characters. For example, if there are 12 such characters, WS-CNT will contain 12 if its initial value was 0.

SI Asia Pacific,, Singapore 78

Page 79: Cobol Notes v01

9.3 STRING AND UNSTRING VERBS

Two or more strings of characters can be combined to form one longer string with the help of the STRING statement, whereas the UNSTRING statement facilitates the splitting of one string to many sub-strings. These verbs can also be used to transfer characters from a string to another string starting at some particular character position either in the receiving field or in the sending field.

9.3.1 The STRING verb

Format:

identifier-1 identifier-2STRING , . . . literal-1 literal-2

identifier-3 DELIMITED BY literal-3

SIZE

Identifier-4 identifier-5, , . . .

literal-4 literal-5

identifier-6 DELIMITED BY literal-6 . . .

SIZE

INTO identifier-7

; ON OVERFLOW imperative-statement

The following rules should be followed when this verb is used.

a) This statement is used to concatenate one or more strings into one by placing them side-by-side. The strings to be concatenated are the complete or partial contents of literals/identifiers-1,2,4,5, etc. referred to as sending fields. The concatenated string is placed in identifier-7 referred to as the receiving field.

b) Sending strings may be alphanumeric literals, figurative constants or identifiers with usage DISPLAY. Figurative constants are treated as single characters.

c) The receiving string, i.e., identifier-7 must also be with usage DISPLAY. If certain portions of the receiving string does not receive any character, these portions will retain the original characters.

d) If the DELIMITED BY SIZE phrase is used, the entire contents are transferred from left to right into identifier-7 until the right-most character is transferred or identifier-7 is full. For example:

01 WS-STR-1 PIC X(4) VALUE “RAIN”.

SI Asia Pacific,, Singapore 79

Page 80: Cobol Notes v01

The statement,

STRING “MA” DELIMITED SIZE INTO WS-STR-1.

Will make the content of WS-STR-1 TO BECOME “MAIN”. It may be noted that the characters I, N in WS-STR-1 remain unchanged.

e) If the DELIMITED phrase without the SIZE option is used, the characters of the sending strings are transferred from left to right to identifier-7. the transfer of characters to identifier-7 will be terminated when any one of the following conditions takes place.

o The end of the sending strings is reached.o The character specified in the DELIMITED phrase is encountered.o Identifier-7 is full.

The character specified in the DELIMITED phrase (e.g., literals/identifiers-3 and 6) is not transferred.

Example 1:

Let us consider the following DATA DIVISION entries.

01 WS-STR-1 PIC X(5) VALUE “SPORE”.01 WS-STR-2 PIC X(4) VALUE SPACES.

Now the execution of the statement

STRING WS-STR-1 DELIMITED BY “O” INTO WS-STR-2

Will store “SP “ in WS-STR-2. It may be noted that in this case, the character “O” specified in the DELIMITED phrase, is encountered before reaching the end of WS-STR-1. The character ‘O’ is not transferred to WS-STR-2.

Example 2:

The following are the DATA DIVISION entries.

01 WS-STR-1 PIC X(4) VALUE “ABCD”.01 WS-STR-2 PIC X(6) VALUE “Ma UB ”.01 WS-STR-3 PIC X(9) VALUE “121,34,56”.01 WS-STR-4 PIC X(14) VALUE SPACES.

STRING WS-STR-1, WS-STR-2, WS-STR-3 DELIMITED BY“ ” , “,” INTO WS-STR-4.

This statement will make the contents of WS-STR-4 to be “ABCDMA121 “. In this example, first, all the four characters of WS-STR-1 are transferred to WS-STR-4 as WS-STR-1 does not contain any one of the delimiters. Next, only two characters of WS-STR-2 are transferred to WS-STR-4, as the third character of WS-STR-2 is a delimiter. Lastly, three characters of WS-STR-3 are transferred to WS-STR-4, as the fourth character of WS-STR-3 is a delimiter. The remaining characters of WS-STR-4 are spaces as originally WS-STR-4 contains spaces.

SI Asia Pacific,, Singapore 80

Page 81: Cobol Notes v01

f) The delimiters (i.e., identifier-3/literal-3 and identifier-6/literal-6) in the DELIMITED phrase can denote one or more characters. When identifier is used it must have DISPLAY usage.

g) There can be several delimiters in a STRING statement. If any one of these delimiters is encountered, the transmission of characters will be terminated.

h) The sending data items are transferred in the order of their appearance in the STRING statement. The rules of alphanumeric data transfer are applicable, except that no space filling will be provided.

i) As each character is transferred to the receiving field, the value of identifier-8 is increased by 1. For example, let WS-STR-1, WS-STR-2, WS-STR-3 and WS-STR-4 be described as before and let the statement be

STRING WS-STR-1, WS-STR-2, WS-STR-3 DELIMITED BY “ ”, “,” INTO WS-STR-4 WITH POINTER CHARACTER-POSITION.

j) If we assume that CHARACTER-POSITION initially contains 03 then after the execution of the statement WS-STR-4 and CHARACTER-POSITION will contain “ ABCDMA121 ” and 12 respectively.

k) The STRING statement terminates when all data has been transferred or the end of the data item referred to by identifier-7 has been reached. In the latter case, if further characters cannot be transferred owing to the fact that end of identifier-7 has been reached, the statement following the OVERFLOW phrase will be executed, if specified. If the OVERFLOW phrase is not specified, the control is transferred to the next executable statement in sequence.

Example 3:

Suppose there is a field called WS-NAME defined as follows:

01 WS-NAME.03 FIRST NAME PIC X(10).03 MIDDLE-NAMEPIC X(6).03 SURNAME PIC X(20).

We assume that in each field the characters are stored as left justified. Now, while printing this name we want to print SURNAME first, then the FIRST-NAME and finally the MIDDLE-NAME by leaving only one space after each of these names. Only the set of non-blank characters from the left of the fields are to be considered.

Let the receiving field be defined as:

01 WS-OUTREC PIC X(39).

We also define the following field:01 WS-A PIC X VALUE SPACE.

The following statement is a solution of the above problem.

STRING SURNAME DELIMITED BY SPACES,WS-A DELIMITED BY SIZE,FIRST-NAME DELIMITED BY SPACES,WS-A DELIMITED BY SIZE,MIDDLE-NAME DELIMITED BY SPACES

SI Asia Pacific,, Singapore 81

Page 82: Cobol Notes v01

INTO WS-OUTREC.

9.3.2 The UNSTRING verb

Format:

UNSTRING identifier-1

Identifier-2 identifier-3DELIMITED BY [ALL] , OR [ALL] .. .

Literal-1 literal-2

INTO identifer-4 [, DELIMITER IN identifier-5]

[, COUNT IN identifier-6 ]

, identifier-7 [, DELIMITER IN identifier-8 ]

[, COUNT IN identifier-9 ] . . .

[ TALLYING IN idenyifier-10] [ ; ON OVERFLOW imperative-statement]

The following rules should be followed when the UNSTRING verb is used:

a) The data in identifier-1 is separated and placed in multiple-receiving fields, namely, identifier-4, identifier-7, etc.

b) The sending field, i.e., identifier-1 can only be an alphanumeric field with DISPLAY usage.

c) The receiving fields, i.e., identifier-4, identifier-7, etc., must also have DISPLAY usage. They can be described as alphabetic, alphanumeric or numeric fields.

d) All literals must be described as nonnumeric literals. If literal is a figurative constant, it is treated as a single character.

e) If the DELIMITED BY phrase is not used, the characters in the sending field are transferred from left to right into the receiving fields until the rightmost character of the sending field is transferred or the receiving fields are full.

f) If the DELIMITED BY phrase is used, the sending field is examined for the occurrence of the character or characters (known as delimiter) in the DELIMITED BY phrase.

When two contiguous delimiters are encountered and the word ALL is not mentioned, the first delimiter terminates the transfer of data to the current-receiving field and the second delimiter causes the filling of the next receiving field either with spaces or with zeros depending on the description of the field. When ALL is specified, two or more contiguous occurrences of the delimiter are together considered as a single delimiter.

Example 4:

Let us consider the following DATA DIVISION entries.

SI Asia Pacific,, Singapore 82

Page 83: Cobol Notes v01

01 WS-STR-1 PIC X(10).01 WS-STR-2 PIC X(10).01 WS-STR-3 PIC X(15).01 WS-STR-DATA PIC X(38) VALUE IS “R.K. LAXMAN.”

Now, the execution of the statement

UNSTRING WS-STR-DATA DELIMITED BY “.”INTO WS-STR-1, WS-STR-2, WS-STR-3

Will store the character ‘R’ followed by 9 blanks in WS-STR-1, the character ‘K’ followed by 9 blanks in WS-STR-2 and ‘LAXMAN’ followed by 9 blanks in WS-STR-3. The first period (.) after R in WS-STR-DATA terminates the transfer of characters from this sending field to the first receiving field WS-STR-1. The second period after K again terminates the transfer of characters to the second receiving field WS-STR-2 and ultimately the third period terminates the transfer of characters to WS-STR-3.

Example 5:

Let us consider the same DATA DIVISION entries as in Example 2 and let WS-STRING contain “P.R RAMA RAO ”.

The statement

UNSTRING WS-STRING DELIMITED BY “.” OR ALL “ ” INTO WS-STR-1, WS-STR-2, WS-STR-3

Will store “P ” in WS-STR-1, “R ” in WS-STR-2 and “RAO” in WS-STR-3. In this case the termination of the transfer of characters takes place if either the delimiter period (.) or spaces is encountered. The first termination takes place due to the delimiter period whereas the second and third terminations take place due to spaces.

The optional DELIMITER IN phrase or COUNT IN phrase can be specified only if the DELIMITED BY phrase is used. The delimiting character will be moved to the identifier specified in the DELIMITER IN phrase.

Chapter 10

Subroutines

10.1 Introduction

Subroutines are programs that are written for a specific purpose and which can be re-used by program any number of times or by several programs commonly. It is just like normal Cobol program with all the four divisions. Subroutines promote the modular way of programming. A paragraph can also be considered as a module but it is limited to only one program whereas subroutines are compiled and kept separately.

SI Asia Pacific,, Singapore 83

Page 84: Cobol Notes v01

Subroutines are the means of inter-program communication. Subroutines are called from the main program, and after execution, subroutine should return the control back to the caller program. A subroutine can call other subroutines as well.

10.2 The CALL Statement

The subroutine can be called from the main program using a ‘CALL’ statement. Calling program can also pass values to a subroutine.

Format:

CALL “<sub-routine-name>” | <identifier> USING <data-name-1>, <data-name-2>, …….. [ ON OVERFLOW imperative statement ]

Example 1:

……. CALL “SUBR1”. ……. This statement calls a subroutine ‘SUBR1’.

Example 2:

……. CALL “SUBR1” USING WS-A, WS-B, WS-C. DISPLAY WS-C.

This statement calls a subroutine ‘SUBR1’; along with, it also passes three variables. These variable values can be retrieved and some processing can be done within the subroutine.

Example 3: MOVE ‘SUBR1’ TO WS-SUBR. CALL WS-SUBR USING WS-A, WS-B, WS-C.

DISPLAY WS-C.As you can see from the above example that a subroutine name can be stored

in a variable and can be used with the call statement. This statement has the same effect as the earlier example but here; the flexibility lies in calling different subroutines with the same CALL statement, this type of call is referred as dynamic call. The latter is called as a static call.

The variables that are passed to a subroutine are called actual parameters and when the subroutine receives them, they are formal parameters in the subroutine.

WORKING-STORAGE SECTION and PROCEDURE DIVISION in the subroutine

The subroutine is just like the normal program with all the four divisions but there are few additions and considerations such as:

SI Asia Pacific,, Singapore 84

Page 85: Cobol Notes v01

Subroutine must have a LINKAGE SECTION in DATA DIVISION, which should declare all the formal variables, which are being accepted. All the declared variables should not contain VALUE clause

PROCEDURE DIVISION must have USING phrase to connect and accept the parameters that are being passed from the caller program

Logical end of the program should be done using EXIT PROGRAM or GOBACK statement; STOP RUN should not be used as the control needs to be passed back again to the caller program. The difference between EXIT PROGRAM and GOBACK is that the EXIT PROGRAM must be the only statement in the paragraph whereas GOBACK can be coded along with other commands in the paragraph (it may depend on compilers)

Example:

LINKAGE SECTION. 77 LS-A PIC 9(2).

77 LS-B PIC 9(2).77 LS-C PIC 9(3).

PROCEDURE DIVISION USING LS-A, LS-B, LS-C. 0000-MAIN.

PERFORM 1000-COMPUTE THRU 1000-EXIT.PERFORM 2000-RETURN THRU 2000-EXIT.

0000-EXIT. EXIT.

1000-COMPUTE. COMPUTE LS-C = LS-A + LS-B.

1000-EXIT. EXIT.

2000-RETURN. EXIT PROGRAM.

2000-EXIT. EXIT.

Chapter 11

File Handling

11.1 Introduction

In order to use files (datasets) in COBOL, you will have to do few things. The first step is to select the file in the FILE-CONTROL paragraph of INPUT-OUPUT SECTION. Second step is to declare the file definitions in the FD entry of FILE SECTION. Next step is to use the file in PROCEDURE DIVISION. The major procedure division statements are OPEN, READ, WRITE, REWRITE, DELETE, START and CLOSE.

COBOL is powerful enough to handle both VSAM and non-VSAM datasets.

SI Asia Pacific,, Singapore 85

Page 86: Cobol Notes v01

11.2 Sequential File Handling

The characteristics of each of the files handled in a program are specified in the ENVIRONMENT DIVISION and DATA DIVISION. Those characteristics that depend primarily on the input-output device and the computer system are described in the ENVIRONMENT DIVISION, while characteristics that are of a general nature are described in the DATA DIVISION.

11.2.1 The SELECT Entry

The SELECT entry for a sequential dataset is give below:

ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL.

SELECT <file-name> ASSIGN TO <ddname>

ORGANIZATION IS SEQUENTIAL

ACCESS MODE IS SEQUENTIAL

FILE STATUS IS data-name-1

The ORGANIZATION and ACCESS MODE is optional, if omitted COBOL will assume sequential organization and access mode. The ORGANIZATION indicates the dataset organization and the ACCESS MODE indicates the way in which the dataset will be accessed by the program.

The FILE STATUS is used to check the status of the dataset after every file operations. For example, after opening the file you can check the file status to verify that the open is successful. The data-name-1 defined in FILE STATUS must be defined in WORKING-STORAGE SECTION with a picture clause X(2) or 9(2).

11.2.2 The FILE SECTION Entries

The general characteristics of a file are described in the file description (FD) entry of the FILE SECTION of DATA DIVISION. The various clauses in the FD entry specify the said characteristics. The general format of the FD entry is given below.

DATA DIVISION.FILE SECTION.

FD file-name

RECORDS BLOCK CONTAINS integer –1

CHARACTERS

RECORDS CONTAINS integer-2 CHARACTERS

SI Asia Pacific,, Singapore 86

Page 87: Cobol Notes v01

RECORD IS STANDARD LABEL

RECORDS ARE OMITTED

RECORDING MODE IS F [V]

(a) BLOCK CONTAINS Clause

BLOCK CONTAINS clause is used to specify the block size either in terms of records or in terms of characters. BLOCK CONTAINES 100 RECORDS means that there are 100 records in the block. If each of the record contains 50 characters, the said clause can be written as BLOCK CONTAINS 5000 CHARACTERS. When the block size is specified in CHARACTERS, care should be taken to ensure that the block size is a multiple of the record size. IT is not required to give the block size as the COBOL compiler will get the actual block size of the dataset being used.

(b) RECORD CONTAINS Clause

This clause specifies the size of a record. Thus RECORD CONTAINS 50 CHARACTERS means that each record of this file consists of 50 characters. The record is described in the record-description entries that follow the FD entry. The compiler determines the size of the record from these descriptions. So the compiler does not use the RECORD CONTAINS clause. It is used only for documentary purposes.

(c) LABEL RECORD CLAUSE

This clause specifies whether or not the standard labels should be present in the magnetic-tape files. The word STANDARD indicates that the file should have standard labels, while the word OMITTED specifies that the file is unlabelled. It may be noted that the clause LABEL RECORDS ARE OMITTED is generally used for printer files.

(d) RECORDING MODE CLAUSE

This clause is used to specify whether the dataset has fixed or variable length records. RECORDING MODE IS F, means the data set contains only fixed length records and RECORDING MODE IS V, means the record length varies. By default the compiler will assume fixed record length.

11.2.3 The Procedure Division Statements

In order to use a sequential dataset in COBOL, you can use the following statements.

(a) The OPEN statement

Before start using a dataset, it must be opened in the proper mode. The open mode determines the way in which the dataset is being used in the program. A file can be opened in any one of the four open modes – INPUT, OUTPUT, EXTEND and I-O.

When a dataset is opened in the INPUT mode, it becomes an input dataset. There must be an existing dataset available on the specified medium. The records

SI Asia Pacific,, Singapore 87

Page 88: Cobol Notes v01

can be read sequentially through subsequent executions of READ statements on the dataset.

OUTPUT mode is used when dataset is to be created for the first time. Records can be placed onto the dataset through subsequent executions of the WRITE statements.

The EXTEND mode also opens a dataset for output, the record will be appended to the end of the dataset. i.e. the subsequent execution of the WRITE statements on the dataset are appended by adding new records at its end.

The I-O mode is used to update a record in a dataset. It is to be noted that you must open the dataset in I-O mode if you wish to read and rewrite records. So it is usually known as update mode.

Format:

OPEN INPUTOUTPUT file-name-1 [ , file-name-2 ] . . .EXTENDI-O

Examples:

OPEN INPUT F100.OPEN INPUT F100 F200.OPEN INPUT F100 OUTPUT F200.OPEN INPUT F300 OUTPUT F400 F500 EXTEND F500

(b) The WRITE Statement

The WRITE statement is used to add new record the sequential dataset. The dataset may reside on direct access volumes, tapes or cartridge.

Format:

WRITE record-name FROM identifier

As a result of the execution of the WRITE statement, the record is released from the record buffer and is written onto the physical dataset. The first execution of the WRITE statement writes the first record and subsequent executions write the records sequentially. The FROM option is used to write the record from another record. For example, suppose you want to read a dataset and write the content of the record to another dataset you can use FROM option.

MOVE F200-EMP-RECORD TO F100-EMP-RECORD.WRITE F100-EMP-RECORD.

The above statements can be changed as given below:

WRITE F100-EMP-RECORD FROM F200-EMP-RECORD.

SI Asia Pacific,, Singapore 88

Page 89: Cobol Notes v01

In order to use the WRITE statement the file must be opened in the OUTPUT or EXTEND mode.

(c) The REWRITE Statement

The REWRITE statement is used to update an existing record in the dataset.

Format:

REWRITE record-name FROM identifier

The format of REWRTIE is similar to that of a WRITE statement and the FROM option has the same meaning.

The REWRITE statement can only be used if the file is opened in the I-O mode and its execution must be preceded by the execution of a successful READ statement on the file. The REWRITE statement replaces the last-record read. After the execution of the REWRITE statement, the record is no longer available in the record buffer.

Example:

REWRITE F100-EMP-RECORD.REWRITE F100-EMP-RECORD FROM F200-EMP-RECORD.

(d) The READ statement

The READ statement is used to read a record from a dataset. The dataset must be opened in INOUT or I-O mode.

Format:

READ file-name [INTO record-name] [AT END imperative-statement]

When you read a record from a dataset the record will be placed in the record area of that dataset specified in FD entry. If you want to place the record in different place, say in a working storage area, you can use INTO clause. The statement specified in AT END will execute if the dataset is being read completely. This means that if you try to read the dataset beyond the last record the control will transfer to AT END and the statements specified in AT END will be executed.

Example:

READ F100.READ F100 AT END MOVE ‘Y’ TO EOF-FLAG.READ F100 INTO WS-F100-RECORD AT END MOVE ‘Y’ TO EOF-FLAG.

(e) The CLOSE Statement

SI Asia Pacific,, Singapore 89

Page 90: Cobol Notes v01

The CLOSE statement is used to close a dataset, which was opened in the program.

Format:

CLOSE file-name-1 [file-name-2, ……]

The CLOSE statement terminates the processing of the dataset. If you want to process the dataset again, you will have to open it using OPEN statement.

Example:

CLOSE F100.CLOSE F100 F200 F300.

The following program is used to read a sequential dataset and count the number of records in it.

000001 IDENTIFICATION DIVISION. 000002 PROGRAM-ID. LAB25. 000003 ENVIRONMENT DIVISION. 000004 INPUT-OUTPUT SECTION. 000005 FILE-CONTROL. 000006 SELECT F100 ASSIGN TO F100 000007 ORGANIZATION IS SEQUENTIAL 000008 ACCESS MODE IS SEQUENTIAL. 000009 DATA DIVISION. 000010 FILE SECTION. 000011 FD F100 000012 LABEL RECORDS ARE STANDARD 000013 RECORDING MODE IS F. 000014 01 F100-REC PIC X(50). 000015 WORKING-STORAGE SECTION. 000016 01 WS-COUNT PIC 9(5) VALUE ZERO. 000017 01 WS-EOF PIC X VALUE 'N'.

000018 88 EOF VALUE 'Y'. 000019 PROCEDURE DIVISION. 000020 0000-MAIN. 000021 PERFORM 1000-OPEN THRU 1000-EXIT. 000022 PERFORM 2000-READ THRU 2000-EXIT. 000023 PERFORM 3000-COUNT THRU 3000-EXIT UNTIL EOF. 000024 DISPLAY 'TOTAL RECORDS = ' WS-COUNT. 000025 PERFORM 4000-CLOSE THRU 4000-EXIT. 000026 STOP RUN. 000027 0000-EXIT. 000028 EXIT. 000029 1000-OPEN. 000030 OPEN INPUT F100. 000031 1000-EXIT. 000032 EXIT. 000033 2000-READ. 000034 READ F100 AT END MOVE 'Y' TO WS-EOF. 000035 2000-EXIT.

000036 EXIT. 000037 3000-COUNT. 000038 ADD 1 TO WS-COUNT.

SI Asia Pacific,, Singapore 90

Page 91: Cobol Notes v01

000039 PERFORM 2000-READ THRU 2000-EXIT. 000040 3000-EXIT. 000041 EXIT. 000042 4000-CLOSE. 000043 CLOSE F100. 000044 4000-EXIT.

000045 EXIT.

11.3 Processing Variable length record In the case of variable length record, the RECORD CONTAINS and BLOCK CONTAINS clauses are quite different.

Format:

RECORDSBLOCK CONTAINS integer-1 TO integer-2

CHARACTERS

RECORD CONTAINS integer-3 TO integer-4 CHARACTERS

RECORDING MODE IS V

The BLOCK CONTAINS clause indicates the size of the buffer to be set up for the dataset. Integer-1 specifies the average size and the Integer-2 specifies the maximum size. When the RECORDS option is used, the buffer will be sufficient to hold the integer-2 of the largest record. What is actually happening here is that the buffer is considered as a block.

The RECORD CONTAINS clause indicates the size of the record. Integer-3 and integer-4 respectively denote the minimum and maximum sizes of the records in the file.

The RECORDING MODE clause denotes that the record is variable (V) length.

All other clauses described for fixed-length records are also available in the case of variable-length records.

11.4 Generating reports

Sometime you may wish to generate reports. Writing records to a printer file similar to that in an ordinary dataset. But there are some additional features of WRITE statement are used while generating reports.

Format:

WRITE record-name FROM [identifier-1 ]

identifier-2 LINEBEFORE integer LINESAFTER ADVANCING

PAGE

SI Asia Pacific,, Singapore 91

Page 92: Cobol Notes v01

The additional feature of WRITE statement, which is used to generate report, is ADVANCING option. It is use to advance the print head to the next page so that the printing will start in the new page. Also you can specify the number of lines to be advanced before or after printing.

Example:

WRITE F300-OUTPUT-RECORD FROM WS-HEADER-1.WRITE F300-OUTPUT-RECORD FROM WS-HEADER-1

AFTER ADVANCING 2 LINES.WRITE F300-OUTPUT-RECORD FROM WS-HEADER-1

AFTER ADVANCING PAGE.

SI Asia Pacific,, Singapore 92

Page 93: Cobol Notes v01

The following program is used to print the report on SYSOUT.

000001 IDENTIFICATION DIVISION. 000002 PROGRAM-ID. LAB26. 000003 ENVIRONMENT DIVISION. 000004 INPUT-OUTPUT SECTION. 000005 FILE-CONTROL. 000006 SELECT E100 ASSIGN TO E100. 000007 DATA DIVISION. 000008 FILE SECTION. 000009 FD E100 000010 LABEL RECORDS ARE STANDARD 000011 RECORDING MODE IS F. 000012 01 E100-REC. 000013 05 EMPNO PIC X(4). 000014 05 ENAME PIC X(7). 000015 05 EDEPT PIC X(4). 000016 05 ESAL PIC 9(4). 000017 05 FILLER PIC X(61). 000018 000019 WORKING-STORAGE SECTION. 000020 01 WS-EOF PIC X VALUE 'N'. 000021 01 WS-SNO PIC 9(2) VALUE 1. 000022 01 HEAD-REC. 000023 05 FILLER PIC X(8) VALUE "S. No. ". 000024 05 FILLER PIC X(10) VALUE "Emp. No. ". 000025 05 FILLER PIC X(11) VALUE "Emp. Name ". 000026 05 FILLER PIC X(12) VALUE "Emp. Dept. ". 000027 05 FILLER PIC X(11) VALUE "Emp. Salary". 000028 01 LINER PIC X(55) VALUE ALL "=". 000029 01 OUT-REC. 000030 05 SNO PIC ZZ9. 000031 05 FILLER PIC X(5) VALUE SPACES. 000032 05 EMPNO PIC X(10). 000033 05 ENAME PIC X(11). 000034 05 EDEPT PIC X(12). 000035 05 ESAL PIC ZZZ9.99. 000036 PROCEDURE DIVISION. 000037 0000-MAIN. 000038 PERFORM 1000-OPEN THRU 1000-EXIT. 000039 PERFORM 2000-READ THRU 2000-EXIT 000040 UNTIL WS-EOF = 'Y'. 000041 PERFORM 9000-CLOSE THRU 9000-EXIT. 000042 STOP RUN. 000043 0000-EXIT. 000044 EXIT. 000045 1000-OPEN. 000046 OPEN INPUT E100. 000047 DISPLAY LINER. 000048 DISPLAY HEAD-REC. 000049 DISPLAY LINER. 000050 READ E100 AT END MOVE 'Y' TO WS-EOF. 000051 1000-EXIT. 000052 EXIT. 000053 2000-READ. 000054 MOVE CORR E100-REC TO OUT-REC.

SI Asia Pacific,, Singapore 93

Page 94: Cobol Notes v01

000055 MOVE WS-SNO TO SNO OF OUT-REC. 000056 DISPLAY OUT-REC. 000057 ADD 1 TO WS-SNO. 000058 READ E100 AT END MOVE 'Y' TO WS-EOF. 000059 2000-EXIT. 000060 EXIT. 000061 9000-CLOSE. 000062 CLOSE E100. 000063 DISPLAY LINER. 000064 9000-EXIT. 000065 EXIT.

SI Asia Pacific,, Singapore 94

Page 95: Cobol Notes v01

Chapter 12

SORT and MERGE

12.1 The SORT Statement

The SORT statement is used to perform internal sort in COBOL. It is used to arrange the records in an input dataset either in ascending or descending order. Suppose we have a dataset that contains unsorted records and we want to sort it in the ascending order of a key. In this situation you we can use the SORT verb in COBOL.

Format:

ASCENDINGSORT file-name-1 ON KEY data-name-1, [data-name-2, ..]

DESCENDING

ASCENDING ON KEY data-name-3, [data-name-4 ..]

DESCENDING

USING file-name-2 GIVINGfile-name-3.

The file-name-1 is the name of the work file, whereas the names of the input and output files are to be specified in file-name-2 and file-name-3 respectively. It is to be noted that the work file (file-name-1) should be defined in the SD (Sort Description) entry and not in the normal FD (File Description) entry.

The format of the SD entry is as follows:

SD file-name

RECORD CONTAINS integer-1 [ TO integer-2 CHARACTERS ]

RECORD ISDATA data-name-1 [, data-name-2 . . .]

RECORDS ARE

The clauses have the same meanings as in the case of FD entry. The record description of the work file should be done in the usual manner.

The following rules should be taken into consideration while specifying the SORT statement.

SI Asia Pacific,, Singapore 95

Page 96: Cobol Notes v01

a) The input, output as well as the work file are opened by the SORT statement before the sorting begins and are closed by the SORT statement itself after the sorting is over. So there should not be any OPEN or CLOSE statement specified with the input and output datasets.

b) There could be any number of SORT statements in a program.

c) You may use any number of keys to sort. Also you may sort one key in ascending and another in descending order, depends on the requirement.

d) All the keys on which the sorting is done, must appear with their descriptions in the record descriptions of file-name-1. These keys need not be described either in file-name-2 or in file-name-3. Note that the order of appearance of the keys in the SORT statement has no relevance to their positions within the record.

e) Keys in the SORT statement do not require any qualification even when they are identical to data names defined elsewhere.

f) When two or more records in the input file have identical keys, their relative order within the input file may not be retained in the output file.

g) The file-name-2 and file-name-3 must be sequential files.

Example:

Let us see an example. Assume that we have a sequential dataset with the following records description in the DATA DIVISION.

FD F100-EMP.01 F100-RECORD.

03 F100-EMP-ID PIC 9(5).03 F100-EMP-NAME PIC X(25).03 F100-DEPT PIC X(4).03 F100-BASIC-PAY PIC 9(7)V99.03 F100-ALLOWANCE PIC 9(5)V99.

Suppose we wish to sort this dataset first on F100-DEPT in ascending order and then within each department in the descending order of F100-EMP-ID. First we need to define a work file in the SD entry.

SD SORT-FILE.01 SORT-RECORD.

03 FILLER PIC X(30).03 DEPARTMENT PIC X(4).03 BASIC-PAY PIC 9(7)V99.03 ALLOWANCE PIC 9(5)V99.

FD F200-EMP.01 F200-RECORD PIC X(50).

The PRCOEDURE DIVISION statement will be written as follows.

SI Asia Pacific,, Singapore 96

Page 97: Cobol Notes v01

SORT SORT-FILE ON ASCENDING KEY DEPARTMENTDESCENDING KEY F100-EMP-IDUSING F100-EMP GIVING F200-EMP.

12.2 The MERGE Statement

We have seen the SROT statement in the previous section. Like sorting, the merging of files is frequently required in various commercial applications. From the previous section you can understand that the SORT statement require minimum 3 files; one work file, one input file and an output file. COBOL has the facility to merge two or more sequential dataset. If you need to merge files you can use the MERGE statement.

Format:

MERGE file-name-1 ON ASCENDING KEY data-name-1 ,data-name-2 ..

DESCENDING

ASCENDING ON KEY data-name-3 , data-name-4 . . .

DESCENDING

USING file-name-2 , file-name-3, file-name-4 . . .

GIVING file-name-5.

As in the case of SORT statement we need one work file and it must be defined in SD entry. The input dataset names and output dataset name must be specified in FD entry. The input files to be merged through the MERGE statement are specified in the USING phrase. These files must be sequential files and must be sorted on the merge keys. The rules of the SORT statement in respect of the ASCENDING/DESCENDING KEY phrases are also applicable in this case. The merged output file is specified in the GIVING phrase. All the files mentioned in the MERGE statement must have records of same size and the positions of the merge keys within the record descriptions of each of the files must be the same. When two records from different input files have identical keys, their relative positions within the merged file will be in the same order in which the input file names are specified in the USING phrase.

Example:

Let us see an example of MERGE statement. Assume that we have two sequential dataset with the following records description in the DATA DIVISION.

FD F100-EMP.

SI Asia Pacific,, Singapore 97

Page 98: Cobol Notes v01

01 F100-RECORD.03 F100-EMP-ID PIC 9(5).03 F100-EMP-NAME PIC X(25).03 F100-DEPT PIC X(4).03 F100-BASIC-PAY PIC 9(7)V99.03 F100-ALLOWANCE PIC 9(5)V99.

FD F200-EMP.01 F200-RECORD.

03 F200-EMP-ID PIC 9(5).03 F200-EMP-NAME PIC X(25).03 F200-DEPT PIC X(4).03 F200-BASIC-PAY PIC 9(7)V99.03 F200-ALLOWANCE PIC 9(5)V99.

Suppose we wish to merge these datasets and create single output dataset. Like SORT statement, MERGE also requires a work file and must be defined with SD as follows.

SD MERGE-FILE.01 MERGE-RECORD.

03 FILLER PIC X(30).03 DEPARTMENT PIC X(4).03 BASIC-PAY PIC 9(7)V99.03 ALLOWANCE PIC 9(5)V99.

The following file description is used as the output dataset.

FD F300-EMP.01 F300-RECORD PIC X(50).

The PRCOEDURE DIVISION statement will be written as follows.

MERGE MERGE-FILE ON ASCENDING KEY DEPARTMENTUSING F100-EMP, F200-EMP GIVING F300-EMP.

It is to be noted that as in the case of SORT statement the MERGE will automatically open and close the required files. So you should not code any explicit OPEN or CLOSE statement to these files.

SI Asia Pacific,, Singapore 98

Page 99: Cobol Notes v01

Chapter 13

Direct Access File Handling

13.1 INDEXED SEQUENTIAL and RELATIVE FILES

Files, which are stored on a direct access storage medium such as a magnetic disk, are often called as Direct Access Files. Records can be accessed either sequentially or randomly or dynamically under such organization of files. In the MVS environment, the direct access files (datasets) for random access are created and maintained by VSAM (Virtual Storage Access Method). Such datasets are created using IDCAMS utility. Therefore, hereafter, the knowledge of creation of such datasets under VSAM is assumed.

13.2 Handling INDEXED SEQUENTIAL Files (KSDS)

A record in a sequential file can be accessed only sequentially. If you want to access a record from sequential dataset randomly, say by using the employee number, there is no way to access it. To do this you will have to read the records sequentially from beginning to end and then match each record with the supplied key value. Where as in the case of indexed sequential data sets you will be able to access records either sequentially or randomly. However, in most applications it may be required to access records randomly by using a key value. Therefore the indexed sequential dataset will be access randomly in majority of the applications.

In indexed sequential datasets (also referred to as indexed files), the records are stored in the key sequence order (usually ascending order). In addition, some index tables are also created and maintained with the file. The purpose of the index tables is that they provide a means of identifying the groups of records in the file. Thus in order to have access to a record, first, the group to which a record belongs is identified with the help of the index tables. Then the group is sequentially searched to locate the record.

In order to use indexed datasets, we must create a VSAM keyed sequential dataset (KSDS). Generally in all mainframe applications we will be using KSDS as the master file. Since KSDS has a key associated with it you will be able to access the records by using the key value.

13.2.1 INPUT-OUTPUT SECTION for Indexed Sequential Files

The FILE-CONTROL paragraph statements for the indexed sequential dataset is little bit different from that of a sequential data set.

Format:

FILE-CONTROL.

SI Asia Pacific,, Singapore 99

Page 100: Cobol Notes v01

SELECT <file-name> ASSIGN TO <dd-name>ORGANIZATION IS INDEXEDACCESS MODE IS SEQUENTIAL [RANDOM] [DYNAMIC]RECORD KEY IS <key-field> [ALTERNATE RECORD KEY IS <alternate-key>

[WITH DUPLICATES] ][FILE STATUS IS data-name-1]

The organization of an indexed file (KSDS) must be INDEXED. The access mode can be SEQUENTIAL (default value), RANDOM or DYNAMIC.

The SEQUENTIAL access mode indicates that the records are accessed sequentially. The RANDOM indicates that the records are accessed randomly (by using the key). The DYNAMIC indicates that the records are accessed either sequentially or randomly or even both.

The RECORD KEY clause is used to specify the key field of the dataset. Note that this field must a part of your record description entries.

The ALTERNATE RECORD KEY is an optional statement, which is used to specify that the records are accessed by using alternate key also. The alternate key can be unique or duplicate. If you want to read a KSDS by using its alternate index you must specify the ALTERNATE KEY parameter. The word RECORD is optional.

The FILE STATUS is an optional statement and is similar to sequential dataset. The data-name-1 specified here must be declared in the WORKING-STORAGE section as picture 9(2) or X(2).

Example:

FILE-CONTROL.

SELECT K100 ASSIGN TO K100ORGANIZATION IS INDEXEDACCESS MODE IS RANDOMRECORD KEY IS K100-EMP-NO.

SELECT K200 ASSIGN TO K200ORGANIZATION IS INDEXEDACCESS MODE IS DYNAMICRECORD KEY IS K200-EMP-NOALTERNATE RECORD KEY IS K200-EMP-DEPT.

SI Asia Pacific,, Singapore 100

Page 101: Cobol Notes v01

13.2.2 PROCEDURE DIVISION Statements for Indexed Files

Like sequential datasets, we have the entire file handling statements here also. These statements include OPEN, READ, WRITE, REWRITE and CLOSE. The additional statements that are available here is DELETE and START. The format of OPEN and CLOSE statements are exactly similar to a sequential dataset. SO we are not repeating it again here.

(a) The READ Statement

The format of the READ statement is same as sequential dataset when the access mode is sequential. However, if the access mode is RANDOM or DYNAMIC the format is different.

Format1:

Read statement for SEQUENTIAL access is:

READ file-name [ RECORD ] [INTO identifier ][ AT END imperative-statement ]

Format2:

Read statement for RANDOM access is:

READ file-name [ RECORD ] [INTO identifier ][ KEY IS data-name ][ INVALID KEY imperative-statement ]

The data name in the KEY IS phrase must be either the prime key or the alternate key data item. If the phrase is not specified, the prime key is assumed. Note that the data-name must be defined in the SELECT entry.

Format3:

Read statement for DYNAMIC access is:

READ file-name NEXT [ RECORD ] [INTO identifier ][ AT END imperative-statement ]

Note that in the third format the key word NEXT is must.

Examples:

Suppose you want to access the dataset by using the primary key, say EMP-NO, you will have to write the following statement.

MOVE 10000 TO K100-EMP-NO.READ K100 INVALID KEY MOVE ‘Y’ TO WS-REC-NOT-FOUND.

If you want to access the dataset using the alternate key, say EMP-DEPT, the statement would be:

MOVE ‘HRD’ TO K200-EMP-DEPT.READ K200 KEY IS K200-EMPDEPT

SI Asia Pacific,, Singapore 101

Page 102: Cobol Notes v01

INVALID KEY MOVE ‘Y’ TO WS-REC-NOT-FOUND.

In the second example, the phrase KEY IS is required. This is because we are reading the dataset using the alternate key rather than the primary key. If you omit the KEY IS option COBOL will assume the primary key.

(b) The WRITE Statement

The WRITE statement is used to add a new record to the dataset.

Format:

WRITE record-name [ FROM identifier ]

[ INVALID KEY imperative-statement ]

At the time of execution of the WRITE statement, the file must be open either in the OUTPUT or I-O mode. Upon successful execution of the WRITE statement, a record is released to the file and the record area associated with the record name no longer contains the record. Note that the record will be stored in the dataset based on the key value specified in the record. The FROM phrase has the same meaning as in the case of a sequential file.

The imperative statement of the INVALID KEY phrase is executed when an attempt is made to write a record with an existing key value.

(c) The REWRITE Statement

The REWRITE statement is used to update an existing record in the dataset.

Format:

REWRITE record-name [ FROM identifier ]

[ INVALID KEY imperative-statement ]

The REWRITE statement is used to replace an existing record by the contents of the record specified in the record name. The file must be opened in the I-O mode. The FROM phrase has the same meaning as in the case of the WRITE statement. When the access mode is RANDOM OR DYNAMIC, the record to be replaced is identified by the contents of the key value. When the access mode is SEQUENTIAL, prior to the execution f the REWRITE statement, a READ statement on the file must be successfully executed, and there should not be any other input-output statement on the file in between the READ and REWRITE statements. In this case, the record read by this READ statement serves the purpose. The imperative statement after the INVALID KEY is executed when an attempt is made to replace a record position, which is empty. An empty record position is that position where no record has been a DELETE statement. Upon successful execution of the REWRITE statement, the record area does not contain the released data.

(d) The DELETE Statement

Format:

SI Asia Pacific,, Singapore 102

Page 103: Cobol Notes v01

DELETE file-name [ RECORD ] [ INVALID KEY Imperative-statement ]

The DELETE statement deletes a record determined by the value of the record key in RANDOM or DYNAMIC access modes. File should be opened in I-O mode. In both the access modes, INVALID KEY phrase has to be used. Whereas, in the SEQUENTIAL access mode, INVALID KEY phrase should not be used, rather, the record, which has to be deleted, should be successfully read first.

Example:

Suppose you want to delete a record from employee KSDS with the primary key ‘E009’, you can write the following statement.

MOVE ‘E009’ TO K100-EMP-NO. DELETE K100 INVALID KEY DISPLAY ‘RECORD NOT FOUND !’.

(e) The START Statement

The START statement positions to the first record in the file which satisfies the condition specified in the KEY phrase. File has to be opened either in I-O or INPUT mode. The access mode should be SEQUENTIAL or DYNAMIC. Once located a record, subsequent sequential operations on the file can start from this point instead of the beginning. The data name in this phrase must be the record key, alternate key or any alphanumeric data item that is the leftmost field in the record key. If KEY phrase is omitted EQUAL operator is assumed. INAVLID KEY condition arises if no matching record is found.

Format:

START file-name KEY IS [ EQUAL TO] [ = ] [ GREATER THAN ] [ > ] [ NOT LESS THAN ] [ NOT < ] data-name [ INVALID KEY imperative statement ]

Example:

Suppose you want to process all employees under ‘HRD’ department in an employee KSDS, you can write the following statement to locate the first logical record.

MOVE ‘HRD’ TO K100-EMP-DEPT. START K100 INVALID KEY IS EQUAL TO K100-EMP-DEPT

INVALID KEY PERFORM NOT-FOUND-PARA.

Will position the file at the first logical record of ‘HRD”, after which a successive sequential reading will find all ‘HRD’ matching records one after the another.13.3 Handling RELATIVE FILES (RRDS)

In relative files, records are identified by a relative record number (RRN). The relative record number specifies the position of the record from the beginning of the file. Thus the relative record number 1 identifies the first record, the relative record number 2 identifies the second record and so on.

SI Asia Pacific,, Singapore 103

Page 104: Cobol Notes v01

A relative file can be accessed either sequentially or randomly. When the file is accessed sequentially, the records are accessed in the increasing order of their relative record numbers. When a file is accessed randomly, the programmer must specify the relative record number. The record is accessed directly regardless of the previous access of any other record in the file.

It may be noted that in the case of relative organization, the reading as well as the writing can be done randomly. Thus, when a file is written with the records randomly, some of the record positions may remain empty. While these positions can be filled in subsequently, the programmer should avoid specifying these empty positions while reading such a relative file randomly. If a relative file is read in a sequential manner, such empty positions within it, if any, are ignored.

The handling of relative files requires some special codes in the FILE-CONTROL paragraph as well as in the PROCEDURE DIVISION. These are discussed below.

FILE-CONTROL Paragraph for Relative Files:

Format:

FILE-CONTROL.

SELECT <file-name> ASSIGN TO <dd-name>ORGANIZATION IS REALTIVE[ ACCESS MODE IS SEQUENTIAL [RANDOM] [DYNAMIC]]

[ RELATIVE KEY IS <data-name> ][FILE STATUS IS data-name-1]

Example:

SELECT R100 ASSIGN R100 ORGANIZATION IS RELATIVE ACCESS MODE IS DYNAMIC RELATIVE KEY IS REL-KEY.

Except for the ORGANIZATION and ACCESS MODE clauses, all other clauses have the same meaning as in the case of sequential files. The ORGANIZATION clause specifies that the said file is a relative file. Whether the file should be used sequentially or randomly, should be specified through the word SEQUENTIAL or RANDOM in the ACCESS MODE clause. The clause ACCESS MODE IS DYNAMIC indicates that the file is accessed sequentially and/or randomly in the procedure division. The phrase RELATIVE KEY must be specified when the access mode is RANDOM or DYNAMIC. The data-name-1 is called the relative key data item and it indicates the field that contains the relative record number. The programmer must place an appropriate value in the relative key data item while using a record randomly. Data-name-1 must not be part of the record description for the said relative file. If the ACCESS MODE clause is not specified, SEQUENTIAL is assumed.

13.3.1 PROCEDURE DIVISION Statements for Relative Files

SI Asia Pacific,, Singapore 104

Page 105: Cobol Notes v01

The statements OPEN, CLOSE, READ, WRITE and REWRITE which are available for sequential files are all available for the relative files. In addition, two other verbs, namely, DELETE and START are also available. As regards the OPEN and CLOSE statements, there is no difference between a relative file and sequential disk file.

(a) The READ Statement

Like index sequential datasets, you can read relative dataset in various ways.

Format1:

Read statement for SEQUENTIAL access is:

READ <file-name> RECORD [ INTO identifier ][ AT END imperative-statement ]

Format2:

Read statement for RANDOM or DYNAMIC access is:

READ <file-name> RECORD [ INTO identifier ] [ INVALID KEY imperative-statement ]

Format3:

Read statement for DYNAMIC access is:

READ <file-name> [ NEXT ] RECORD [ INTO identifier ][ AT END imperative-statement ]

As usual, a READ statement reads a record of the file. The file must be open in either the INPUT or I-O mode.

Format1 is the normal form of the READ statement and this is the only form that is applicable to sequential files. In the case of relative files, this format is used when the access mode is sequential. If the RELATIVE KEY phrase is also specified with the ACCESS MODE SEQUENTIAL clause, then upon the successful completion of the READ statement, the relative record number of the accessed record is placed in the relative key data item.

Format2 is used when the access mode is either random or dynamic. The record to be read is identified from the contents of the relative key data item. For example, suppose R100 and WS-KEY are the names for the relative file and relative key data item respectively. The following statements will read the fiftieth record from this file.

MOVE 50 TO WS-KEY.READ R100 RECORD INVALID KEY PERFORM 9000-ERROR.

The imperative statement of the INVALID KEY phrase is executed when the read is unsuccessful. Reading is considered unsuccessful if attempt is made to read a

SI Asia Pacific,, Singapore 105

Page 106: Cobol Notes v01

record (a) form an empty record position of the relative file or (b) from outside the externally defined boundaries of the file.

Format3 of the READ statement can be used when the access mode is dynamic and the records are to be read sequentially. As a result of the execution of this statement, the next record from the file is read. The next record is identified according to the following rules:

a) When the READ NEXT statement is the first statement to be executed after the OPEN statement on the file, the next record is the first record of the file.

b) When the execution of the READ NEXT statement follows the execution of another READ statement on the same file (Format2 or Format3 above).

c) When the execution of the READ NEXT statement follows the execution of the START statement, the next record is the record to which the file is logically positioned by the START statement.

Note that the above rules permit the switch from random to sequential reading in the case of relative files with the dynamic access mode.

When format1 or format3 is used, empty record positions within the relative file are ignored.

(a) The WRITE Statement

At the time of execution of the WRITE statement, the file must be opened either in the OUTPUT or I-O mode. Upon successful execution of the WRITE statement, a record is released to the file and the record area associated with the record name no longer contains the record. The FORM phrase has the same meaning as in the case of a sequential file.

Format:

WRITE record-name [ FROM identifier ][ INVALID KEY imperative-statement ]

When the file is accessed randomly, the statement releases the record to that relative record position on the file which is indicated by the record number in the relative key data item. For example, suppose R200-REC and WS-KEY are the record name and relative key data item name for a relative file opened in the I-O mode. Then, upon execution of the following statements

MOVE 50 TO WS-KEY.WRITE R200-REC INVALID KEY PERFORM 9000-ERROR.

The record is written at the fiftieth record position on the file.

When the file is accessed sequentially, records are released to the file in the sequential record positions. If the relative key data name is specified with the ACCESS MODE IS SEQUENTIAL clause, the record number of the record just released is written in the said data name.

The imperative statement of the INVALID KEY phrase is executed in the following cases:

SI Asia Pacific,, Singapore 106

Page 107: Cobol Notes v01

a) When an attempt is made to write beyond the externally defined boundaries of the file.

b) When an attempt is made to write in the record position, which already contains a valid record.

(b) The REWRITE Statement

The REWRITE statement is used to update an existing record. The file must be opened in the I-O mode. The FROM phrase has the same meaning as in the case of the WRITE statement. When the access mode is RANDOM OR DYNAMIC, the record to be replaced is identified by the contents of the relative key data item. When the access mode is SEQUENTIAL, prior to the execution of the REWRITE statement, a READ statement on the file must be successfully executed, and there should not be any other input-output statement on the file in between the READ and REWRITE statements. In this case, the record read by this READ statement serves the purpose. The imperative statement after the INVALID KEY is executed when an attempt is made to replace a record position which is empty. An empty record position is that position where no record has been a DELETE statement. Upon successful execution of the REWRITE statement, the record area does not contain the released data.

Format:

REWRITE record-name [ FROM identifier ][ INVALID KEY imperative-statement ]

(c) The DELETE Statement

The DELETE statement deletes the record from a relative dataset. The deleted record is no longer available. The record position whose content is to be deleted is identified in the same manner as in the case of the REWRITE statement. Thus, when the ACCESS MODE IS SEQUENTIAL the execution of the DELETE statement must be preceded by the execution of a READ statement on the file and the INVALID KEY phrase should not be specified. The INVALID KEY condition arises when an attempt is made to delete the record of an empty record position. In this case the statement after the INVALID KEY is executed. The file must be opened in the I-O mode. The execution of a delete statement does not affect the contents of the record area.

Format:

DELETE file-name RECORD[ INVALID KEY imperative-statement ]

(d) The START Statement

The START statement is used to position the relative file at some specified point so that subsequent sequential operations on the file can start from this point instead of the beginning of the file. The KEY IS phrase indicates how the file is to be positioned. The data name in this phrase must be the data name in the RELATIVE KEY phrase of the SELECT clause.

SI Asia Pacific,, Singapore 107

Page 108: Cobol Notes v01

Format:

START file-name KEY IS [ EQUAL TO] [ = ] [ GREATER THAN ] [ > ] [ NOT LESS THAN ] [ NOT < ] data-name

[ INVALID KEY imperative statement ]Example:

MOVE 50 TO WS-KEY. START R100 KEY IS GREATER THAN WS-KEY INVALID KEY PERFORM 9000-ERROR.

Will position the file at the fifty-first record position if the relative key data item WS-KEY contains 50.

The INVALID KEY condition arises if the specified record position is empty. In that case the imperative statement after the INVALID KEY phrase is executed.

The START statement requires that the file must be opened in the INPUT or I-O mode. The access mode can only be SQUENTIAL or DYNAMIC.

SI Asia Pacific,, Singapore 108

Page 109: Cobol Notes v01

Appendix A: Examples

(a) The following program is used to accept an operational code and the details of an employee from SYSIN and process accordingly.

000001 IDENTIFICATION DIVISION. 000002 PROGRAM-ID. LAB27. 000003 ENVIRONMENT DIVISION. 000004 INPUT-OUTPUT SECTION. 000005 FILE-CONTROL. 000006 SELECT K100 ASSIGN TO K100 000007 ORGANIZATION IS INDEXED 000008 ACCESS MODE IS DYNAMIC 000009 RECORD KEY IS K100-EMPNO 000010 FILE STATUS IS WS-K100-STATUS. 000011 DATA DIVISION. 000012 FILE SECTION. 000013 FD K100 000014 RECORD CONTAINS 80 CHARACTERS. 000015 01 K100-REC. 000016 05 K100-EMPNO PIC X(4). 000017 05 K100-NAME PIC X(7). 000018 05 K100-DEPT PIC X(4). 000019 05 K100-SAL PIC 9(4). 000020 05 K100-REST PIC X(61). 000021 000022 WORKING-STORAGE SECTION. 000023 01 WS-K100-STATUS PIC 99. 000024 01 WS-EMPNO PIC X(4). 000025 01 WS-OP-CODE PIC 9. 000026 01 WS-HEAD-REC. 000027 05 FILLER PIC X(32) VALUE ALL '='. 000028 05 FILLER PIC X(16) VALUE ' PROGRAM-OUTPUT '. 000029 05 FILLER PIC X(32) VALUE ALL '='. 000030 01 WS-IN-REC. 000031 05 K100-NAME PIC X(7). 000032 05 K100-SEP1 PIC X. 000033 05 K100-DEPT PIC X(4). 000034 05 K100-SEP1 PIC X. 000035 05 K100-SAL PIC 9(4). 000036 05 K100-REST PIC X(61). 000037 PROCEDURE DIVISION. 000038 0000-MAIN. 000039 PERFORM 1000-OPEN THRU 1000-EXIT. 000040 PERFORM 2000-READ THRU 2000-EXIT. 000041 PERFORM 9000-CLOSE THRU 9000-EXIT. 000042 STOP RUN. 000043 0000-EXIT. 000044 EXIT. 000045 1000-OPEN. 000046 DISPLAY WS-HEAD-REC. 000047 OPEN I-O K100. 000048 EVALUATE WS-K100-STATUS 000049 WHEN '00' 000050 DISPLAY 'FILE OPENED FINE. ' 000051 CONTINUE

SI Asia Pacific,, Singapore 109

Page 110: Cobol Notes v01

000052 WHEN OTHER 000053 DISPLAY 'ERROR IN OPENING FILE, THE STATUS: ' 000054 - WS-K100-STATUS 000055 PERFORM 9000-CLOSE THRU 9000-EXIT000056 STOP RUN 000057 END-EVALUATE. 000058 1000-EXIT. 000059 EXIT. 000060 2000-READ. 000061 ACCEPT WS-OP-CODE FROM SYSIN. 000062 ACCEPT WS-EMPNO FROM SYSIN. 000063 MOVE WS-EMPNO TO K100-EMPNO. 000064 READ K100. 000065 EVALUATE WS-K100-STATUS 000066 WHEN 00 000067 PERFORM 3000-PROC THRU 3000-EXIT 000068 WHEN 23 000069 PERFORM 4000-PROC THRU 4000-EXIT 000070 WHEN OTHER 000071 DISPLAY 'SEVERE FILE I/O ERROR !' 000072 END-EVALUATE. 000073 2000-EXIT. 000074 EXIT. 000075 3000-PROC. 000076 IF WS-OP-CODE = 1 THEN 000077 DISPLAY 'EMPLOYEE NUMBER : ' K100-EMPNO OF K100-REC 000078 DISPLAY 'EMPLOYEE NAME : ' K100-NAME OF K100-REC 000079 DISPLAY 'EMPLOYEE DEPT. : ' K100-DEPT OF K100-REC 000080 DISPLAY 'EMPLOYEE SALARY : ' K100-SAL OF K100-REC 000081 ELSE 000082 PERFORM 3500-PROC THRU 3500-EXIT. 000083 3000-EXIT. 000084 EXIT. 000085 3500-PROC. 000086 EVALUATE WS-OP-CODE 000087 WHEN 3 000088 ACCEPT WS-IN-REC FROM SYSIN 000089 MOVE CORR WS-IN-REC TO K100-REC 000090 REWRITE K100-REC 000091 DISPLAY K100-EMPNO ' MODIFIED.' 000092 WHEN 4 000093 DELETE K100 000094 DISPLAY K100-EMPNO ' HAS BEEN DELETED.' 000095 WHEN OTHER 000096 DISPLAY K100-EMPNO ' IS DUPLICATING.' 000097 END-EVALUATE. 000098 3500-EXIT. 000099 EXIT. 000100 4000-PROC. 000101 IF WS-OP-CODE = 2 THEN 000102 ACCEPT WS-IN-REC FROM SYSIN 000103 MOVE CORR WS-IN-REC TO K100-REC 000104 WRITE K100-REC

SI Asia Pacific,, Singapore 110

Page 111: Cobol Notes v01

000105 DISPLAY K100-EMPNO ' RECORD HAS BEEN INSERTED.' 000106 ELSE 000107 DISPLAY K100-EMPNO ' RECORD NOT FOUND !!'. 000108 4000-EXIT. 000109 EXIT. 000110 9000-CLOSE. 000111 CLOSE K100. 000112 9000-EXIT. 000113 EXIT.

SI Asia Pacific,, Singapore 111

Page 112: Cobol Notes v01

(b) The following program is used to sort an input file to another file. Sorting will be taken place based on the employ number.

000001 IDENTIFICATION DIVISION. 000002 PROGRAM-ID. LAB28. 000003 ENVIRONMENT DIVISION. 000004 INPUT-OUTPUT SECTION. 000005 FILE-CONTROL. 000006 SELECT F100 ASSIGN TO F100. 000007 SELECT F200 ASSIGN TO F200. 000008 SELECT F300 ASSIGN TO F300. 000009 DATA DIVISION. 000010 FILE SECTION. 000011 FD F100 000012 LABEL RECORDS ARE STANDARD 000013 RECORDING MODE IS F. 000014 01 F100-REC PIC X(50). 000015 FD F200 000016 LABEL RECORDS ARE STANDARD 000017 RECORDING MODE IS F.

000018 01 F200-REC PIC X(50). 000019 SD F300. 000020 01 F300-REC. 000021 03 F300-EMP-NO PIC X(5). 000022 03 FILLER PIC X(45). 000023 PROCEDURE DIVISION. 000024 0000-MAIN. 000025 SORT F300 ON ASCENDING KEY F300-EMP-NO 000026 USING F100 000027 GIVING F200. 000028 STOP RUN. 000029 0000-EXIT.

000030 EXIT.

SI Asia Pacific,, Singapore 112

Page 113: Cobol Notes v01

Appendix B: VSAM File Status Codes

00 SUCCESSFUL COMPLETION 02 DUPLICATE KEY, NON UNIQ. ALT INDX 04 READ, WRONG LENGTH RECORD 05 OPEN, FILE NOT PRESENT 07 CLOSE OPTION INCOMPAT FILE DEVICE OPEN IMPLIES TAPE; TAPE NOT USED 10 END OF FILE 14 RRN > RELATIVE KEY DATA 20 INVALID KEY VSAM KSDS OR RRDS 21 SEQUENCE ERROR, ON WRITE OR CHANGING KEY ON REWRITE 22 DUPLICATE KEY 23 RECORD OR FILE NOT FOUND 24 BOUNDARY VIOLATION. WRITE PAST END OF KSDS RECORD. COBOL 370: REL: REC# TOO BIG, OUT OF SPACE ON KSDS/RRDS FILE 30 PERMANENT DATA ERROR, DATA CHECK, PARITY CHK, HARDW 34 BOUNDARY VIOLATION, WRITE PAST END OF ESDS RECORD, OR NO SPACE TO ADD KSDS/RRDS RECORD, OUT OF SPACE ON SEQUENTIAL FILE 35 OPEN, FILE NOT PRESENT 37 OPEN MODE INCOMPAT WITH DEVICE 38 OPENING FILE CLOSED WITH LOCK 39 OPEN, FILE ATTRIB CONFLICTING 41 OPEN, FILE IS OPEN 42 CLOSE, FILE IS CLOSED 43 DELETE OR REWRITE & NO GOOD READ FIRST 44 BOUNDARY VIOLATION/REWRITE REC TOO BIG 46 SEQUENTIAL READ WITHOUT POSITIONING 47 READING FILE NOT OPEN AS INPUT/IO/EXTEND 48 WRITE WITHOUT OPEN IO 49 DELETE OR REWRITE WITHOUT OPEN IO 90 UNKNOWN 91 VSAM - PASSWORD FAILURE 92 LOGIC ERROR/OPENING AN OPEN FILE OR READING OUTPUT FILE OR WRITE INPUT FILE OR DEL/REW BUT NO PRIOR READ 93 VSAM - VIRTSTOR. RESOURCE NOT AVAILABLE 94 VSAM - SEQUENTIAL READ AFTER END OF FILE OR NO CURRENT REC POINTER FOR SEQ 95 VSAM - INVALID FILE INFORMATION OR OPEN OUTPUT (LOAD) WITH FILE THAT NEVER CONTNED DATA 96 VSAM - MISSING DD STATEMENT IN JCL 97 VSAM - OPEN OK, FILE INTEGRITY VERIFIED

SI Asia Pacific,, Singapore 113

Page 114: Cobol Notes v01

(c) The following program is used to merge two files and create an output file.

000001 IDENTIFICATION DIVISION. 000002 PROGRAM-ID. LAB29. 000003 ENVIRONMENT DIVISION. 000004 INPUT-OUTPUT SECTION. 000005 FILE-CONTROL. 000006 SELECT F100 ASSIGN TO F100. 000007 SELECT F200 ASSIGN TO F200. 000008 SELECT F300 ASSIGN TO F300. 000009 SELECT F400 ASSIGN TO F400. 000010 DATA DIVISION. 000011 FILE SECTION. 000012 FD F100 000013 LABEL RECORDS ARE STANDARD 000014 RECORDING MODE IS F. 000015 01 F100-REC PIC X(50). 000016 FD F200 000017 LABEL RECORDS ARE STANDARD 000018 RECORDING MODE IS F. 000019 01 F200-REC PIC X(50). 000020 FD F300 000021 LABEL RECORDS ARE STANDARD 000022 RECORDING MODE IS F. 000023 01 F300-REC PIC X(50). 000024 SD F400. 000025 01 F400-REC. 000026 03 F400-EMP-NO PIC X(5). 000027 03 FILLER PIC X(45). 000028 PROCEDURE DIVISION. 000029 0000-MAIN. 000030 MERGE F400 ON ASCENDING KEY F400-EMP-NO000031 USING F100, F200 000032 GIVING F300. 000033 STOP RUN. 000034 0000-EXIT. 000035 EXIT.

SI Asia Pacific,, Singapore 114

Page 115: Cobol Notes v01

Appendix C: Lab Exercises

Lab Exercises (COBOL I)

1. Pass five numeric values from SYSIN and find the highest and lowest value among them.

2. Pass a numeric code between 1 and 4 followed with two numeric values in successive two lines from the SYSIN, based on the code (1 – ADD, 2 – SUBTRACT, 3 – DIVIDE, 4 – MULTIPLY) perform the operation on two values and display the result. Display proper error message if the code is less than 0 or greater than 4.

3. Display whether a numeric passed from SYSIN is an even or an odd number.4. Enter a string from SYSIN and display the first 3 characters.5. Enter a date in the format DDMMYYYY and display the date in the format DD-

Month-YYYY, where Month is January, February, etc depends on the input month. Display an error message if the month code is wrong. (Use IF and GO TO statements)

6. Rewrite the above program using IF and GO TO DEPENDING ON statements. 7. Generate the series 1 4 9 16 25 36 .. 100.

Lab Exercises (COBOL II)

1. Lab test on Class 1 and Class 2 topics – 1 hour duration

2. Pass ten numeric values from SYSIN and find the highest and lowest value among them (accept and process using loop).

3. Pass a number and print a multiplication table in the format n x 1 = n, etc. (Use PERFORM with TIMES option.)

4. Rewrite the above program using PERFORM with UNTIL option.5. Generate the series 1 1 2 3 5 8 …. N, where N is a number supplied through

SYSIN.6. Accept a name from SYSIN and print as follows. (Eg. Name is MOUSE)

1MOUSE2MOUSEMOUSE3MOUSEMOUSEMOUSE…..…..10…..

7. Rewrite the above programs (2.2 through 2.5) using inline perform statement.

Lab Exercises (COBOL III)

1. Accept a string of length 10 and count the number of vowels in it.

SI Asia Pacific,, Singapore 115

Page 116: Cobol Notes v01

2. Accept a string of length 10 and print it in reverse.3. Accept a date in the format YYYYMMDD and print it in the format DD-

monthname-YYYY (eg. 20030105, would be printed as 05-January-2003)4. Accept an employee record in the given format and compute the bonus based

on the given condition.1 – 5 Employee number6 – 15 Employee name16 – 16 Employee sex17 – 19 Hours worked20 – 24 Basic pay

The bonus will be calculated based on the number of hours worked and basic pay.

Bonus = 50% of basic pay, if hours worked > 48 and Basic pay <= 5000Bonus = 35% of basic pay, if hours worked > 48 and Basic pay > 5000 & <= 9000 Bonus = 25% of basic pay, if hours worked > 35 & < =48 and Basic pay <= 5000Bonus = 15% of basic pay, if hours worked > 35 & <= 48 and Basic pay > 5000& <= 9000

Lab Exercises (COBOL IV)

1. Pass a Student record with Student number and six unit test marks from SYSIN. Find the average of each student.

2. Pass an Item record with three corresponding sales bills (bill number, quantity sold) and unit price as the last field. Calculate each Item’s sales.

3. Pass a Student record with Student number and six unit test marks from SYSIN. Find the average of each student.

4. Hard code five countries with their respective capitals. Pass a country name from SYSIN while running and display the respective capital.

5. Accept a date in the format YYYYMMDD and print it in the format DD-monthname-YYYY (eg. 20030105, would be printed as 05-January-2003). Use OCCURS and REDEFINES clause.

Lab Exercises (COBOL V)

1. Pass a student’s marks record of four subjects and the master record as shown and display the output record as mentioned using the necessary character manipulation related verbs:

Input records: S001/45668782 AJAY KUMAR/X/BANGALORE/

Output: S001AJAY KUMARBANGALOREX ENGLISH: 45 MATHS: 66 PHYSICS: 87 CHEMISTRY: 82Lab Exercises (COBOL VI)

1. Write a program to count the number of records in a file.2. Write a program to count the number of characters in a flat file.3. Write a program to count the number of duplicate records in a file.

SI Asia Pacific,, Singapore 116

Page 117: Cobol Notes v01

4. Write a program to accept an Employee Number from the SYSIN and display his details.

5. Write a program to find and display matching records in two input files.

Lab Exercises (COBOL VII)

1. Write a program to concatenate two input files into another file.2. Write a program to read an employee flat file and write only those employee

records into another file whose department is HRD and Salary > 3000.3. Write a program to accept operational code and data to perform the following

operations on an Employee Flat file: Operational Code: 1-for Adding new records and supply a record along

in the second line of SYSIN Operational Code: 2-for Modifying a record, supply the record to be

modified (use Employee number to locate a record) in the second line Operational Code: 3-for Info of an Employee, pass Employee number in

the second line Operational Code: 4-for Deletion of record, pass employee number to

delete in the second line

e.g.; to add a new record//SYSIN DD *1E009ALOK MKTG2500/*

Lab Exercises (COBOL VIII)

1. Write a subroutine to find the length of a string value.2. Write a subroutine to validate a date string.3. Write a subroutine to sort an array and put into another array.

Lab Exercises (COBOL IX)

Write a program to produce a summary report of Employees who has taken advance salaries with following information: Empno, Name, Department, Salary, Total Salary taken, Net-to-pay and Last date of advance taken. The following are the files to be taken for processing with corresponding fields:

Employee Master (KSDS): Empno, Name, Department, SalaryAdvance (PS): Empno, Advance Amount, date of advance taken

Consideration: An employee may take advance salary more than once, there can invalid entries of employee number in Advance file.NB: Processing should done while reading Advance file until the end of the records in the file.

Lab Exercises (COBOL X)

1. Write a program to accept operational code and data to perform the following operations on an Employee VSAM KSDS file:

SI Asia Pacific,, Singapore 117

Page 118: Cobol Notes v01

Operational Code: 1-for Adding new records and supply a record along in the second line of SYSIN, duplicates should be discarded

Operational Code: 2-for modifying a record, pass an employee code and supply the record to be modified in the second line

Operational Code: 3-for Viewing info of an Employee, pass Employee number in the second line

Operational Code: 4-for Deletion of record, pass employee number to delete in the second line

SI Asia Pacific,, Singapore 118

Page 119: Cobol Notes v01

Appendix D: References

a) COBOL Programming by M K Roy and D Ghosh Dastidarb) COBOL Programming by Stern and Sternc) Advanced COBOL by Gary DeWard Brownd) Structured COBOL by Mike Murach

SI Asia Pacific,, Singapore 119