Sie sind auf Seite 1von 172

Student Notebook

Table of Contents
UNIT 1. Introduction to Language Features COMMON BUSINESS ORIENTED LANGUAGE COBOL PROGRAM ORGANIZATION COBOL LANGUAGE STRUCTURE STRUCTURE OF COBOL PROGRAM CHARACTER SET OF COBOL SAMPLE COBOL PROGRAM CODING FORMAT USER-DEFINED WORDS UNIT 2. The Organization of a COBOL Program IDENTIFICATION DIVISION ENVIRONMENT DIVISION DATA DIVISION DATA-ITEMS LEVEL NUMBERS SPECIAL LEVEL NUMBERS W-S DECLARATIONS FILLER PICTURE CLAUSE USAGE CLAUSE VALUE CLAUSE REDEFINES CLAUSE DUPLICATE DATA NAMES RENAMES CLAUSE FIGURATIVE CONSTANTS EDITED FIELDS MORE EDITING CHARACTER EXAMPLES UNIT 3. PROCEDURE DIVISION PROCEDURE DIVISION COBOL VERBS PARAGRAPHS TERMINATOR STATEMENTS SCOPE TERMINATORS DISPLAY VERB ACCEPT VERB MOVE VERB ELEMENTARY & GROUP MOVES CORRESPONDING PHASE REFERENCE MODIFICATION
Copyright Course materials may not be produced in whole or in part without the prior written permission.

Student Notebook

ADD VERB ADD CORRESPONDING STATEMENT ON SIZE ERROR PHRASE NUMERIC DATA SUBTRACT VERB SUBTRACT CORRESPONDING STATEMENT MULTIPLY VERB DIVIDE VERB COMPUTE STATEMENT PERFORM STATEMENT PERFORM THROUGH PERFORMN TIMES PERFORMVARYING IN-LINE PERFORM RELATIONAL EXPRESSIONS IF STATEMENT COMPOUND CONDITIONALS CLASS CONDITION CONTINUE & NEXT SENTENCE STATEMENT EVALUATE STATEMENT SET TO TRUE INITIALIZE UNIT 4. FILE HANDLING IN COBOL FILES FIXED VS VARIABLE LENGTH RECORDS FILE-CONTROL PARAGRAPH ACCESS MODE FILE STATUS CLAUSE I-O CONTROL PARAGRAPH FILE SECTION FILE OPERATIONS OPEN MODES READ-SEQUENTIAL ACCESS END OF FILE PROCESSING READ RANDOM ACCESS READ DYNAMIC ACCESS START STATEMENT WRITE STATEMENT WRITEFROM READINTO REWRITE & DELETE APPENDING TO SEQUENTIAL FILES FILE COMPARISON CLOSE STATEMENT
Copyright Course materials may not be produced in whole or in part without the prior written permission.

Student Notebook

SEQUENTIAL FILES INDEXED FILES INVALID KEY ACCESS MODE: SEQUENTIAL & RANDOM ACCESS MODE: DYNAMIC RELATIVE FILES UNIT 5. TABLE HANDLING INTRODUCTION: TABLE HANDLING OCCURS CLAUSE SUBSCRIPT INDEXING ONE DIMENSIONAL TABLE TWO DIMENSIONAL TABLE MULTIDIMENTIONAL TABLE TABLE-SORTING SET SEARCH BINARY SEARCH UNIT 6. Library Services COPY STATEMENT NESTED COPY COPY REPLACING COPY PSEUDO-TEST REPLACE PSEUDO-TEST UNIT 7. CHARACTER HANDLING STRING UNSTRING STATEMENT EXAMINE STATEMENT INSPECT TALLYING STATEMENT INSPECT REPLACING STATEMENT UNIT 8. SORT / MERGE SORT/MERGE SORT STATEMENT MERGE STATEMENT SORT PROCEDURES RELEASE STATEMENT RETURN STATEMENT Cobol Lab

Copyright Course materials may not be produced in whole or in part without the prior written permission.

Student Notebook

UNIT 1

Introduction To Language Features

Copyright Course materials may not be produced in whole or in part without the prior written permission.

Student Notebook

Common Business Oriented Language


1959 New Language is named COBOL 1960 Codasyl established COBOL maintenance committee

(Conference on data system language). 1961 1st version of complier made available. Users started writing programs (1962). 1968 2nd version of cobol was approved and standardized by ANSI 1974 Revised and released as COBOL-74 1985- Revised and released as COBOL-85

Notes: To meet the increasing demands for a high level language suitable for business data processing, the United States Department of Defense Convened a Conference on 28th and 29th of May 1958. Three committee were formed for the actual design of the language. In September 1959 the short term committee submitted a report to the Defense Directorate thus COBOL came into existence. COBOL is known as a structured programming language because it allows programmers to segregate the modules and put them into different paragraphs in a more efficient way. Some of the features of COBOL are It is English-like and more easily readable Efficient file handling capabilities. More than 70% of business applications are running on COBOL Reduces the efforts required for documentation of the program. The following features are available with VS COBOL II:
Copyright Course materials may not be produced in whole or in part without the prior written permission. 2

Student Notebook

MVS/XA and MVS/ESA support The compiler and the object programs it produces can be run in either 24- or 31-bit addressing mode

Copyright Course materials may not be produced in whole or in part without the prior written permission.

Student Notebook

COBOL Program Organization


The basic structure of any cobol program contains four divisions namely:

IDENTIFICATION DIVISION ENVIRONMENT DIVISION DATA DIVISION PROCEDURE DIVISION


Every cobol program must have these divisions.

Notes: The four divisions of a COBOL source program are : IDENTIFICATION DIVISION The primary purpose of these program is to name the program. ENVIRONMENT DIVISION This division is primarily used to tell the computer about the input and output devices such as files or printers.

DATA DIVISION
Copyright Course materials may not be produced in whole or in part without the prior written permission. 4

Student Notebook

The division is used to define and describe the data items and being used in the program. Data items and data names refer to some storage space in memory to store data. Here you would distinguish between data, which will be used for a scratch pad area called WORKING-STORAGE and the holding area for data that will be used by the files. PROCEDURE DIVISION The PROCEDURE DIVISION is the section of our program where the logic or commands reside. This is also the place logic or rules we will use to manipulate the data defined in the DATA DIVISION to solve a business problem.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

Student Notebook

Cobol Language Structure


Characters Character String COBOL Words User-Defined Words Reserved Words Figurative Words Special Registers IBM Extensions Non-numeric and numeric Literals

Notes:

Copyright Course materials may not be produced in whole or in part without the prior written permission.

Student Notebook

Structure of a Cobol Program


Examples Divisions Sections or Paragraphs DATA DIVISION PROGRAM-ID FILE SECTION, 100-PARA MOVE A TO B IF A>B MOVE A TO B ELSE ADD C TO D

Statements Sentences

Notes: All COBOL programs should follow the structure. Rules of coding varies, depending on the compiler versions but the structure remains same. A period (.) is a must at the end of each sentence and indicates the end of the sentence. A typical program could contain divisions, sections or paragraphs within divisions, and statements within sections or paragraphs. There are both system and user defined sections and paragraphs. Eg: PROCEDURE DIVISION. ADD-PARA. ADD A,B GIVING C. SUB-PARA.

Where A,B and C are dada items defined in the data divisions.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

Student Notebook

Character Set of COBOL


COBOL supports the following characters Numbers Alphabets Spaces or blanks Arithmetic operators Special characters : : : : : 0-9 (10 Numericals) a-z, A-Z (26 English letters) Some times denoted by blanks ex: **, *, +, -, / ex: - \ / , ;

Notes: The character 0-9 are called numeric characters or digits. The characters A-Z are called letters and remaining are called special characters. The COBOL dictionary words used for coding are called COBOL reserved words and they should not be used as user-defined words. Lower case alphabets can be used for coding depending on the compiler version. Comma (,) or space is used as separators for user-defined words.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

Student Notebook

Sample COBOL Program

Columns 1 67 8

11 12

72 73

80

* This is a sample program

IDENTIFICATION DIVISION. PROGRAM-ID. SAMPLE. ENVIRONMENT DIVISION. DATA DIVISION. WORKING-STORAGE SECTION. 01 A PIC 9(2) VALUE 20. 01 B PIC 9(2) VALUE 3O. 01 C PIC 9(3) VALUE ZEROS. PROCEDURE DIVISION. DISPLAY THE SUM IS. ADD A ,B GIVING C. DISPLAY C. STOP RUN.
Notes: 1-6 7 8-11 12-72 73-80 -------------- Sequence numbers -------------- Indicator/Comment/Continuation -------------- Area A -------------- Area B -------------- Descriptor

This foil shows a sample COBOL program to ADD two numbers and DISPLAY the sum. SAMPLE is the program name. SAMPLE, A, B AND C are called user-defined words. A, B,C are called variables or data-items.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

Student Notebook

Coding Format
01 06 Sequence Sequence numbers are generated by cobol compiler for each line To mark an asterisk (*) or a slash (/) for comment line, or a hyphen (-) for continuation of a statement. All division headings, section and paragraph headings and 01 level entries should begin from this area. All Cobol statements and sentences should lie within this area Any thing written in this area is ignored.

07

Indicator

08 11

Area A

12 72

Area B

73 80

Description

Notes: COBOL coding should follow the standard format. The Screen is divided into different areas for the purposes explained above. All statements indicating action are called COBOL verbs and should begin from 12th column or after. -E.g MOVE, ADD, DIVIDE, STOP RUN

Copyright Course materials may not be produced in whole or in part without the prior written permission.

10

Student Notebook

User-defined Words
Valid TOTAL-OF-FIGURES 34B100-PARA1 GROSS-PAY Literals Numeric constants Alphanumeric constants Invalid DATA -48B GROSS PAY Examples 35, -345.67 Leo talstoy ka01-h215 Reason Cobol reserved word Hyphen in beginning space in b/w 2 words

Paragraph names, Identifiers, File names can be defined by users. The terms identifiers, data-names, variables, data-items are often used interchangeably indicates memory.

Notes: All user-defined words should conform to following rules: Length should not exceed 30 characters. At least one character must be an alphabet. Spaces and special characters are not allowed. Word can contain hyphens (-) but not in the beginning or at the end Cannot be a COBOL reserved word.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

11

Student Notebook

UNIT 2
The Organization of a COBOL Program

Copyright Course materials may not be produced in whole or in part without the prior written permission.

12

Student Notebook

IDENTIFICATION DIVISION

IDENTIFICATION DIVISION. PROGRAM-ID. <Pgm-name> AUTHOR. <Pgmr-name> DATE WRITTEN. <Entry> DATE-COMPILED. <Entry> SECURITY. <Entry>

Required Required Optional Optional Optional Optional

At least one space required after the period

Notes: The Identification Division must be the first division in every COBOL source program. It must be coded as IDENTIFICATION DIVISION or ID DIVISION followed by a separator period. The Identification Division identifies the source program and the resultant output listing. The user can include the date the program is written and other information as desired under the paragraphs in the general format. This entire division (including the division header) is optional.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

13

Student Notebook

ENVIRONMENT DIVISION
ENVIRONMENT DIVISION. CONFIGURATION SECTION. SOURCE-COMPUTER. <Entry>. OBJECT-COMPUTER. <Entry>. INPUT-OUTPUT SECTION. FILE-CONTROL. ------------------------------------------------------I-O-CONTROL. ---------------------------------------------------------

Notes: The Environment Division is divided into two sections: The CONFIGURATION SECTION The Configuration Section is an optional section for programs which describe the computer environment on which the program is compiled and executed. The Configuration Section can be specified only in the ENVIRONMENT DIVISION of the outermost program of a COBOL source program. The INPUT-OUTPUT SECTION The Input-Output Section of the Environment Division contains two paragraphs: o FILE-CONTROL paragraph o I-O-CONTROL paragraph FILE-CONTROL paragraph The keyword FILE-CONTROL can appear only once, at the beginning of the FILE-CONTROL paragraph. It must begin in Area A, and be followed by a separator period. The FILE-CONTROL paragraph is optional. The FILE-CONTROL paragraph associates each file in the COBOL program with an external data set, and specifies file organization, access mode, and other information.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

14

Student Notebook

There are three formats for the FILE-CONTROL paragraph: QSAM, SAM, and VSAM sequential file entries VSAM indexed file entries VSAM relative file entries. The FILE-CONTROL paragraph begins with the word "FILE-CONTROL", followed by a separator period. It must contain one and only one entry for each file described in an FD or SD entry in the Data Division. Within each entry, the SELECT clause must appear first, followed by the ASSIGN clause. The other clauses can appear in any order. I-O-CONTROL paragraph Specifies information needed for efficient transmission of data between the external data set and the COBOL program. The series of entries must end with a separator period The keyword I-O-CONTROL can appear only once, at the beginning of the paragraph. The word I-O-CONTROL must begin in Area A, and must be followed by a separator period. Each clause within the paragraph can be separated from the next by a separator comma or a separator semicolon. The order in which I-O-CONTROL paragraph clauses are written is not significant

Copyright Course materials may not be produced in whole or in part without the prior written permission.

15

Student Notebook

DATA DIVISION
Data division is the third and most frequently used division in all programs. Every data items or variable required by the program should be declared in appropriate section of the data division, before using in procedure division. The Data Division is divided into three sections:

File Section: Defines the structure of data files (including sort-merge files). If the program is accessing files.

Working-Storage Section: Describes records and subordinate data items that are not part of data files but are required by the program.

Linkage Section: Describes data made available by another program. It usually appears in the called program and describes data items that are referred to by the calling and the called programs.

Each section has a specific logical function within a COBOL source program, and each can be omitted from the source program when that logical function is not needed. If included, the sections must be written in the order shown.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

16

Student Notebook

DATA DIVISION. FILE SECTION. FD . ----------------------------WORKING-STORAGE SECTION. 01 VAR-1 PIC A(5). 01 ID-1 PIC X(10) 01 DATA-NAME PIC 9(5)

DATA TYPES -Alphabetic -Alphanumeric -Numeric

Level number

picture Clause

data type (length)

LINKAGE SECTION. record-description-entry data-item-description-entry

Copyright Course materials may not be produced in whole or in part without the prior written permission.

17

Student Notebook

DATA-ITEMS
Explicitly identifies the data being described

The data-item must be the first word following the level-number.

The data-item values can be changed during program execution.

A data-item

name cannot be the same as a section-name or a

paragraph name

Notes: Data item is a user-defined word which is associated with Level number. COBOL Reserved words should not be Data items. The data division of a COBOL source program describes, in a structured manner, all the data to be processed by the program. This division allocates memory locations for the data items that a program requires. There are several types of storage locations in COBOL: file buffers, misc. scratch data, communication buffers, screen paint data and report format data.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

18

Student Notebook

Level Numbers
Range of level numbers available are 01 to 49 and

66 level specified for RENAMING CLAUSE

77 levels specified exclusively for elementary items

88 levels specified for CONDITION NAMES.

An elementary item can be declared with level numbers 01 and 77

01 and 77 level entries must begin from area A and other level entries can begin from any where in area A or area B
Notes: Level represents the nature of a data item. The level-number specifies the hierarchy of data within a record, and identifies special-purpose data entries. A level-number begins a data description entry, a renamed or redefined item, or a condition-name entry. A level-number has a value taken from the set of integers between 01 and 49, or from one of the special levelnumbers, 66, 77, or 88. Level-number 01 and 77 must begin in Area A and must be followed either by a separator period; or by a space, followed by its associated data-name, FILLER, or appropriate data description clause.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

19

Student Notebook

Level numbers 02 through 49 can begin in Areas A or B and must be followed by a space or a separator period. Level number 66 and 88 can begin in Areas A or B and must be followed by a space. Single-digit level-numbers 1 through 9 can be substituted for level-numbers 01 through 09. Successive data description entries can start in the same column as the first or they can be indented according to the level-number. Indentation does not affect the magnitude of a level-number. When level-numbers are indented, each new level-number can begin any number of spaces to the right of Area A. The extend of indentation to the right is limited only by the width of Area B. Higher numbered level(s) represent subordinate definition(s). Level numbers need not be consecutive (but should be in ascending order)

Copyright Course materials may not be produced in whole or in part without the prior written permission.

20

Student Notebook

Special Level Numbers


LEVEL-66 Identifies items that must contain a RENAMES clause; such items regroup previously defined data items. LEVEL-77 Identifies data item description entries that are independent working-storage, local-storage, or linkage section items; they are not subdivisions of other items and are not subdivided themselves. Level-77 items must begin in Area A. LEVEL-88 identifies any condition-name entry that is associated with a particular value of a conditional variable.
Notes: LEVEL-66 regroups previously defined items. A level-66 entry cannot rename another level-66 entry, nor can it rename a level-01, level-77, or level-88 entry. All level-66 entries associated with one record must immediately follow the last data description entry in that record. LEVEL-77 items are ELEMENATARY items with no subdivision. LEVEL-77 names are unique because they can not be qualified. LEVEL-88 describes condition-names. LEVEL-88 can be used to describe both elementary and group items. Level-77 and level-01 entries in the working-storage, local-storage, and linkage sections that are referenced in a program or method must be given unique datanames because level-77 and level-01 entries cannot be qualified. Subordinate datanames that are referenced in the program or method must be either uniquely defined, or made unique through qualification. Unreferenced data-names need not be uniquely defined.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

21

Student Notebook

Picture Clause
Describes the characteristics of the data CODE A B G or N 9 X P meaning alphabetic or space Blanks or spaces Graphical data Indicates a Numeric Indicates an Alpha Numeric Indicates the position of the assumed decimal point when the point lies outside the data item. Indicates the position of assumed decimal point of numeric field. Indicates whether the data item signed.

V S
Notes:

Picture clause specifies the data type of an identifier. Identifier with PIC clause 9 implies that it is numeric data type, which can take art in arithmetic computations. V and S clauses are allowed with numeric data types only. X clause represents an alphanumeric data type which can hold any character including numbers also. A clause indicates an alphabetic data type. Group items are always considered as alphanumeric only. Therefore GROSS-PAY, DEDUCTIONS can not be used for computations.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

22

Student Notebook

W-S Declarations
WOKING-STORAGE SECTION. 01 PAY. 05 GROSS-PAY. 10 BASIC PIC 9(4)V99. 10 DA PIC 9(4)V99. 10 HRA PIC 9(4)V99 05 DEDUCTIONS. 07 PF-DED 07 IT-DED 05 NET-PAY PIC 05 NAME PIC 05 E-CODE PIC

Alternatively 9(4)V9(2) 9999V99

PIC 9(3)V99. PIC 9(3)V99. 9(4)V99. A(5). X(6).

AAAAA XXXXXX

Notes: Use the WORKING-STORAGE SECTION in the DATA DIVISION of the OBJECT paragraph to describe the instance data that a COBOL class needs, that is, the data to be allocated for each instance of the class. The OBJECT keyword, which you must immediately precede with an IDENTIFICATION DIVISION declaration, indicates the beginning of the definitions of the instance data and instance methods for the class. Pay, gross-pay, deductions are called group items and they dont have PICTURE clause. Other elements with picture clause are called elementary items, which cannot be broken further. Pay is a Group item is divided into Gross-pay, Deductions, net-pay, name, e-code further Gross-pay sub-divided into Basic, DA, HRA and DEDUCTIONS subdivided into PF-DED and IT-DED.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

23

Student Notebook

FILLER
FILLER is a COBOL Reserved Word used to describe data fields that will not be referenced in the PROCEDURE DIVISION.

If the data-name of FILLER clause is omitted, the data item being described is treated as though it was FILLER 01 EMPLOYEE-RECORD. 05 EMPLOYEE-TYPE 05 EMPLOYEE-SERIAL 05 EMPLOYEE-NAME 05 05 EMPLOYEE-ADDRESS FILLER PIC PIC PIC PIC PIC PIC X. X(6). X(30). X(2). X(60). X(34).

Notes: FILLER is a data item that is not explicitly referred to in a program. The key word FILLER is optional. If specified, FILLER must be the first word following the levelnumber. IF data-name or FILLER clause is omitted, the data item being described is treated as though FILLER had been specified. The VALUE clause may be used on FILLER items, e.g. to assure BLANKS in header lines between fields. In a MOVE CORRESPONDING statement, or in an ADD CORRESPONDING or SUBTRACT CORRESPONDING statement, FILLER items are ignored. In an INITIALIZE statement, elementary FILLER items are ignored.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

24

Student Notebook

USAGE Clause
<level number> data-name [PIC X(n)] [USAGE] COMP COMP-1 COMP-2 COMP-3

COMP COMP-1 COMP-2 COMP-3

- Binary Representation - Hexa Decimal Representation - Hexa Decimal Representation

Size: Half/Full/Double word Size: Full word for Float Size: Double word for Float

- Packed Decimal Representation Size: round(n/2)+1 Where n is number of digits.

Notes: The usage description must match the data-field type described in the FD descriptor of the COBOL program. If the COBOL program does not include a usage clause, select the Chars (character) option for the usage. The USAGE clause can be specified for a data description entry with a level-number other than 66 or 88. However, if it is specified at the group level, it applies to each Elementary item in the group. The usage of an elementary item must not contradict the usage of a group to which the elementary item belongs. The USAGE clause specifies the format in which data is represented in storage. The format can be restricted if certain Procedure Division statements are used. When the USAGE clause is not specified at either the group or elementary level, it assumed that the usage is DISPLAY.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

25

Student Notebook

Computational (COMP) Usage


When usage is specified as COMP, the numeric data item is represented in pure binary. The item must be an integer (no assumed decimal point is allowed). Such that data items are often used as subscripts. The PICTURE of a COMP item should not contain any character other than 9, S. This is the equivalent of BINARY. The COMPUTATIONAL phrase is synonymous with BINARY.

COMPUTATIONAL-1 (COMP-1) Usage


If the usage of a numeric data item is specified as COMP-1, it will be represented in one word in the floating point form. The number is actually represented in Hexa decimal (base 16). Such representation is suitable for arithmetic operations. The PICTURE clause cannot be specified for COMP-1 items. Specified for internal floating-point items (single precision). COMP-1 items are 4 bytes long.

COMPUTATIONAL-2(COMP-2) Usage
This usage is same as COMP-1, except that the data is represented internally in two words. The advantage is that this increases the precision of the data which means that more significant digits can be available for the item. The PICTURE clause cannot be specified for COMP-2 items. Specified for internal floating-point items (double precision). COMP-2 items are 8 bytes long.

COMPUTATIONAL-3(COMP-3) Usage
In this form of internal representation the numeric data is the decimal form, but one digit takes half-a-byte. The sign is stored separately as the right most half a-byte regardless of whether S is specified in the PICTURE or not. The hexa decimal number C or F denotes a positive sign and the Hexa decimal number D denotes a negative sign. Inorder that data fields can start and end on byte boundaries, numbers with an even number of digits are stored with an extra half-byte of zeroes on the left hand side. Thus an item with

PICTURE

S9(5)V9(3)

USAGE IS COMP-3

will require 5 bytes to be stored internally. Only the characters 9, S, V and P can be used in the PICTURE of a COMP-3 item. This is the equivalent of PACKED-DECIMAL.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

26

Student Notebook

Value Clause
Value Clause defines the initial value of a data item must not be used for items declared in FILE SECTION. Can also specify FIGURATIVE CONSTANTS. If defined at the group level can be used for array declaration also EXAMPLES 01 NUM-1 01 E-CODE

PIC 9(3) PIC X(6)

VALUE 245. VALUE E10K3. contents VALUE IS ER34155 PIC X(2). ER PIC XXX 341 PIC X(3) 55

At group level 01 GROUP-ITEM 05 E-ITEM-1 05 E-ITEM-2 05 E-ITEM-3

Group item is considered as alphanumeric.


Notes: Assigning values to identifiers is called initialization. If variables are not initialized, then they may contain any value, which was stored at the time of last execution of program. It is advised to always initialize working-storage variables. The VALUE clause specifies the initial contents of a data item or the values associated with a condition-name. The use of the VALUE clause differs depending on the data division section in which it is specified. A VALUE clause that is used in the file section or the linkage section in an entry other than a condition-name entry is syntax checked, but has no effect on the execution of the program. In the working-storage section and the local-storage section, the VALUE clause can be used in condition-name entries or in specifying the initial value of any data item. The data item assumes the specified value at the beginning of program execution. If the initial value is not explicitly specified, the value is unpredictable.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

27

Student Notebook

REDEFINES Clause
Two or more data items can share the same working storage area by REDEFINING a storage area.

Level number data name-1 REDEFINES data-name-2

Level numbers of data-name-1 and data-name-2 must be identical

The redefines clause must immediately follow data-name-I

Must not be used for level number 66 or 88 items.

Data-name-1 should not contain VALUE clause

Multiple redefinition is allowed

Notes: Two or more storage areas defined in the data sometimes may not be used simultaneously, in such cases; only one storage area can serve the purpose of two or more areas if the area is defined. The REDEFINES clause used allows the said area to be referred to by more than one data name with different sizes and pictures.

ILLUSTRATES REDEFINES CLAUSE


Copyright Course materials may not be produced in whole or in part without the prior written permission. 28

Student Notebook

DATA DIVISION. WORKING-STORAGE SECTION. 01 X1 02 02 X3 02 02 02 X4 02 02 X5 02

Y Y1

PIC 99. REDEFINES

PIC XX.

01

01

01

Z PIC X VALUE M. ZZ PIC X (25) VALUE ALL *. ZZZ PIC X (45) VALUE ALL - . REDEFINES X3. FILL1 PIC X. FILL2 PIC X (70). REDEFINES X4. BUFFER PIC X (71).

PROCEDURE DIVISION PARA 1. MOVE 20 TO Y. DISPLAY X1. MOVE A1 TO Y1. DISPLAY X1 DISPLAY X3. DISPLAY X4. DISPLAY X5. STOP RUN.

Duplicate Data Names


Copyright Course materials may not be produced in whole or in part without the prior written permission. 29

Student Notebook

Are allowed, provided they belong to a group item 01 Pay-Rec. 02 Id-numbers 02 Name 02 Dept 01 Print-Rec. 02 Filler 02 Id-numbers 02 Filler 02 Name 02 Dept

PIC 9(5). PIC X (25). PIC X (20). PIC PIC PIC PIC PIC X X X X X (5). (5) (5). (25). (920).

MOVE Id-Numbers (OF | IN) Pay-Rec TO Id-Numbers (OF | IN)PrintRec. * OF and IN are called Qualifiers. To move the data stored in the four fields of Pay-Rec. the four MOVE statements serve the purpose. Using the MOVE CORRESPONDING statement the same can be accomplished.

RENAMES Clause
Syntax:
Copyright Course materials may not be produced in whole or in part without the prior written permission. 30

Student Notebook

66 data-name-1 RENAMES data-name-2 THRU data-name-3 E.g. : 01 PAY REC. 02 FIXED-PAY. 05 BASIC 05 DA 02 ADDITIONAL-PAY. 05 HRD 05 INCENT 02 DEDUCTIONS. 05 PF 05 IT 05 OTHER 66 PAY-OTHER-THAN-BASIC 66 IT-AND-PF-DEDUCTIONS

PIC 9(6) V99. PIC 9(6) V99. PIC 9(4) V99. PIC 9(3) V99. PIC 9(3) V99. PIC 9(4) V99. PIC 9(3) V99. RENAMES DA THRU INCENT. RENAMES PF THRU IT.

Notes: In order to re-group elementary data items in a record, so that they can belong to the original as well as to the new group, the RENAMES clause is used. The RENAMES clause specifies alternative and possibly overlapping groupings of elementary data items. LEVEL-66 regroups previously defined items. A level-66 entry cannot rename another level-66 entry, nor can it rename a level-01, level-77, or level-88 entry. All level-66 entries associated with one record must immediately follow the last data description entry in that record.

ILLUSTRATES RENAMES CLAUSE


DATE DIVISION. WORKING-STORAGE SECTION. 01 PAY
Copyright Course materials may not be produced in whole or in part without the prior written permission. 31

Student Notebook

02

05

05

66 66

FIXED-PAY 10 E-BASIC PIC 9(6). 99 10 E-DA PIC 9(6). 99. ADDL-PAY. 10 HRA PIC 9(4). 99. 10 INCENTIVE PIC 9(3). 99. DEDUCTIONS. 10 E-PF PIC 9(3). 99. 10 E-IT PIC 9(4). 99. 10 OTHERS PIC 9(3). 99. PAY-LESS-BASIC RENAMES E-DA THRU INCENTIVE. IT-AND-PF RENAMES E-PF THRU E-IT.

PROCEDURE DIVISION. MAIN-PARA MOVE-123456.78 TO E-BASIC. MOVE 234567.89 TO E-DA. MOVE 1234.56 TO HRA. MOVE 123.45 TO INCENTIVE. MOVE 123.45 TO E-PF. MOVE 1234.56 TO E-IT. MOVE 123.45 TO OTHERS. DISPLAY PAY. DISPLAY FIXED-PAY. DISPLAY ADDL-PAY. DISPLAY DEDUCTIONS. DISPLAY PAY-LESS-BASIC. DISPLAY IT-AND-PF. STOP RUN.

Figurative Constants
Constants frequently used by most programs

Copyright Course materials may not be produced in whole or in part without the prior written permission.

32

Student Notebook

Collating sequence is the order in which the characters are compared by the system.

Figurative Constants

Meaning

HIGH-VALUE(S) LOW-VALUES (S) ZERO, ZEROS, ZEROES SPACE (S)

Represents the highest and lowest value in the collating sequence. One or more Zeroes One or more blanks

Example:
Notes:

01 ID-1 PIC X(3) VALUE SPACES.

Figurative constants are reserved words that name and refer to specific constant values. ZERO, ZEROS, ZEROES: Represents the numeric value zero (0) or one or more occurrences of the character zero, depending on context. When the figurative constant ZERO, ZEROS, or ZEROES is used in a context that requires an alphanumeric character, an alphanumeric character zero is used. SPACE: Represents one or more blanks or spaces. SPACE is treated as an alphanumeric literal when used in a context that requires an alphanumeric character, as a DBCS literal when used in a context that requires a DBCS character, and as a national literal when used in a context that requires a national character. HIGH-VALUE: Represents one or more occurrences of the character that has the highest ordinal position in the collating sequence used. HIGH-VALUE is treated as an alphanumeric literal in a context that requires an alphanumeric character.
Copyright Course materials may not be produced in whole or in part without the prior written permission. 33

Student Notebook

LOW-VALUE: Represents one or more occurrences of the character that has the lowest ordinal position in the collating sequence used. LOW-VALUE is treated as an alphanumeric literal in a context that requires an alphanumeric character.

Edited Fields
Move 345.46 to a field of picture 9(3)v99 & display or print You may see different number in result
Copyright Course materials may not be produced in whole or in part without the prior written permission. 34

Student Notebook

Characters must be edited before report is taken to suppress leading zeros, to include currency signs or to include date separators. Editing Codes Z * $ Effect Leading Zeros if any will be suppressed Leading Zeros are replaced by asterisks(*) Currency sign appears in the left most of the field. Appears at left or right of the field as specified in the picture clause if value is negative + Appears if value is positive, else minus sign appears Editing Codes are specified in the picture clause for variables intended for report purpose.

These variables cannot be used for arithmetic calculations.

More Editing Characters


EDIT CODES Meaning

Copyright Course materials may not be produced in whole or in part without the prior written permission.

35

Student Notebook

CR or DB

To be specified in the right most position of the pic clause. Appears only if the value is negative it replaced by two characters.

Stands for decimal point. Cannot specify with V clasue.

, B 0

Insert in position where specified. Blank is appeared. Zero is also appeared. To be specified left most position of pic clasue.

- (hyphen) /(slash)

Used as date separator. Appears where specified.

BLANK WHEN ZERO

Sets all null values to blanks.

EXAMPLES
DATA 02346 0005
Copyright Course materials may not be produced in whole or in part without the prior written permission.

PIC CLAUSE UNEDITED 9(5) 9(4)

PIC CLAUSE EDITED ZZ999 ZZ99

EDITED VALUE 2346 05


36

Student Notebook

03.42 0.007 05634 00143 453 -0453 -0453 453 -453 70.46 156758 00 8654 24

99V99 9V999 9(5) 9(5) 9(3) 9(4) 9(4) 9(3) 9(3) 99V99 9(6) 99V9 9(4) 99

Z999 ZV999 **999 $9(5) $**999 -ZZ9(2) 9999999999+ 99.9999/99/99 99.9 Blank when zero 99b9b9 9900

003 007 *5634 $00143 $**453 -453 0453453 45370.46 15/67/58

86b5b4 2400

Notes: The above table shows contents of unedited fields in the first column. Contents of edited fields after moving the data-1 shown in last column. Edited fields (Fields with editing codes) cannot take part in arithmetic computations. Moving of numeric edited fields to unedited fields is illegal.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

37

UNIT 3

PROCEDURE DIVISION

Copyright Course materials may not be produced in whole or in part without the prior written permission.

38

PROCEDURE DIVISION
PROCEDURE DIVISION[USING <DATA-ITEM1>, <DATA-ITEM2>. MAIN-PARA. DISPLAY ENTER VALUE OF A:. ACCEPT A. DISPLAY ENTER VALUE OF B:. ACCEPT A. MOVE A TO B. ADD A TO B. DISPLAY A VALUE : A. DISPLAY B VALUE : B. ---------------------------------------------------------------STOP RUN.
Notes: Procedure Division can consists of Sections (Optional) Paragraphs (Optional) Statements. While coding, we must follow the following Hierarchy: SECTION------- PARAGRAPHS ------ STATEMENTS Or PARAGRAPH------- STATEMENTS Or STATEMENTS

Copyright Course materials may not be produced in whole or in part without the prior written permission.

39

COBOL VERBS
All instructions are coded in Procedure division. BASIC COBOL VERBS MOVE ACCEPT DISPLAY PERFORM GO TO STOP RUN CALL COPY SORT MERGE FILE OPERATIONS CHARACTER HANDLING TABLE HANDLING CONDITIONS ARITHMETIC VERBS

Notes: Arithmetic Verbs Conditions File handling Character handling Table handling : ADD, SUBTRACT, MULTIPLY, DIVIDE, COMPUTE : IF.ELSE, EVALUATE : READ, WRITE, REWRITE, DELETE : INSPECT, STRING, UNSTRING : SET, SEARCH

Paragraphs
Paragraphs are building blocks of the PROCEDURE DIVISION
Copyright Course materials may not be produced in whole or in part without the prior written permission. 40

PROCEDURE DIVISION. MAIN-PARA. STATEMENT1. STATEMENT2. ------------------------------------------------------------PARA-100. -----------------------------------------

Notes: A paragraph-name must begin in Area A and must be followed by a separator period. A paragraph-name need not be unique because it can qualified by a SECTION name. Paragraph-names need NOT contain any alphabetic character (i.e. can be all numeric). A paragraph ends at: The next paragraph-name or section header The end of the PROCEDURE DIVISION The Scope terminator END-PARAGRAPH

Terminator Statements
EXIT PROGRAM
Copyright Course materials may not be produced in whole or in part without the prior written permission. 41

The EXIT PROGRAM statement specifies the end of a called program and returns control to the calling program

STOP RUN The STOP RUN statements halts the execution of the object program, and returns control to the system

GOBACK The GOBACK statement functions like the EXIT PROGRAM statement. When it is coded as part of a called program and like the STOP RUN when coded in a main program

Notes: If these statements are not the last statements in a sequence, statements following them will not be executed.

Scope Terminators
Explicit scope terminators mark the end of certain PROCEDURE DIVISION statements. Explicit scope terminators are COBOL Reserved Words.
Copyright Course materials may not be produced in whole or in part without the prior written permission. 42

END-ADD END-SEARCH END-CALL END-MULTIPLY END-START END-COMPUTE END-PERFORM END-STRING END-DELETE END-READ END-DIVIDE END-UNSTRING END-EVALUATE END-REWRITE END-WRITE END-IF An explicit Scope Terminator is paired with the unpaired occurrence of the verb. An implicit Scope Terminator is a separator period.
Notes: Example: PERFORM PARA-1 UNTIL A > 10 STATEMENT1 STATEMENT2 -------------------------------------END-PERFORM. Period (.) should not encounter in between PERFORM and END-PERFORM. Since it indicates end of the PERFORM statement, then compiler error will raise.

DISPLAY Verb
The function of the DISPLAY statement is to display low-volume results on the operators console or some other hardware device.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

43

Syntax: >>____DISPLAY_____ __identifier-1___ __ | _____________________________________________> | _ literal-1______| E.g: PROCEDURE DIVISION. DISP-PARA. DISPLAY SRCH-ARG NOT IN TABLE.. ---------------------------------------------------------------DISPLAY HELLO HOW ARE YOU.
Notes: The DISPLAY statement transfers the contents of each operand to the output device. The contents are displayed on the output device in the order, left to right, in which the operands are listed. WITH NO ADVANCING when specified, the positioning of the output device will not be changed in any way following the display of the last operand.

ACCEPT Verb
Format 1 transfers data from an input/output device into identifier1. When the FROM phrase is omitted, the system input device is assumed.
Copyright Course materials may not be produced in whole or in part without the prior written permission. 44

Format 1 is useful for exceptional situations in a program when operator intervention (to supply a given message, code, or exception indicator) is required. Format 1 : >>__ACCEPT______identifier-1___ _______________________________ ______________>< | _ FROM__ _mnemonic-name-1___ _| | _ environment-name _ | 77 SEARCH-VALUE PIC X(10). . ACCEPT SEARCH-VALUE FROM SYSIN.
Notes: The ACCEPT statement transfers data into the specified identifier. There is no editing or error checking of the incoming data. If the source of the ACCEPT statement is a file and identifier-1 is filled without using the full record delimited by the record terminator, the remainder of the input record is used in the next ACCEPT statement for the file. The record delimiter characters are removed from the input data before the input records are moved into the ACCEPT receiving area. If the source of the ACCEPT statement is a terminal, the data entered at the terminal, followed by the enter key, is treated as the input data. If the input data is shorter than identifier-1, the area is padded with spaces.

MOVE Verb
MOVE verb is used to copy the contents of an identifier into another identifier. MOVE <identifier-1> Or <literal-1>
Copyright Course materials may not be produced in whole or in part without the prior written permission.

TO <identifier-2>[<identifier-3>,.].

45

E.g.: MOVE MOVE MOVE MOVE MOVE A TO B, C, D dataname-1 to dataname-2 345 to num-1 345 TO K XYZ TO data-name-1

If the length of the receiving field is less than the length of sending field then truncation occurs.
Notes: The MOVE statement transfers data from one area of storage to one or more other areas. An index data item cannot be specified in a MOVE statement. If the sending field (identifier-1) is reference-modified, subscripted, or is an alphanumeric or alphabetic function-identifier, the reference-modifier, subscript, or function is evaluated only once, immediately before data is moved to the first of the receiving operands.

Elementary & Group Moves


The receiving or sending field of a MOVE statement can be either an elementary item or a group item. When both the fields are elementary items, the data movement is known as an elementary move. When atleast one of the fields is a group item, it is called group move. 01 MSG-FLD
Copyright Course materials may not be produced in whole or in part without the prior written permission.

PIC X (10).
46

01 DATA-FLD PIC X (10). 01 OLD-ADDR. 05 NO PIC X (5). 05 NAME PIC X (15). ------------------------------------------------------------01 NEW-ADDR. 05 N-NO PIC X (5). 05 N-NAME PIC X (15). ------------------------------------------------------------MOVE OUT OF SEQUENCE TO MSG-FIELD MOVE SPACES TO OLD-ADDR, NEW-ADDR MOVE DATA-FLD TO MSG-FIELD. MOVE NEW-ADDR TO OLD-ADDR.
Notes: Elementary move Both sending and receiving data items are elementary items Data conversion may take place, as well as editing or de-editing On alphabetic moves, all necessary space-fill or truncation will occur

Group Move Both sending and receiving data items are group items No data conversion takes place

CORRESPONDING Phrase
01 STRUCT-1. 03 FIELD-A 03 FIELD-B 03 FIELD-C 03 FIELD-D 01 STRUCT-2. 10 FIELD-C 10 FILLER 10 FIELD-B
Copyright Course materials may not be produced in whole or in part without the prior written permission.

PIC PIC PIC PIC PIC PIC PIC

9(9) X(5) 9(4)V99 9(4)V99

VALUE 23456789. VALUE abcde. VALUE 1234.56. VALUE 123456789.

Z(4).99. XXX. X(5).


47

10 FILLER 10 FIELD-A 10 FILLER

PIC PIC PIC

XXX. Z(9) XXX.

MOVE CORRESPONDING STRUCT-1 TO STRUCT-2 Statement moves 3 fields but gives warning.
Notes: Given the data definitions in the visual, the MOVE CORRESPONDING statement in the visual moves three fields (FIELD-A, FIELD-B and FIELD-C) but gives a warning message similar to the one below.

ILLUSTRATES MOVE CORRESPONDING


DATA DIVISION WORKING STORAGE SECTION. 01 DATA-1 05 E-ID PIC 9(5) 05 E-NAME PIC X (25) 05 E-DEPT PIC X (20) 05 E-BASIC PIC 9(4) V99 01 DATA-2. 05 FILLER PIC X(5)
Copyright Course materials may not be produced in whole or in part without the prior written permission.

VALUE VALUE VALUE VALUE

2345. ALL N. ALL D 1234.67.

48

05 05 05 05 05 05 05

E-ID FILLER E-NAME FILLER E-DEPT FILLER E-BASIC

PIC PIC PIC PIC PIC PIC PIC

9(5) X(5) X (25). X(5). X(20) X(5) 9(4). 99

PROCEDURE DIVISION. PARA 1. MOVE E-ID OF DATA-1 TO E-ID OF DATA-2 MOVE E-NAME OF DATA-1 TO E-NAME OF DATA-2. MOVE E-DEPT OF DATA-1 TO E-BASIC OF DATA-2. DISPLAY DATA-1 DISPLAY DATA-2 MOVE SPACES TO DATA-2. MOVE CORRESPONDING DATA-1 TO DATA-2. DISPLAY DATA-1 DISPLAY DATA-2. STOP RUN.

Reference Modification
Reference Modification defines a data item by specifying its leftmost character and optionally, a length

MOVE data-name1 (begin : [length]) TO data-name2 If length is omitted, the data item continues to rightmost character of data-name1 (the colon is required). The data name must have usage

Copyright Course materials may not be produced in whole or in part without the prior written permission.

49

DISPLAY. It may be qualified or subscripted. When qualified or subscripted, the reference modification is specified last.

Notes: Eg: WORKING-STORAGE SECTION. 01 CAT-TYPE PIC X(15) VALUE 'CALICO'. 01 DOG-TYPE PIC X(15) VALUE 'SCHNAUZER'. 01 CAT-ABBREV PIC X(5). 01 DOG-END PIC X(10). PROCEDURE DIVISION. *Reference Modification Example Number 1: (From position 1:For 5 positions.)

MOVE CAT-TYPE(1:5) TO CAT-ABBREV. *This will move "CALIC" to CAT-ABBREV. (The letters from position 1 of CAT-TYPE for 5 positions.) DISPLAY CAT-ABBREV. *Reference Modification Example Number 2: (From position 2: For 4 Bytes.) MOVE CAT-TYPE(2:4) TO CAT-ABBREV. *This will move "ALIC" to CAT-ABBREV2. (The letters from position 2 of CAT-TYPE for 4 positions.) DISPLAY CAT-ABBREV. *Reference Modification Example Number 3: (From position number 5 to the end of the field.) MOVE DOG-TYPE (5:) TO DOG-END.
Copyright Course materials may not be produced in whole or in part without the prior written permission. 50

*This will move "AUZER" to DOG-END. (The letters from position 5 of DOGTYPE to the end of DOG-TYPE.) DISPLAY DOG-END.

ADD Verb
All identifiers (or literals) preceding the word TO are added together, and then this sum is added to, and replaces, each identifier-2. The action is repeated in order left-to-right for each identifier-2 Identifiers must be elementary numeric items Format 1 :

Copyright Course materials may not be produced in whole or in part without the prior written permission.

51

>>___ADD_______ identifier-1_ _|__ To _____identifier-2__ ________ ____________ __|_________> |_literal-1___| |_ROUNDED _| >___ ____________________________________________________ ___________________________> |_ ____ __SIZE ERROR imperative-statement-1______| >___ _____________________________________________________ ___________________________> |_ NOT___ ______ ___SIZE ERROR__imperative statement_2_| >___ _______ _________________________________________________> |_ END-ADD_|

In Format 1, all identifiers or literals preceding the key word TO be added together and this sum is stored in a temporary data item. This| temporary data item is then added to each successive occurrence of identifier-2, in the left-to-right order in which identifier-2 is specified. Identifier must name an elementary numeric item. Literal must be a numeric. The ADD statement sums two or more numeric operands and stores the result.

Example: ADD A TO B. ADD 112 TO B. ADD A TO B ON SIZE ERROR GO TO ERR-PARA.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

52

ADD Verb (Continue.)


The operands preceding the GIVING are added together and the sum replaces the value of each identifier-3
Copyright Course materials may not be produced in whole or in part without the prior written permission. 53

Identifiers must be elementary numeric items, except when following GIVING then they may also be numeric edited. Format 2:
>>___ADD_______ identifier-1_ _|__ ___ _ ____ _ __ _ identifier-2__ __________________________> |_literal-1___| |_TO_| |_literal-2______|

>___ GIVING ___________identifier-3__ ______________ _| ___________________________________ > |_ ROUNDED__| >___ _____________________________________________________ ____________________________ > |_ _________ ___SIZE ERROR__imperative statement_1_| >___ _____________________________________________________ ___________________________ > |_ NOT___ ______ _SIZE ERROR__imperative statement_2_| |_ ON_| >___ _______ _________________________________________________ > |_ END-ADD_|

In Format 2, the values of the operands preceding the word GIVING are added together, and the sum is stored as the new value of each data item referenced by identifier-3.

Identifier must name an elementary numeric item, except when following the word GIVING. Each identifier following the word

GIVING must name an elementary numeric or numeric-edited item Literal must be a numeric.
Copyright Course materials may not be produced in whole or in part without the prior written permission. 54

Example: ADD A TO B GIVING C

ADD CORRESPONDING Statement


Elementary data items within identifer-1 are added to, and stored in the corresponding elementary data items with identifer-2. ADD CORRESPONDING identifiers must be group items
Copyright Course materials may not be produced in whole or in part without the prior written permission. 55

Format: >>___ADD_______ CORRESPONDING_ ___identifier-1___ TO___ identifier2____________________> |_CORR__________| >___ ______________ __ ______________________________________________ ________________ > |_ ROUNDED__| | _ ___ __SIZE ERROR____ imperative-statement-1_| |_ ON_ | >___ _____________________________________________________ ___________________________ > |_NOT___ ______ __SIZE ERROR__imperative statement_1_| |_ON___| >___ _____________________________________________________ ___________________________ > |_ NOT___ ______ _SIZE ERROR__imperative statement_2_| |_ ON_| >___ _______ _________________________________________________ > |_ END-ADD_|

In Format 3, elementary data items within identifier-1 are added to and stored in the corresponding elementary items within identifier-2. Identifier must name a group item. Literal must be a numeric.
Notes:

ON SIZE ERROR Phrase


If the value of an arithmetic evaluation exceeds the largest value that can be contained in a result, then a size error condition exists. The SIZE ERROR condition applies to final results, not intermediate calculations
Copyright Course materials may not be produced in whole or in part without the prior written permission. 56

If ON SIZE ERROR phrase is not specified, then truncation of the results will occur. If ON SIZE ERROR phrase is specified, the imperative statement (in ON SIZE ERROR) is taken, following which control is transferred to the end of the arithmetic statement. For ADD CORRESPONDING or SUBTRACT

CORRESPONDING, the ON SIZE ERROR imperative is not taken until all individual additions or subtractions have been completed.

A size error condition can occur in three different ways: When the absolute value of the result of an arithmetic evaluation, after decimal point alignment, exceeds the largest value that can be contained in the result field When division by zero occurs In an exponential expression, as indicated in the following table:

Size error Zero raised to zero power Zero raised to a negative number A negative number raised to a fractional power
Copyright

Action taken when a SIZE ERROR clause is present The SIZE ERROR imperative is executed. The SIZE ERROR imperative is executed. The SIZE ERROR imperative is executed

Action taken when a SIZE ERROR clause is not present The value returned is 1, and a message is issued. Program is terminated abnormally. The absolute value of the base is used, and a message is issued

57 Course materials may not be produced in whole or in part without the prior written permission.

The size error condition applies only to final results, not to any intermediate results.

NUMERIC Data
Types of numeric items are:

Binary Packed decimal. (Internal decimal) Floating point representation.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

58

The PICTURE character-string can contain only the symbols 9, P, S and V The number of digit positions must range from 1 through 18, inclusive If unsigned, the contents of the item in standard data format must contain a combination of the Arabic numerals 0-9. If signed, it may also contain a +, - or other representation of the operation sign

Notes:
A VALUE clause can specify a figurative constant ZERO.

SUBTRACT Verb
Format 1:
>>___SUBTRACT_______ identifier-1_ _|__ FROM_________________________________________> |_literal-1___| > ______identifier-2__ _______________ _|________________________________________________> | _ ROUNDED ____|

Copyright Course materials may not be produced in whole or in part without the prior written permission.

59

>___ ____________________________________________________ ___________________________> |_ ____ __SIZE ERROR imperative-statement-1______| |_ON _| >___ _____________________________________________________ ___________________________> |_ NOT___ ______ ___SIZE ERROR__imperative statement_2_| >___ _______ _________________________________________________> |_ END-SUBTRACT_|

All identifiers or literals preceding the key word FROM are added together and this sum is subtracted from and stored immediately in identifier-2. This process is repeated for each successive occurrence of identifier-2, in the left-to-right order in which identifier-2 is specified.

Notes:

SUBTRACT Verb (Continue.)


Format 2:
>>___SUBTRACT_______ identifier-1_ _|__ FROM ___ _ identifier-2__ __________________________> |_literal-1___| |_literal-2______|

>___ GIVING ___________identifier-3__ ______________ _| ___________________________________ > |_ ROUNDED__|


Copyright Course materials may not be produced in whole or in part without the prior written permission. 60

>___ _____________________________________________________ ____________________________ > |_ _______ ___SIZE ERROR__imperative statement_1_| |_ ON _| >___ _____________________________________________________ ____________________________ > |_ NOT___ ______ _SIZE ERROR__imperative statement_2_| |_ ON_| >___ _______ __________________________________________________ > |_ END-SUBTRACT_|

All identifier or literals preceding the key word FROM are added together and this sum is subtracted from identifier-2 or literals-2. The result of the subtraction is stored as the new value of each data item referenced by identifier-3.
Notes: Example: 1. SUBTRACT A FROM B. The value of a subtracted from the value of B and then the resultant value will be stored in B. 2. SUBTRACT 9 FROM C. 3. SUBTRACT C FROM 9. Is not valid because 9 is a Literal.

SUBTRACT CORRESPONDING Statement


Format:
>>___SUBTRACT_______ CORRESPONDING_ ___identifier-1___ FROM________________________> |_CORR__________| >___ identfier-2____ __ ___________ _____________________________________________________ > |_ ROUNDED__| >___ _____________________________________________________ ____________________________ > |____ ______ __SIZE ERROR__imperative statement_1_|
Copyright Course materials may not be produced in whole or in part without the prior written permission. 61

|_ON___| >___ _____________________________________________________ ____________________________ > |_ NOT___ ______ _SIZE ERROR__imperative statement_2_| |_ ON__| >___ _______ __________________________________________________ > |_ END-SUBTRACT_|

Elementary data items within identifier-1 are subtracted from, and the results are stored in, the corresponding elementary data items within identifier-2.

Notes:

MULTIPLY Verb
Format 1:
>>___MULTIPLY_______ identifier-1___ ___BY____identifier-2___ __________________| __________> |_ literal-1________| >___ _____________________________________________________ ____________________________ > |____ ______ __SIZE ERROR__imperative statement_1_| |_ON___| >___ _____________________________________________________ ____________________________ > |_ NOT___ ______ _SIZE ERROR__imperative statement_2_| |_ ON__| >___ _______ _________________________________________________ ><
Copyright Course materials may not be produced in whole or in part without the prior written permission. 62

|_ END-MULTIPLY_|

In Format 1, the value of identifier-1 or literal-1 is multiplied by the value of identifier-2; the product is then placed in identifier-2. For each successive occurrence of identifier-2, the multiplication takes place in the left-to-right order in which identifier-2 is specified.

Notes: The MULTIPLY statement multiplies numeric items and sets the values of data items equal to the results.

MULTIPLY Verb (continue..)


Format 2:
>>___MULTIPLY_______ identifier-1_ _|__ BY_______ _ identifier-2__ __________________________> |_literal-1___| |_literal-2______|

>___ GIVING ___________identifier-3__ ______________ _| ___________________________________ > |_ ROUNDED__| >___ _____________________________________________________ ____________________________ > |_ _______ ___SIZE ERROR__imperative statement_1_| |_ ON _|

Copyright Course materials may not be produced in whole or in part without the prior written permission.

63

>___ _____________________________________________________ ____________________________> |_ NOT___ ______ _SIZE ERROR__imperative statement_2_| |_ ON_| >___ _______ _________________________________________________ > |_ END-MULTIPLY_|

In Format 2, the value of identifier-1 or literal-1 is multiplied by the value of identifier-2 or literal-2. The product is then stored in the data item(s) referenced by identifier-3.

Notes:

DIVIDE Verb
Format 1:
>>___DIVIDE_____ _____ identifier-1_ _|__ INTO__________identifier-2____ _________ __ |____> |_literal-1___| |_ROUNDED _| >___ ____________________________________________________ ____________________________> |_ ____ __SIZE ERROR imperative-statement-1____________| |_ON _| >___ _____________________________________________________ ____________________________> |_ NOT___ ______ ___SIZE ERROR__imperative statement_2_| |_ON __| >___ _______ __________________________________________________> |_ END-DIVIDE_|
Copyright Course materials may not be produced in whole or in part without the prior written permission. 64

In Format 1, the value of identifier-1 or literal is divided into the value of identifier-2, and the quotient is then stored in identifier-2. For each successive occurrence of identifier-2, the division takes place in the leftto-right order in which identifier-2 is specified.

Notes: The DIVIDE statement divides one numeric data item into or by other(s) and sets the values of data items equal to the quotient and remainder

DIVIDE Verb (Continue)


Format 2:
>>___DIVIDE_______ identifier-1_ _|__ INTO_______ _ identifier-2__ ___________________________> |_literal-1___| |_literal-2______|

>___ GIVING ___________identifier-3__ ______________ _| ___________________________________ > |_ ROUNDED__| >___ _____________________________________________________ ____________________________ > |_ _______ ___SIZE ERROR__imperative statement_1_| |_ ON _| >___ _____________________________________________________ ____________________________> |_ NOT___ ______ _SIZE ERROR__imperative statement_2_| |_ ON_|
Copyright Course materials may not be produced in whole or in part without the prior written permission. 65

>___ _______ _________________________________________________ > |_ END-DIVIDE_|

In Format 2, the value of identifier-1 or literal-1 is divided into or by the value of identifier-2 or literal-2. The value of the result is stored in each data item referenced by identifier-3.

Notes:

COMPUTE Verb
Format:
>>___COMPUTE_______ identifier-1_ ____________ _|____ _ =______ __________________________> |_ ROUNDED _| |_ EQUAL_| >___ arithmetic expression_______________________________________________________________ _> ____________________________ > |_ _______ ___SIZE ERROR__imperative statement_1_| |_ ON _| >___ _____________________________________________________ ____________________________ > |_ NOT___ ______ _SIZE ERROR__imperative statement_2_| |_ ON_| >___ _______ __________________________________________________ > |_ END-COMPUTE_|

Copyright Course materials may not be produced in whole or in part without the prior written permission.

66

The arithmetic expression is calculated and replaces the value for each identifier-1 item. Valid operators allowed in the expression are: + addition * multiplication ** exponentiation
Notes: The COMPUTE statement assigns the value of an arithmetic expression to one or more data items. With the COMPUTE statement, arithmetic operations can be combined without the restrictions on receiving data items imposed by the rules for the ADD, SUBTRACT, MULTIPLY, and DIVIDE statements.

- subtraction / division

Identifier-1 Must name elementary numeric item(s) or elementary numeric-edited item(s). Can name an elementary floating-point data item. The word EQUAL can be used in place of =. An arithmetic expression ca consists of any of the following: 1. 2. 3. 4. An identifier described as a numeric elementary item A numeric literal The figurative constant ZERO Identifiers are literals, as defined in terms 1,2, and 3, separated by arithmetic operators 5. Two arithmetic expressions, as defined in items 1,2,3, and/or 4, separated by an arithmetic operator 6. An arithmetic expression, as defined in items 1,2,3,4 and/or 5, enclosed in parentheses.

When the COMPUTE statement is executed, the value of the arithmetic expression is calculated, and this value is stored as the new value of each data item referenced by identifier-1.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

67

PERFORM Statement
PERFORM Paragraph-name/Section-header

Transfer the control to the specified paragraph or section and expects the control back after executing the paragraph.

PERFORM Para-name-1 [ THROUGH (or) THRU Para-name-n]

Notes:

Copyright Course materials may not be produced in whole or in part without the prior written permission.

68

PERFORM types PERFORM Para-name PERFORM Para-name N TIMES PERFORM Para-name VARYING K FROM M BY N UNTIL CONDITION K>20 PERFORM Para-name VARYING K FROM M BY N UNTIL CONDITION K>20 AFTER VARYING.

PERFORM THROUGH
PROCEDURE DIVISION. 100-MAIN-PARA. PERFORM 200-PARA THRU 500-PARA. STOP RUN. 200-PARA. * Statements. 400-PARA. * Statements 500-PARA. * Statements 300-PARA. Statement

- Not executed

All the paragraphs between 200-PARA and 500-PARA are executed.

Notes:

Copyright Course materials may not be produced in whole or in part without the prior written permission.

69

PERFORMN times
PERFORM PARA-NAME-1[THROUGH (or) THRU PARA-NAME-N] N TIMES.
EX:

PERFORM PARA-1000 15 TIMES. PERFORM PARA-1000 THRU PARA-4000 15 TIMES. PARA-1000. ADD A TO B. -----------------------------------------------PARA-2000. SUBTRACT A FROM B. ------------------------------------------------------------PARA-4000. MULTIPLY A BY B. ----------------------------

Notes:

Copyright Course materials may not be produced in whole or in part without the prior written permission.

70

PERFORMVARYING
PERFORM PARA-NAME-1 [THRU (or) THROUGH PARA-NAME-N] VARYING { identifier- 1 } {identifier-2 } {Index-name-1} FROM {index-name-2} { Literal-1 }

BY

{identifier-3 } {Literal-2 }

UNTIL

Condition

EX: PERFORM PARA-2000 THRU PARA-5000 VARYING A FROM M BY N UNTIL A > Y PERFORM para-1 Varying K FROM 10 BY 5 UNTIL K>100

Notes: Example 2 says: Sets the value of K to 10 initially Execute para-1


Copyright Course materials may not be produced in whole or in part without the prior written permission. 71

Check the condition K > 100 If condition is true, transfer the control to next line If condition is false, increment K by 5 Execute para-1 again Check the condition K > 100 Repeat steps from 2 through 7 until Condition K > 100 becomes true

Flow Chart for PERFORM .. VARYING

Enter

Set identifier 1 to initial value

True Condition False Exit

False

Execute range

Add increment to identifier.


Copyright Course materials may not be produced in whole or in part without the prior written permission. 72

PERFORM with the VARYING-AFTER Option


PERFORM PARA-NAME-1 [THRU (or) THROUGH PARA-NAME-N] VARYING { identifier- 1 } {identifier-2 } {Index-name-1} FROM {index-name-2} {Literal-1 } BY {identifier-3 } {Literal-2 } UNTIL Condition-1

AFTER

{ identifier- 4 } { Index-name-3}

FROM

{identifier-5 } {index-name-4} { Literal-3 } Condition-2

BY

{identifier-6} {Literal-4 }

UNTIL

AFTER

{ identifier- 7 } {Index-name-5} FROM

{identifier-8 } {index-name-6} { Literal-5 } Condition-3

BY

{identifier-9 } {Literal-6 }

UNTIL

This form is used when a nested repetition of the range is required while varying more than one identifier.
Copyright Course materials may not be produced in whole or in part without the prior written permission. 73

For example: PERFORM RANGE-TO-BE-EXECUTED VARYING I FROM 1 BY 1 UNTIL I > 50 AFTER J FROM 1 BY 1 UNTIL J > 10. The range RANGE-TO-BE-EXECUTED will be performed 500 times,.

In-Line PERFORM
The in-line PERFORM will be coded using END-PERFORM. Named Paragraph PERFORM MOVEIT VARYING X FROM 1 BY 1 UNTIL X = 5. ... MOVEIT. MOVE DATA-FLD (X) TO PRINT (X). In-line PERFORM PERFORM VARYING X FROM 1 BY 1 UNTIL X = 5. MOVE DATA-FLD (X) TO PRINT (X). END-PERFORM.
Notes: An In-line PERFORM requires the END-PERFORM terminator. Conversely the END-PERFORM phrase must not be specified when the statement is PERFORM procedure name.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

74

IN-LINE PERFORM Considerations


DO not use for procedures executed from several places/ Use for procedures referenced only once. Consider not using if readability is affected , such as multiple-page PERFORM, No periods may appear within the in-line PERFORM. Delimited by END-PERFORM. END-PERFORM cannot be used at end of an out-of-line PERFORM. The OPTIMIZE compile option may move the PERFORM in-line in the object code at the compile time.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

75

IF... ELSE Statement


The IF statement evaluates a condition and provides for alternative actions in the object program, depending on the evaluation. Format : >>_______IF_____Condition-1____ __________ _____ ___statement1___|__ ____________________> |_THEN_____| |_NEXT SENTENCE _| >___ ____________________________ ____ ________________ ______________________________> | <____________ | | (1) | | _ ELSE__ ___statement-2_|_____ | |___END-IF________| Note : (1) END-IF can be specified with NEXT SENTENCE as an IBM extension.

Notes: The IF statement evaluates a condition and provides for different sets of statements to execute, depending on the evaluation of the IF. Condition can be any simple or complex condition. Statement-1, statement-2 Can be any one of the following: An imperative statement An conditional statement An imperative statement followed by a conditional statement NEXT SENTENCE If the NEXT SENTENCE phrase is specified, and then the END-IF phrase must not be specified. NEXT SENTENCE passes control to the statement after the closest following period. However, if the NEXT SENTENCE phrase is executed, control will not pass to the statement after the closest following period.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

76

Compound Conditionals
Conditional expressions can be compound using the AND and OR logical operators Conditional conditions can also use parentheses to group conditions. IF ITEM-1 = DOMESTIC-ITEM-NO AND ITEM-2 = OVERSEAS-ITEM-NO OR ITEM-1 = OVERSEAS-ITEM-NO AND ITEM-2 = DOMESTIC-ITEM-NO SET MIXED-SHIPMENT-FLAG TO TRUE END-IF . SEARCH TABLEPAIR VARYING NDX WHEN ITEM-1(NDX) = FROM-CITY AND ITEM-2(NDX) = TO-CITY MOVE WHEN ITEM-2(NDX) = FROM-CITY AND ITEM-1(NDX) = TO-CITY MOVE .. END-SEARCH

Notes:

Relational Expressions
Copyright Course materials may not be produced in whole or in part without the prior written permission. 77

Relational tests (comparisons) can be express as: IS LESS THAN IS NOT LESS THAN GREATER THAN IS NOT GREATER THAN IS EQUAL TO IS NOT EQUAL TO IS GREATER THAN OR EQUAL TO IS LESS THAN OR EQUAL TO < NOT < > NOT > = NOT = >= <=

Notes:

CONTINUE & NEXT SENTENCE Statement


Example 1 - NEXT SENTENCE IF A = B
Copyright Course materials may not be produced in whole or in part without the prior written permission. 78

IF C = D NEXT SENTENCE ELSE MOVE MESSAGE-1 TO RPT-MESSAGE-1 END-IF ADD C TO TOTAL DISPLAY TOTAL IF E = F MOVE MESSAGE-4 TO RPT-MESSAGE-2 END-IF END-IF. Example 2 - CONTINUE IF A = B IF C = D CONTINUE ELSE MOVE MESSAGE-1 TO RPT-MESSAGE-1 END-IF ADD C TO TOTAL DISPLAY TOTAL IF E = F MOVE MESSAGE-4 TO RPT-MESSAGE-2 END-IF END-IF.

Notes:

EVALUATE Statement
EVALUATE is a great way to implement the case programming construct EVALUATE dataname WHEN value-1 . Course materials may not be produced in whole or in part WHEN value-2 {THROUGH | THRU} without the prior written permission. value-3 . WHEN NOT value-4

Copyright

79

Basic EVALUATE Example: EVALUATE dataname WHEN A WHEN D WHEN U WHEN W WHEN OTHER END-EVALUATE

Perform add-trans Perform delete-trans Perform update-trans Perform bad-trans

The scope of a WHEN clause is all statements UNTIL the next WHEN clause, the END-EVALUATE, or a period

Notes: The EVALUATE statement provides a shorthand notation for a series of nested IF statements. It can evaluate multiple conditions. That is, the IF Statements can be made up of compound conditions.

Examples:
Working-Storage for all Examples: 01 PLANET. 05 PLANET-NUMBER PIC 9. 05 PLANET-NAME PIC X(7). Evaluate Example Number 1: (Evaluate a PIC 9 field)
Copyright Course materials may not be produced in whole or in part without the prior written permission. 80

EVALUATE PLANET-NUMBER WHEN 1 MOVE "Mercury" TO PLANET-NAME WHEN 2 MOVE "Venus " TO PLANET-NAME WHEN 3 MOVE "Earth " TO PLANET-NAME WHEN 4 MOVE "Mars " TO PLANET-NAME WHEN 5 MOVE "Jupiter" TO PLANET-NAME WHEN 6 MOVE "Saturn " TO PLANET-NAME WHEN 7 MOVE "Uranus " TO PLANET-NAME WHEN 8 MOVE "Neptune" TO PLANET-NAME WHEN 9 MOVE "Pluto " TO PLANET-NAME WHEN OTHER MOVE " " TO PLANET-NAME END-EVALUATE. Evaluate Example Number 2: (Evaluate a PIC X field) EVALUATE PLANET-NAME WHEN "Mercury" MOVE 1 WHEN "Venus " MOVE 2 WHEN "Earth " MOVE 3 WHEN "Mars " MOVE 4 WHEN "Jupiter" MOVE 5 WHEN "Saturn " MOVE 6 WHEN "Uranus " MOVE 7 WHEN "Neptune" MOVE 8 WHEN "Pluto " MOVE 9 WHEN OTHER MOVE 0 END-EVALUATE.

TO TO TO TO TO TO TO TO TO TO

PLANET-NUMBER PLANET-NUMBER PLANET-NUMBER PLANET-NUMBER PLANET-NUMBER PLANET-NUMBER PLANET-NUMBER PLANET-NUMBER PLANET-NUMBER PLANET-NUMBER

Evaluate Example Number 3: Let each of MONTH and NO-OF-Days be two-digited numeric integer fields. The values 1,2,3, etc. for MONTH denote respectively, January, February, March etc. depending on the value of MONTH , we wish to ove 30,31 or 28 to NO-OF-DAYS. For example , if the value of MONTH is 1, we shall move 31; if it is 2, we shall move 28 and so on. The EVALUATE statement for the purpose is as follows: EVALUATE TRUE WHEN MONTH = 4 OR 6 OR 9 OR 11 MOVE 30 TO NO-OF-DAYS WHEN MONTH = 2 MOVE 28 TO NO-OF- DAYS WHEN OTHER MOVE 31 TO NO-OF-DAYS END EVALUATE. In this case, we have assumed that MONTH has a correct value. Evaluate Example Number 4: Suppose MARKS contains the marks obtained by a student. GRADE is an one- character alphanumeric field. We wish to calculate GRADE according to the following rules
Copyright Course materials may not be produced in whole or in part without the prior written permission. 81

MARKS

GRADE

80 100 A 60 - 79 B 45 - 59 C 30 - 44 D 0 - 29 E The EVALUATE statement for the purpose is shown below. EVALUATE MARKS WHEN 80 THRU 100 MOVE A TO GRADE WHEN 60 THRU 79 MOVE B TO GRADE WHEN 45 THRU 59 MOVE C TO GRADE WHEN 30 THRU 44 MOVE D TO GRADE WHEN ZERO THRU 29 MOVE E TO GRADE WHEN OTHER MOVE W TO GRADE END-EVALUATE. The literal W is moved to GRADE in the case of wrong marks.

ILLUSTRATES CONDITION NAMES


DATA DIVISION. WORKING-STORAGE SECTION. 77 88 88 88 88 88 MARTIAL-STATUS SINGLE MARRIED WIDOWED DIVORCED ONCE-MARRIED PIC 9. VALUE 0. VALUE 1. VALUE 2. VALUE 3. VALUES ARE 1, 2, 3.
82 Course materials may not be produced in whole or in part without the prior written permission.

Copyright

88 77

VALID-STATUS AMOUNT

PIC 9 (4)

VALUES ARE 0 THRU 3. VALUE 1000.

PROCEDURE DIVISION. MAIN-PARA. DISPLAY Martial Status: DISPLAY 0- Single / 1- Married / 2- Widowed / 3- Divorced. ACCEPT MARTIAL-STATUS. IF NOT VALI-STATUS DISPLAY Error in Entry. IF SINGLE SUBTRACT 100 TO AMOUNT. IF MARRIED ADD 100 TO AMOUNT. IF WIDOWED ADD 200 TO AMOUNT. IF DIVORCED SUBTRACT 200 FROM AMOUNT. IF ONCE-MARRIED ADD 250 TO AMOUNT DISPLAY AMOUNT. STOP RUN.

INITIALIZE Statement
The INITIALIZE statement sets selected categories of data fields to predetermined values. It is functionally equivalent to one or more MOVE statements. When the REPLACING phrase is not used: SPACE is the implied sending field for alphabetic alphanumeric, alphanumeric-edited, and DBCS items. ZERO is the implied sending field for numeric and numeric-edited items.
>>___INITIALIZE____identifier1_________________________________________________________________> _______>< | < _____________________________________________ __________________ Copyright Course materials may not be produced in whole or in part without the prior written permission.

| 83

|_REPLACING____ _ALPHABETIC_______ __ _______ __BY____ identifier-2 _ _ | _ | |_ALPHANUMER____| |_DATA_| |_LITERAL-1__| |_NUMERIC __________| |_ALPHANUMERIC-EDITED_| |_NUMERIC-EDITED__| |_ DBCS _____________| |_ EGCS _____________|

Notes: The INITIALIZE statement sets selected categories of data fields to predetermined values. It is functionally equivalent to one or more MOVE statements. A subscripted item can be specified for identifier-1. A complete table can be initialized only by specifying identifier-1 as a group that contains the complete table. The data description entry for identifier-1 must not contain a RENAMES clause. An index data item cannot be an operand of INITIALIZE. Special registers can be specified for identifier-1 and identifier-2 only if they are valid receiving fields or sending fields, respectively, for the implied MOVE statement(s).

When the REPLACING phrase is used: The category of identifier-2 or literal-1 must be compatible with the category indicated in the corresponding REPLACING phrase, according to the rules for the NUMERIC category. The same category cannot be repeated in a REPLACING phrase. The Key word following the word REPLACING corresponds to a category of data shown Classes of Data visual.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

84

SET TO TRUE Statement


When this form of the SET statement is executed, the value associated with a condition-name is placed in its conditional variable according to the rules of the VALUE clause. >>__SET____condition-name-1_|_ TO TRUE_________________________>< condition-name-1: Must be associated with a conditional variable. If more than one literal is specified in the VALUE clause of condition-name1, its associated conditional variable is set equal to the first literal. 01 CUST-TYPE PIC 99. 88 INACTIVE VALUE 9. 88 SPEC-ACCTS VALUE 20, 11, 40, 44.
Copyright Course materials may not be produced in whole or in part without the prior written permission. 85

SET INACTIVE TO TRUE SET SPEC-ACCTS TO TRUE

Notes:

Class Condition
NUMERIC The item entirely contains characters 0 through 9 (with or without a sign determined by its PICTURE clause). It may be USAGE DISPLAY or PACKED DECIMAL. ALPHABETIC The entire item contains only A through Z, a through z, or spaces ALPHABETIC-UPPER The entire item contains only A through Z (exclusively upper-case) or spaces. ALPHABETIC-LOWER The entire item contains only a through z (exclusively lower-case) or spaces.

Notes:
Copyright Course materials may not be produced in whole or in part without the prior written permission. 86

Ex: 1. IF A IS NUMERIC -------------------------------------------2. IF C IS ALPHABETIC ---------------------------------------------Where A and C are Data items.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

87

Student Notebook

UNIT 4

FILE HANDLING IN COBOL

Copyright Course materials may not be produced in whole or in part without the prior written permission.

89

Student Notebook

FILES
A record is a group of logically or functionally related fields. A File is a group of Records. A group of records, which can be created, copied, modified, retrieved and deleted. E.g.: Details of an employee -Name, Adds, Phone no., Dept no etc Forms a record

Details of all employees -Group of such record forms a file.

Notes: Files can be broadly categorized into Program files and Data files. In COBOL the term Files is used to indicate data files. Data files are normally created on a tape or disk and subsequently program can refer them.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

90

Student Notebook

Fixed vs Variables Length Records


Fixed length records. Corresponding fields of all the records have same length. Variable length records. Field lengths may vary from record to record.

Notes: The size of a record is the cumulative size of all the fields in it. If all the records of a file have the same structure then they are called Fixed length-records. For convenience, records of different lengths can be placed together in one file. Then they are known as variable-length-records.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

91

Student Notebook

FILE-CONTROL Paragraph
Format: SELECT [OPTIONAL] File-name-1 ASSIGN TO Assignment-name-1 [ RESERVE <INTEGER> AREA ] SEQUENTIAL [ ORGANIZATION IS INDEXED ] RELATIVE SEQUENTIAL RANDOM DYNAMIC

[ACCESS MODE IS

[FILE STATUS IS Data-name-1]


Notes: The FILE-CONTROL paragraph associates each file with an external data-set. FILE_CONTROL paragraph is in INPUT-OUTPUT Section of ENVIRONMENT Division.Not all options are available on all platforms. SELECT OPTIONAL may be specified only for files opened in the input, I-O, or extended mode. You must specify SELECT OPTIONAL for such input files that are not necessarily present each time the program is executed. The file-name-1 must be identified by an FD or SD entry in the DATA DIVISION. The ASSIGN clause associates the programs name for a file with the external name for the actual data file. The RESERVE clause allows you to specify the number of input/output buffers to be allocated at run time for the file. The ORGANIZATION clause identifies the logical structure of the file.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

92

Student Notebook

ORGANIZATION IS SEQUENTIAL
The Records are stored in contigious allocation. To access the record in Sequential mode only(I,e to read the last record, it reads all the records until last record found.) Deletion of record is not possible.Updation is possible but record length should not changed.

ORGANIZATION IS INDEXED
Each record in the file has one or more embedded keys; each key is associated with an index. An index provides a logical path to the data records, according to the contents of the associated embedded record key data items. Indexed files must be direct-access storage files. Records can be fixed-length or variable-length. Each record in an indexed file must have an embedded prime key data item. When records are inserted, updated, or deleted, they are identified solely by the values of their prime keys. Thus, the value in each prime key data item must be unique and must not be changed when the record is updated. In addition, each record in an indexed file can contain one or more embedded alternated key data items. Each alternated key provides another means of identifying which record to retrieve. The RECORD KEY clause specifies the data item within the record that is the prime RECORD KEY for an indexed file. The values contained in the prime RECORD KEY data item must be unique among records in the file. The ALTERNATRE RECORD KEY clause specifies a data item within the record that provides an alternated path to the data in an indexed file. Used like the RECORD KEY but for an alternate index.

ORGANIZATION IS RELATIVE
The INPUT-OUTPUT FILE-CONTROL for Relative record files is very similar to that of indexed files except you use the RELATIVE KEY clause of the ACCESS MODE phrase and each record identified by the Relative Record Number instead of Recoed Key.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

93

Student Notebook

ACCESS Mode
Modes SEQUENTIAL Meaning Records of the file can be accessed sequentially, starting from first record till the required record is reached. Any record can be accessed beginning from the first record. directly without

RANDOM

DYNAMIC

Records can be accessed both randomly and/or sequentially

Notes: The record of a file stored on a magnetic tape can be accessed in sequential mode only. But the records of file stored on magnetic disk can be accessed in all the modes.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

94

Student Notebook

FILE STATUS Clause


A two-digit number indicates the status of the file.

Value 00 10 30 34

Status Successful Completion At end condition Permanent error Boundary violation

Notes: Input-Output operations may not be successful thus resulting in termination of the program. The data-name specified in the file-status clause contains the status code and can be referred by the programmer. Depending on the code programmer can take specific actions by transferring the control to error-routine paragraphs. The data name should be declared in working-storage section with alphanumeric data type of two characters.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

95

Student Notebook

I-O-CONTROL Paragraph
The Optional I-O-CONTROL paragraph of the Input-Output Section specifies when checkpoints are to be taken and the storage areas to be shared by different files. Specifies information needed for efficient transmission of data between the external data set and the COBOL program.

Notes: The I-O-CONTROL paragraph is optional. The key word I-O-CONTROL can appear only once, at the beginning of the paragraph. The word I-O-CONTROL must begin in Area A, and must be followed by a separator period. Each clause within the paragraph can be separated from the next by a separator comma or a separator semicolon. The order in which I-O-CONTROL paragraph clauses are written is not significant. The I-O-CONTROL paragraph ends with a separator method.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

96

Student Notebook

FILE SECTION
FILE SECTION. FD File-Name BLOCK CONTAINS m RECORDS RECORD CONTAINS n CHRACTERS LABEL RECORDS ARE STANDARD/ OMMITED 01 File-record-structure.

Notes: Each file used in the program should have an FD entry (File Description) in FILE SECTION. BLOCK CONTAINS clause specifies number of records in the block. RECORD CONTAINS clause specifies total number of characters in each record. LABEL RECORDS clause indicates Disk files if STANDARD option is specified Print files if OMITTED option is specified Value clause specifies the name of the physical file and the path 01 level entry should follow immediately after FD paragraph. Blocking Input-Output operations are slower compared to CPU processing speed. To reduce the CPU waiting time, block of records from the disk can be moved to the memory space called buffer thus reducing number of I-O operations. The Programmer can specify the number of records contained in a block. Suitable block size is to be selected by the programmer.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

97

Student Notebook

File Operations
Cobol Verbs Meaning

WRITE

Writes the records into file. Required while creating a new file and while Adding new records to an existing file. Rewrites on one or more existing fields of a file. Required while updating a file. Reads the records of a file and make them available to program Deletes the record from a file.

REWRITE

READ

DELETE

Notes: This foil lists the possible operations that can be performed over files. Before doing any operation, files should be opened and they must be closed before exiting the program OPEN and CLOSE verbs are provided by COBOL.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

98

Student Notebook

OPEN modes
Mode INPUT Stands for input mode. Only reading of records possible. Stands for output mode. Only writing new records possible. Stands for Input ---Output mode. All operations possible Stands for extend mode. Only for appending the records in sequential mode.

OUTPUT

I-O

EXTEND

Notes: SYNTAX OPEN Mode File-name1, File-name2. CLOSE File-name1, File-name2 While opening the file the mode must be specified depending on the operation to perform. More than one file can be opened and closed. Further, files can be opened and closed more than once in a program.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

99

Student Notebook

READ Sequential Access


When the READ statement is executed the file must already be open in INPUT or I-O mode The AT END clause must be before the NOT AT END Format 1: sequential retrieval
>>____READ__file-name-1___ _________________ __ __________ ___________________> |_ NEXT __________| |_RECORD__| |_ (1)| |_ PREVIOUS______| >_____ _______________________ ______________________________________________> |____ INTO___identifier-1____| >_____ ___________________________________ __________________________________> |_ ____ __END_imperative statement-1_| |_ AT _| >_____ ____________________________________________ ____ __________ _______>< |_ NOT___ ______ ___END_imperative-statement-2_| |_END-READ_|

Notes: For sequential access, the READ statement makes the next logical record from a file available to the object program. For random access, the READ statement makes a specified record from a direct-access file available to the object program. When the READ statement is executed, the associated file must be open in INPUT or I-O mode. NEXT RECORD Reads the next record in the logical sequence of records. NEXT is optional when ACCESS MODE IS SEQUENTIAL; PREVIOUS RECORD Reads the previous record in the logical sequence of records.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

100

Student Notebook

END OF FILE Processing


When the AT END condition occurs during sequential processing, the READ statement execution is unsuccessful. The contents of the record area are undefined The following actions take place when AT END occurs: The status indicator is posted. Control is transferred to the AT END phrase, if it is specified If AT END is not specified, then USE AFTER STANDARD ERROR could be specified and that procedure is executed. Then control is returned to the statement following the READ.

Notes:

Copyright Course materials may not be produced in whole or in part without the prior written permission.

101

Student Notebook

READ Random Access


Format 2: Random Retrieval
>>_____READ______file-name-1____ __________ ___ _______________ _____________> >____ _____________________________ ________________________________________> |_KEY_____ ___ __data-name-1__| |_TO_| >_____ _______________________________________________ ______________________> |_INVALID_____ ______ ____imperative-statement-3__| |_KEY __| >____ ___________________________________________ ___ ____________ _______>< |_NOT INVALID___ ___ __imperative-statement-4_| |_END-READ__| |_KEY_|

For VSAM INDEXED files, the KEY field contains a data value that will be matched against the key filed in the file records until the first record having an equal value is found. For VSAM RELATIVE files, the KEY phrase must not be specified.

Notes: Format 2 must be specified for indexed and relative files in random access mode, and also for files in the dynamic access mode when record retrieval is random. Execution of the READ statement depends on the file organization. Indexed Files Execution of a Format 2 READ statement causes the value of the key of reference to be compared with the value of the corresponding key data item in the file records, until the first record having an equal value is found. The file position indicator is positioned to this record, which is then made available. If no record can be so identified, an INVALID KEY condition exists, and READ statement execution is unsuccessful. If the KEY phrase is not specified, the prime RECORD KEY becomes the key of reference for this request. When dynamic access is specified, the prime RECORD KEY is also used as the key of reference for subsequent executions of sequential READ statements, until a different key of reference is established.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

102

Student Notebook

Relative Files Execution of a Format 2 READ statement sets the file position indicator pointer to the record whose relative record number is contained in the RELATIVE KEY data item, and makes that record available. The KEY phrase must not be specified for relative files.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

103

Student Notebook

READ Dynamic Access


For dynamic access, either sequential or random access possible, depending upon the format of the Read statement Dynamic access is allowed only for VSAM indexed or VSAM relative organizations. Dynamic access is established by ACCESS IS DYNAMIC in FILECONTROL SELECT statement The NEXT phrase must be specified for sequential access with dynamic mode. In order to READ NEXT, position must have been established in the file by a successful OPEN, START or READ statement

Notes:

Copyright Course materials may not be produced in whole or in part without the prior written permission.

104

Student Notebook

START Statement
Format :
>>___START___file-name-1___________________________________________________________> >__ _____________________________________________________________________ ________> |_KEY___ ______ ____ __EQUAL___ ___ ________________ _data-name-1____| |__TO _| | |_ TO_| | |_ = ______________________________| |_LESS__ _______ ________________| | |_THAN_| | |_GREATER__ ____ _____________| | |_THAN_| | |_NOT LESS___ _______ ___________| | |_THAN _| | |_NOT < ___________________________| |_NOT GREATER__ _______ ________| | |_THAN_| | |_NOT > ___________________________| |_LESS_ ____ _ OR EQUAL_ __ _____| | |THAN| |_TO_| | |_GREATER__ ____ _OR EQUAL_ __ _| | |_THAN_| \ TO| |_>+_______________________________| >__ _______________________________________ _____________________________________> |_INVALID___ _____ _imperative-statement-1_| |_KEY_| >__ _______________________________________ ___________ ____________ _____________> |_NOT INVALID___ _____ imperative-statement-1_| |_END-START_| |_KEY_|

Notes: The START statement provides a means of positioning within an indexed or relative file for subsequent sequential record retrieval. When the START statement is executed, the associated indexed or relative file must be open in either INPUT or I-O mode. file-name-1 Must name a file with sequential or dynamic access. File-name-1 must be defined in an FD entry in the Data Division, and must not name a sort file. END-START Phrase This explicit scope terminator delimits the scope of the START statement. ENDSTART converts a conditional START statement to an imperative statement so that it can be nested in another conditional statement. END-START can also be used with an imperative START statement.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

105

Student Notebook

WRITE Statement
The WRITE statement releases a logical record for an output or input/output file. When the WRITE statement is executed: - The associated sequential file must be open in OUTPUT or EXTEND mode. - The associated indexed or relative file must be open in OUTPUT, IO, or EXTEND mode. Record-name must be defined in a Data Division FD entry. Recordname can be qualified. It must not be associated with a sort or merge file.

Notes:

Copyright Course materials may not be produced in whole or in part without the prior written permission.

106

Student Notebook

WRITE.FROM
PROCEDURE DIVISION. WRITE File-rec FROM Identifier. File-rec is record-name declared in FILE-SECTION. Identifier is a working-storage section variable The length of the identifier should be equal to the length of the record.

Notes: To Create a file, program can accept the data from the terminal into file record and write it. If the data need to be processed, it can be accepted in a W-S identifier. After processing the data the above WRITE..FROM statement can be issued. Each WRITE statement writes one record at a time.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

107

Student Notebook

READ.INTO
PROCEDURE DIVISION. READ FILE-name (INTO W-S-Rec) | (AT END Statement) File name is defined in SELECT clause. W-S-Rec is working-Storage section identifier. INTO clause moves the file record to W-S-rec. AT END clause if used, indicates the next action after the last record is read.

OPEN INPUT Mode

Notes: READ statement on sequential files reads one record at a time and makes it available to program. Reading begins from first record and if the READ statement is put in a loop. That is executing the statement repeatedly, then it is possible to read consecutive records. Loop can be terminated before AT END condition is reached if required so by the program. If the file is left open next time when the read statement executes, reading continuous from where it was stopped before the termination of loop. If the file is closed then it is to be opened again before reading it.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

108

Student Notebook

REWRITE & DELETE


REWRITE record-name (FROM identifier) Updates an existing record from W-S identifier. OPEN I-O File-name DELETE record-name -----------------not allowed

Deleting of a record in sequential files not allowed.

Notes: It is often required to change the existing data and the process is called UPDATING. COBOL provides REWRITES verb to modify an existing record. For example, changing the address field of an employee requires reading of employee number. Every record to be updated needs to be read first. To search the record of an employee, whose employee number is known, the process is as follows Store the employee number in a variable Open the file Read first record Compare the variable with Emp-No field of the file If it matches update his address by REWRITE Else read next record his address by REWRITE Repeat the process until the require record is read.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

109

Student Notebook

Appending to sequential files


Adding new records to the existing file. OPEN EXTEND Mode WRITE records.

When new records to be added to file open the file in EXTEND mode EXTEND mode causes the pointer to move to the end of the file.

Notes:

Copyright Course materials may not be produced in whole or in part without the prior written permission.

110

Student Notebook

CLOSE Statement
Format : CLOSE File-name-1, [File-name-2 .]

CLOSE Statement Releases the Resourcces which are assigned to that file. Cannot Close the file which is not opened. After performing the operations on the file (I,e no longer used in a program) needs to be closed but not necessary. If the FILE STATUS clause is specified in the FILE-CONTROL entry, the associated status key is updated when the CLOSE statement is executed. If the file is in an open status and the execution of a CLOSE statement is unsuccessful, the EXCEPTION/ERROR procedure (if specified) for this file is executed.

Notes:

Copyright Course materials may not be produced in whole or in part without the prior written permission.

111

Student Notebook

Sequential Files
ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL SELECT file-name ASSIGN TO DEVICE-NAME ORGANIZATION IS SEQUENTIAL. ACCESS MODE IS SEQUENTIAL. FILE STATUS IS data-name.

Area B

Notes: All the files used in the program should have an entry in FILE CONTROL paragraph. For each file used, there should be one SELECT..ASSIGN clause. The file-name is select clause is user defined word and can be used throughout the program wherever required. ASSIGN clause specifies the device on which file stored.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

112

Student Notebook

EXAMPLE: SEQUENTIAL FILE


IDENTIFICATION DIVISION. PROGRAM-ID. SEQFILE. ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT SEQ-FILE ASSIGN TO DD-NM1 ORGANIZATION IS SEQUENTIAL. SELECT OUT-FILE ASSIGN TO DD-NM2 ORGANIZATION IS SEQUENTIAL. DATA DIVISION. FILE SECTION. FD SEQ-FILE. 01 SEQ-REC. 02 NO PIC X(3). 02 NAME PIC X(15). 02 ADDR PIC X(10). FD OUT-FILE. 01 OUT-REC PIC X(28). WORKING-STORAGE SECTION. 01 EOF PIC X. PROCEDURE DIVISION. MAIN-PARA. OPEN INPUT SEQ-FILE OUTPUT OUT-FILE. READ SEQ-FILE INTO OUT-REC AT END MOVE Y TO EOF. PERFORM READ-PARA UNTIL EOF=Y. CLOSE SEQ-FILE OUT-FILE. STOP RUN. READ-PARA. WRITE OUT-REC. READ SEQ-FILE INTO OUT-REC AT END MOVE Y TO EOF.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

113

Student Notebook

Indexed Files
Index component consists of a index structure with a record key values and addresses of corresponding records. RECORD KEY is one or more fields of the records. Suitable record key is to be chosen by the programmer depending on the functionality of the fields.

E.g :

Employee-code, Job-number.

ALTERNATE RECORD KEY can also be chosen. E.g : Employee-name, Job-name.

Indexed files facilitate faster accessing of records compared to that of sequential files.

Notes: When an indexed file is created An index component is also created containing some index tables based on record keys. A data component is created containing the actual records. Record keys identify every record in the file. The process of accessing a record involves searching for the record key with matching index value. Then locate the record from the corresponding address. This is done by the system itself.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

114

Student Notebook

INVALID KEY
(READ | WRITE | REWRITE | DELETE) File-name (INVALID KEY Statement) (AT END Statement). Records and indexes of an indexed file are stored in key sequence order to facilitate faster access. Invalid key clause checks whether any input-output operation is violating the Uniqueness of primary keys
E.g. add a record with duplicate value.

Sequence of the records.


E.g. add a record with key value out of range.

Proper read
E.g. try to read a non-exist record

Reading of a record in indexed files required the key value to be provided by the program

Notes:

Copyright Course materials may not be produced in whole or in part without the prior written permission.

115

Student Notebook

ACCESS MODE: SEQUENTIAL & RANDOM


ACCESS MODE SEQUENTIAL READ File-name NEXT RECORD to read sequentially. DELETE statement should not contain invalid key AT END clause is required.

ACCESS MODE RANDOM READ File-name INVALID KEY statement AT END clause not required.

Notes: When READ NEXT statement is to be executed each time the records are read consecutively. IF the access mode is RANDOM a record is read from corresponding key value.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

116

Student Notebook

ACCESS MODE: DYNAMIC


ACCESS MODE DYNAMIC START file-name key (NOT | LESS THAN | GREATER THAN| LESS THAN ) identifier INVALID KEY statement READ file-name NEXT RECORD AT END statement.

Notes: In a situation demanding the access of more than one consecutive records from the middle of the file then dynamic access is used. The START verb places the read pointer to the record whose key value is compared with an identifier. Record is accessed randomly. READNEXT can be put into loop for sequential reading. For the Rewrite/ Delete operations the records must be read at first.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

117

Student Notebook

EXAMPLE: INDEXED FILE


IDENTIFICATION DIVISION. PROGRAM-ID. SEQFILE. ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT IND-FILE ASSIGN TO DD-NM1 ORGANIZATION IS INDEXED ACCESS MODE IS DYNAMIC RECORD KEY IS NO. SELECT OUT-FILE ASSIGN TO DD-NM2 ORGANIZATION IS INDEXED ACCESS MODE IS DYNAMIC. RECORD KEY IS NO. DATA DIVISION. FILE SECTION. FD IND-FILE. 01 IND-REC. 02 NO PIC X(3). 02 NAME PIC X(15). 02 ADDR PIC X(10). FD OUT-FILE. 01 OUT-REC. 02 NO PIC X(3). 02 NAME PIC X(15). 02 ADDR PIC X(10). WORKING-STORAGE SECTION. 01 VAL PIC X(3). PROCEDURE DIVISION. MAIN-PARA. OPEN INPUT IND-FILE OUTPUT OUT-FILE. MOVE 001 TO VAL. READ IND-FILE RECORD KEY VAL INTO OUT-REC INVALID KEY GO TO ERR-PARA. WRITE OUT-REC. PERFORM EXIT-PARA. ERR-PARA. DISPLAY KEY NOT FOUND. PERFORM EXIT-PARA. EXIT-PARA. CLOSE IND-FILE OUT-FILE. STOP RUN.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

118

Student Notebook

Relative Files
FILE CONTROL SELECT file-name ASSIGN TO Disk ORGANIZATION IS RELATIVE RELATIVE KEY data-name-1 RRN indicates the offset of a record from the first record of the file.

Notes: In relative file Relative Record Number identifies the records of the file. Select clause should specify RELATIVE KEY. Value of data-name-1 indicates RRN. Usage of READ/WRITE/ REWRITE/ DELETE statements, ACCESS modes, OPEN modes and START verb, are exactly similar to that for sequential files.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

119

Student Notebook

Open modes File Organization Sequential


S E Q U E N T I A L

Relative

Indexed

A C C E S S

OPERATIONS I READ X WRITE REWRITE START DELETE READ WRITE REWRITE START DELETE READ WRITE REWRITE START DELETE

O X

I-O X X

E I X X X

O X

I-O X X X X X X X X

I X

O X

I-O X X X X X X X X

R A N D O M

X X

X X

M O D E

D Y N A M I C

X X X

X X X X X

X X X

X X X X X

Copyright Course materials may not be produced in whole or in part without the prior written permission.

120

Student Notebook

UNIT 5

TABLE HANDLING

Copyright Course materials may not be produced in whole or in part without the prior written permission.

121

Student Notebook

Introduction : Table Handling


Consider a situation of accepting 100 numbers from the user , display all. The numbers in sorted order.

Types of tables One dimensional table Two dimensional table Multidimensional table

Table is a list of logically similar items.

Notes: Obviously declaring 100 data items in W-S section and sorting them becomes practically impossible. Tables or Arrays provide the solution to handle situations discussed above. If volume of data to be processed is large and if they are not stored in files, then tables are used.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

122

Student Notebook

OCCURS Clause
Specifies number of occurrences or elements of the table.
WORKING-STORAGE SECTION 01 Marks. 02 Mark Table1 OCCURS 10 TIMES PIC 9(2). Valid 02 Mark Table2 PIC 9(2) OCCURS 10 TIMES Valid 02 Mark Table3 PIC 9(2) OCCURS 10TIMES VALUE Invalid

Notes: OCCURS clause causes setting up of area for holding the table elements. Following rules must be followed with the usage of OCCURS clause. 1. The Integer must be positive. 2. Clause cannot be specified for an item whose level is 01, 66, 77, 88. 3. Value clause should not be specified with occurs clause. 4. OCCURS clause can be specified for file-section entries for both group items as well as elementary items.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

123

Student Notebook

Subscript
Indicates the position of an element in the table.
PROCEDURE DIVISION Marks Table (Subscript) Marks Table (I) Marks Table (5) Marks Table (12) Parentheses required

Valid provided I declared in data division. Valid. Invalid.

Notes: Subscript can be a COBOL variable or a literal. Value of subscript must not exceed the range of no. of occurrences specified by OCCURS clause. If OCCURS clause is specified for a group items subscript should be specified for all elementary items of that group. Subscript should be specified for only data items defined with OCCURS clause, whenever used in procedure division.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

124

Student Notebook

INDEXING
An index-name is an identifier that becomes associated with a particular table. The value in an index is the displacement from the beginning of the table based upon the length of the table element. An index-name may appear on an OCCURS clause, e.g. 01 02 TABLE-OF-MONTHS. MONTHS PIC OCCURS X(10) 12 TIMES.

INDEXED BY NDX.

The index-name is created by the compiler; it does not have to be defined elsewhere in the program. The contents of an index may be changed by the SET TO statement An index may not be used in a MOVE statement or an INITIALIZE statement.
Notes: Indexing allows such operations as table searching and manipulating specific items. To use indexing you associate one or more index-names with an item whose data description entry contains an OCCURS clause. An index associated with an index-name acts as a subscript, and its value corresponds to an occurrence number for the item to which the index-name is associated. The INDEXED BY phrase, by which the index-name is identified and associated with its table, is an optional part of the OCCURS clause. There is no separate entry to describe the index associated with index-name. At run time, the contents of the index corresponds to an occurrence number for that specific dimension of the table with which the index is associated.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

125

Student Notebook

One Dimensional Tables


Specified by one subscript or index Example: 01 ABC. 02 XYZ PIC X(10) OCCURS 10 TIMES.

XYZ(1)

WHERE 1 Specifies the first element of XYZ.

Notes:

Copyright Course materials may not be produced in whole or in part without the prior written permission.

126

Student Notebook

Two Dimensional Tables


Specified by two subscripts or indexes. 5th Subject of 3rd Student. 5th Marks of 3rd Student.

Student (3 5) Marks (3 5)

= =

If it requires storing the Marks of N subject for M students then we require two OCCURS clauses.

Notes: Two dimension tables are used most frequently in applications. Consider for examples, 10 Students of a class appeared for 8 subjects in their annual exams and you need to code a program to store and retrieve the data. Data includes names of all the students, marks and names of corresponding subjects. To store the marks of n subjects of one student, one dimension table serves the purpose. If number of students is more than one than for each student there OCCURS n subjects and marks. Next foil shows the W-S declarations for this example.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

127

Student Notebook

Multidimensional Table
Each OCCURS clause adds a dimension in nested occurs. Ex: 01 Multidimensional. 02 First-dim 02 Second-dim 05 Second 05 Third-dim 10 Third

OCCURS 10 TIMES OCCURS 5 TIMES. PIC A. OCCURS 10 TIMES PIC 5.

PIC X.

Notes: COBOL supports multidimensional tables up to 7 levels.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

128

Student Notebook

Table-Sorting
Use Sorting techniques to sort a table. E.g Bubble sort PERFORM VARYING I FROM 1 BY 1 UNTIL I = N PERFORM J FROM I BY 1 UNTIL J > N IF A[I] > A[J] MOVE A[I] TO TEMP MOVE A[J] TO A[I] MOVE TEMP TO A[J] END-IF END-PERFORM END-PERFORM. I and J are used as subscripts for comparing elements of the table.

Notes: Sorting is the process of arranging the elements of table in order. Searching for a particular element of the sorted table, requires less time when compared to searching from an unsorted table. SORT verb available in COBOL is limited to File sorting.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

129

Student Notebook

SET Verb
SET verb initializes and / or changes the value of index. E.g. : SET K To 1 SET K UP BY 2 SET K DOWN BY 2 K is initialized to 1 Value increment by step of 2. Decrements by step of 2

MOVE verb cannot be used for index. E.g. : SET data-name-1, data-name-2 TO K SET verb moves of value of K to data-name-1 and data-name-2.

Notes: Even though indexes assume the displacement values for table elements internally, programmer sets the value of an index by specifying the position of an element. This means an index indicates the position of an element in the table similar to subscript, but internally it is processed in a different manner, but more efficient.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

130

Student Notebook

SEARCH Verb
Searches for a particular value in the table, which has an index. SEARCH Table name AT END statement WHEN condition statement Ex : SET K TO 1 SEARCH table-name AT END DISPLAY not found. WHEN field-1 = element (K) DISPLAY element (K).

Notes: In the above example, field-1 contains the required value to be searched for in the table, More than one condition can be checked, with more than one WHEN clause. All valid arithmetic operators can be used. This form of search statement is called serial search.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

131

Student Notebook

Binary Search
Searches the table previously sorted, by splitting the table. Faster than serial search Only one WHEN clause is allowed. SEARCH ALL Table-Name . WHEN . other clauses remain same.

Notes: Before applying SEARCH ALL clause the table must be sorted. SEARCH ALL causes the table to split into two halves. Then it determines which half of the table contains the required value by comparing it to the last element of the first half and first element of the second half. Again the selected half-table splits and continues and so on until the value is located.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

132

Student Notebook

ILLUSTRATES ONE-DIMENSIONAL ARRAYS


DATA DIVISION. WORKING STORAGE SECTION. 77 CT PIC 99 VALUE 0. 01 TAX-RATE. 05 RATE PIC 999 OCCURS 5 TIMES. * There should be a space before and after the braces. 01 MONTH-TABLE. 02 FILLER PIC X(9) VALUE January. 02 FILLER PIC X(9) VALUE February. 02 FILLER PIC X(9) VALUE March: 02 FILLER PIC X(9) VALUE April. 02 FILLER PIC X(9) VALUE May. 02 FILLER PIC X(9) VALUE June. 02 FILLER PIC X(9) VALUE July. 02 FILLER PIC X(9) VALUE August. 02 FILLER PIC X(9) VALUE September. 02 FILLER PIC X(9) VALUE October. 02 FILLER PIC X(9) VALUE November. 02 FILLER PIC X(9) VALUE December. 01 MONTH-NAME REDEFINES MONTH-TABLE. 02 MONTH PIC X(9) OCCURS 12 TIMES. PROCEDURE DIVISION. 100-MAIN-PARA. PERFORM 200-FILL-PARA VARYING CT FROM 1 BY 1. UNTIL CT>5. PERFORM 300-DISP-PARA VARYING CT FROM 1 BY 1. UNTIL CT>5. PERFORM 400-MNTH-PARA. STOP RUN. 200-FILL-PARA. COMPUTE RATE ( CT ) = CT*100. 300-DISP-PARA. DISPLAY RATE ( CT ). 400-MNTH-PARA. DISPLAY Month as a number ? ACCEPT CT. IF CT< 1 OR > 12 DISPLAY Error in number ELSE DISPLAY MONTH ( CT ).

Copyright Course materials may not be produced in whole or in part without the prior written permission.

133

Student Notebook

ILLUSTRATES SEARCH VERB


DATA DIVISION. 01 MONTH-TABLE. 02 FILLER PIC X(9) VALUE January. 02 FILLER PIC X(9) VALUE February. 02 FILLER PIC X(9) VALUE March: 02 FILLER PIC X(9) VALUE April. 02 FILLER PIC X(9) VALUE May. 02 FILLER PIC X(9) VALUE June. 02 FILLER PIC X(9) VALUE July. 02 FILLER PIC X(9) VALUE August. 02 FILLER PIC X(9) VALUE September. 02 FILLER PIC X(9) VALUE October. 02 FILLER PIC X(9) VALUE November. 02 FILLER PIC X(9) VALUE December. 01 MONTH-NAME REDEFINES MONTH-TABLE. 02 MONTH OCCURS 12 TIMES INDEXED BY CT. 05 FIRST-THREE PIC X (3). 05 BALANCE-REST PIC X (6). 77 M-NAME PIC X (9) VALUE SPACES. PROCEDURE DIVISION. MAIN PARA. DISPLAY Months Name please. ACCEPT M-NAME. SET CT TO 1. SEARCH MONTH AT END DISPLAY Not Found. WHEN M-NAME = MONTH ( CT ). DISPLAY FIRST-THREE ( CT ). STOP RUN.

ILLUSTRATE TWO-DIMENSIONAL ARRAYS


Copyright Course materials may not be produced in whole or in part without the prior written permission. 134

Student Notebook

DATA DIVISION WORKING-STORAGE SECTION. 01 WORK-AREA 05 MORE DATA PIC A VALUE Y. 88 NO-MORE-DATA VALUE N. 01 TEMPERATURE-ARRAY. 05 DAY-IN-THE-WEEK OCCURS 24 TIMES. 10 HOURS-IN-THE-DAY OCCURS 24 TIMES. 15 DEGREE-TEMP PIC S9(3). 77 DAY-OF-THE-WEEK PIC 9. 77 TIME-OF-THE-DAY PIC 99. 77 HOUR-COUNT PIC 99. 77 DAY-COUNT PIC 9. 77 TOT-TEMP PIC S999. 77 AVERAGE-TEMP PIC S999. PROCEDURE DIVISION. 100-MAIN-PARA. PERFORM 200-DATA-ACCP-RTN UNTIL NO-MORE-DATA. PERFORM 300-DATA-DISP-RTN. STOP RUN. 200-DATA-ACCP-RTN. DISPLAY Day of the Week : 1-Sunday.7-Saturday : ACCEPT DAY-OF-THE-WEEK. DISPLAY Time of the Day during Data Collection : ACCEPT TIME-OF-THE- WEEK. DISPLAY Temperature ACCEPT DEGREE-TEMP (DAY-OF-THE-WEEK, TIME-OF-THEDAY). DISPLAY Anymore (Y/N): ACCEPT MORE-DATA. 300-DATA-DISP-RTN. PERFORM VARYING DAY-COUNT FROM 1 BY 1 UNTIL DAY-COUNT > 7. PERFORM VARYING DAY-COUNT FROM 1 BY 1 UNTIL HOUR-COUNT > 24. DISPLAY DAY : , DAY-COUNT, HOUR: , HOUR-COUNT, TEMP : , DEGREE-TEMP ( DAY-COUNT, HOUR-COUNT ) ADD DEGREE-TEMP ( DAY-COUNT, HOUR-COUNT ) TO TOT-TEMP. COMPUTE AVERAGE-TEMP = TOT-TEMP / 168. DISPLAY Weeks Average Temperature Is : , AVERAGE-TEMP.
Copyright Course materials may not be produced in whole or in part without the prior written permission. 135

Student Notebook

ILLUSTRATES MULTIPLE INDEXES AND 3D ARRAYS


DATA DIVISION. WORKING-STORAGE SECTION. 01 ENROLL-TABLE. 02 FACULTY OCCURS 3 TIMES INDEXED BY F1, F2. 03 DEPARTMENT OCCURS 6 TIMES INDEXED BY D1, D2. 04 YEAR OCCURS 5 TIMES INDEXED BY Y1, Y2. 05 FAC PIC X (15). 05 DEPT PIC X (10). 05 YY PIC 9 (4). 77 ANYMORE PIC A VALUE Y. PROCEDURE DIVISION. 100-MAIN-PARA. SET F1, D1, F2, D2, Y2 TO 1. PERFORM 200-ACC-PARA UNTIL SNYMORE = N. DISPLAY THE CONTENTS OF 3 DIMENSIONSAL ARRAY ARE : PERFORM VARYING R2 FROM 1 BY 1 UNTIL F2 > F1 AFTER D2 FROM 1 BY 1 UNTIL D2 > D1. AFTER Y2 FROM 1 BY 1 UNTIL Y2 > Y1 DISPLAY RAC (F2, D2, Y2) DISPLAY DEPT (F2, D2, Y2) DISPLAY YY (F2, D2, Y2). STOP RUN. 200-ACC-PARA. DISPLAY ENTER FACULTY NAME. ACCEPT FAC (F1, D1, Y1). DISPLAY ENTER DEPARTMENT NAME:. ACCEPT DEPT (F1, D1, Y1). DISPLAY ENTER YEAR. ACCEPT YY (F1, D1, Y1). IF Y1 = 5 IF D1 = 6 IF F1 = 3 MOVE N TO ANYMORE ELSE SET F1 UP BY 1 END-IF ELSE
Copyright Course materials may not be produced in whole or in part without the prior written permission. 136

Student Notebook

SET D1 UP BY 1 END-IF ELSE SET Y1 UP BY 1. DISPLAY ANYMORE. ACCEPT ANYMORE

Copyright Course materials may not be produced in whole or in part without the prior written permission.

137

UNIT 6

Library Services

Copyright Course materials may not be produced in whole or in part without the prior written permission.

138

COPY Statement
The COPY statement is a library statement that places prewritten text in a COBOL program Each COPY must be terminated by a period If library-name is omitted, then SYSLIB is assumed

Format:
>>____COPY____ ____________________> |_ _____text-name___ literal __| _____ _________________________

|_ _OF _ ____ library-name_ ___| |_IN_| |_ literal 2_______|

>____ ____________ _____ ________________________________________________ ___ ______>< |_SUPPRESS__| | <______________________________ _| |__REPLACING_______operand-1___BY__operand-2___|_|

Notes: SUPRRESS means that the imbedded text will not be printed in the source program listing COPY requires the LIB compiler option to be in effect The COPY statement is a library statement that places prewritten text in a COBOL program. Prewritten source program entries can be included in a source program at compile time. Thus, an installation can use standard file descriptions, record descriptions, or procedures without recording them. These entries and procedures can then be saved in user-created libraries; they can then be included in the source program by means of the COPY statement.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

139

Compilation of the source program containing COPY statements is logically equivalent to processing all COPY statements before processing the resulting source program. The effect of processing a COPY statement is that the library text associated with text-name is copied into the source program, logically replacing the entire COPY statement, beginning with the word COPY and ending with the period, inclusive. When the REPLACING phrase is not specified, the library text is copied unchanged. Each COPY statement must be preceded by a space and ended with a separator period. Debugging lines are permitted within library text and pseudo-text. Comment lines or blank lines can occur in library text. Comment lines or blank lines appearing in library text are copied into the resultant source program unchanged with the following exception: a command line or blank line in library text is not copied if that comment line or blank line appears within the sequence of text words that match operand-1 A COPY statement can appear in the source program anywhere a character string or a separator can appear; however, a COPY statement must not be specified within a COPY statement. The resulting copied text must not contain a COPY statement.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

140

Nested COPY
COPY FILEA. FILEA contains: 01 FILEA. 05 NAME PIC X(40). COPY ADDRESS. 05 DATA PIC X(100). ADDRESS contains: 05 STREET PIC X(40). 05 CITY PIC X(20). 05 STATE PIC X(02). 05 ZIP PIC X(09).

Compile produces: 01 FILEA. 05 NAME PIC X(40). 05 STREET PIC X(40). 05 CITY PIC X(20). 05 STATE PIC X(02). 05 ZIP PIC X(09). 05 DATA PIC X(100).
Notes: COBOL allows nested COPY statements. Nested COPY statements cannot contain the REPLACING phrase. A COPY statement can appear in the source program anywhere a character string or a separator can appear. As an IBM extension, COPY statements can be nested. However, nested COPY statements cannot contain the REPLACING phrase, and a COPY statement with the REPLACING phrase cannot contain nested COPY statements. A COPY statement cannot cause recursion. That is, a COPY member can be named only once in a set of nested COPY statements until the end-of-file for that COPY member is reached.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

141

COPY REPLACING
To change some, or all, of the names in the library (COPYed) text, the programmer can use the REPLACING option. The text in the library is unchanged. COPY PAYLIB REPLACING FLDA BY PAY-RECORD FLDA BY HRLY-RATE FLDA BY HRS-WORKD. LIBRARY TEXT 01 FLDA. 02 FLDB PIC 999V99. 02 FLDC PIC 999V99. SOURCE PROGRAM 01 PAY-RECORD. 02 HRLY-RATE PIC 999V99. 02 HRS-WORKD PIC 999V99.

In the discussion that follows, each operand can consist of one of the following: Pseudo-text An identifier A literal A COBOL word Function identifier

Copyright Course materials may not be produced in whole or in part without the prior written permission.

142

COPY Pseudo-Text
To change only part of the data-name(s) in the library text, the programmer can use the REPLACING option with the standard pseudo-text delimiters (==) COPY PAYLIB REPLACING = = : PFFX: = = LIBRAR TEXT 01 :PFFX:. 02 :PFFX:-RTE PIC 999V99. 02 :PFFX: - HRS PIC 999V99.

BY

= = PAY = =.

SOURCE PROGRAM 01 PAY. 02 PAY-RTE PIC 999V99. 02 PAY-HRS PIC 999V99.

Notes : Pseudo-text A sequence of character-strings and/or separators bounded by, but not including, pseudo-text-1 delimiters (= =). Both characters of each pseudo-text-1 delimiter must appear on one line; however, character-strings within pseudo-text-1 can be continued. Any individual character-string within pseudo-text-1 can be up to 322 characters long. Pseudo-text-1 cannot be null, nor can it consist solely of the space character, separator comma, separator semicolon, and/or of comment lines. Beginning and ending blanks are not included in the text comparison process. Embedded blanks are used in the text comparison process to indicate multiple text words. Pseudo-text must not contain the word COPY.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

143

REPLACE Pseudo-test
Replace can be applied to the entire program, including text introduced through COPY members Replace action starts at a the REPLACE statement and continues until: - Another REPLACE statement - REPLACE OFF statement - End of source program REPLACE statements are processed by the compiler after any COPY statements are processed

Copyright Course materials may not be produced in whole or in part without the prior written permission.

144

UNIT 7

CHARACTER HANDLING

Copyright Course materials may not be produced in whole or in part without the prior written permission.

145

STRING
Two or more fields can be concatenated or string in to single-field. STRING DELIMITED BY DELIMITED BY INTO id 7 (id- 1 | literal ), (id-2 | literal ) (id- 3 | literal | size |space),.. (id- 4 | literal ) (id- 4 | literal ), (id 5 | literal ) (with pointer id- 6 ). (ON OVERFLOW statement)

Notes:
Delimited by clause specifies how the fields are concatenated, Its usage is described in following foils. With pointer option if used gives the total no. of characters in the concatenated field (id7) If the length of id-7 is not enough to hold the transferred characters, the statement after on overflow option is executed. One STRING statement can be written instead of a series of MOVE statements. The following rules should be followed when this verb is used. (i). This statement is used to concatenate one or more strings into one by placing them side by side. (ii). Sending strings may be alphanumeric literals, figurative constants or identifiers with usage DISPLAY. (iii). The receiving string, i.e., identifier- 7 must also be with usage DISPLAY.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

146

STRING example :
77 77 77 77 77 id-1 PIC X(7) VALUE Con, Con. id-2 PIC X(7) VALUE Cat, Cat. id-3 PIC X(6) VALUE enated. id-4 PIC X(12) VALUE Spaces. counter PIC 9 (3) VALUE zeros.

STRING id-1, id-2, id-3. DELIMITED BY id-2, id-3, into id-4. WITH POINTER Counter.

RESULT
Content if id-4: CONCATENATED. The following example shows usage of size option. 77 F 1 PIC X(7) VALUE HIGHTEC 77 F 2 PIC X(7) VALUE SPACES. STRING MAIN DELIMITED BY SIZE F 1 INTO F 2. Guess the result.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

147

ILLUSTRATES STRING VERB


DATA DIVISION. WORKING STORAGE-SECTION. 01 FULL-NAME PIC X(30). 01 FIRST-NAME PIC X(10) 01 MIDDLE-NAME PIC X (10) 01 LAST-NAME PIC X (10) PROCEDURE DIVISION. 100-MAIN-PARA. MOVE RAJA TO FIRST-NAME. MOVE ROMOHAN TO MIDDLE-NAME. MOVE ROY TO LAST-NAME. STRING FIRST-NAME,MIDDLE-NAME,LAST-NAME DELIMITTED BY SPACE INTO FULL-NAME.

VALUE SPACES. VALUE SPACES. VALUE SPACES.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

148

UNSTRING Statement
The UNSTRING statement is used to split a single data item into several data items Format:
>>__UNSTRING___identifier1___________________________________________________________> >__ _____________________________________________________________________________ ___> |_DELIMITED___ _____ ___ _____ ___ __identifier-2__ ____ __________________________| |_BY_| |_ALL_| |_literal-1______| | <_____________________ | |__OR_ ____ __ identifier-3_ _| | |_ALL_| |_literal-2__| >___INTO____________________________________________________________________________> <____________________________________________________________________________ >____identifier-4__ _____________________________ ____ ___________________________ __| __> |_DELIMITER__ ___ identifier-5 _| |_COUNT__ ____ identifier-6___| |_IN_| |_IN__| >___ ___________________________ ____ _______________________________ ______________> |_ ____ _POINTER__identifier-7_| |_TALLYING___ ____ __identifier-8_| |_WITH_| |_IN_| >__ _____________________________________________ _________________________________> |_ _____ ___OVERFLOW__imperative-statement-1___| |_WITH_| >___ __________________________________________________ ___ _________________ _______> |_ NOT__ _____ __OVERFLOW__imperative-statement_2_| |_END-UNSTRING_| |_ON_|

Notes:
The UNSTRING statement causes contiguous data in a sending field to be separated and placed into multiple receiving fields. One UNSTRING statement can take the place of a series of MOVE statements, except that evaluation or calculation of certain elements is performed only once, at the beginning of the execution of the UNSTRING statement. When the TALLYING phrase is specified, the field-count field contains a value equal to the initial value, plus the number of data receiving areas acted upon.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

149

ILLUSTRATES UNSTRING VERB


DATA DIVISION. WORKING STORAGE-SECTION. 01 FULL-NAME PIC X(30). 01 FIRST-NAME PIC X(10) 01 MIDDLE-NAME PIC X (10) 01 LAST-NAME PIC X (10) PROCEDURE DIVISION. 100-MAIN-PARA. MOVE RAJA ROMOHAN ROY TO FULL-NAME. UNSTRING FULL-NAME DELIMITTED BY SPACE INTO FIRST-NAME, MIDDLE-NAME,LAST-NAME.

VALUE SPACES. VALUE SPACES. VALUE SPACES.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

150

EXAMINE Statement
EXAMINE Identifier TALLYINY ALL LEADING UNTIL FIRST Literal - 1

EXAMINE Literal - 3

Identifier REPLACING

ALL LEADING UNTIL FIRST

Literal - 2 BY

EXAMINE

Identifier TALLYINY

ALL LEADING UNTIL FIRST

Literal - 4

REPLACING BY Literal - 5

Notes:
This verb is used to scan a string to find the number of occurences of a given character in it. In addition, the Verb can also be use to replace some or all occurrences of the said character by another character. Eg : Let us consider the following DATA DIVISION entry 77 A PIC X(5) VALUE IS PPRIP. Now the statement EXAMINE A TALLYING ALL P. Will store 3 in the TALLY register as there are altogether three Ps in the string. However the statement EXAMINE A TALLYING LEADING P Will store 2 in the TALLY , Since there are only Two leading Ps. The statement EXAMINE A TALLYING UNTIL FIRST I. Will store 3 in the TALLY as there are only Three characters before the character I. It may be noted here that if a particular character is not found, TALLY is set to Zero, When the ALL or LEADING phrase is used. For eg. In the statement
Copyright Course materials may not be produced in whole or in part without the prior written permission. 151

EXAMINE A TALLYING LEADING R Will set TALLY to zero, Since the leading charcter is not R. If the UNTIL FIRST phrase is used and the specified character is not found, the TALLY will contain the size of the string EXAMINE---REPLACING. EXAMINE A TALLYING ALL P REPLACING BY Q Will store 3 in the TALLY register and will change the content of A to QQRIQ. EXAMINE A REPLACING FIRST I BY M Will change the content of A to PPRMP. EXAMINE A REPLACING UNTIL FIRST I BY Y Will change the content of A to YYYIP. In each of the cases A is assumed to be defined as before.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

152

INSPECT TALLYING Statement


The INSPECT statement specifies that characters, or groups of characters, in a data item are to be counted (tallied) or replaced or both. It will count the occurrence of a specific character (alphabetic,numeric, or special character) in a data item. It will fill all or portions of a data item with specified characters, such as spaces or zeros. It will convert all occurrences of specific characters in a data item to usersupplied replacement characters. Format:
>>___INSPECT___identifier1______TALLYING____________________________________________________> <_______________________________________________________ | >____identifier-2___FOR____ __CHARACTERS____ ____________ _| _____________________ __ | __|_____> | |_|phrase 1 |__| | | <_______________________ | | |__ __ALL _________ ___ __identifier-3___ __ ___________ _| _| _| |_LEADING______| |_literal________| |_ | phrase 1 _| >_____REPLACING_____________________________________________________________________ _______> >_______ __CHARACTER BY____ _identifier-5__ ______ _______________ __|__________________ __|____> | |_literal-3____| |__| phrase |_| | | <_______________________________________________________ | <________________ | | |__ ALL_____ ______ ___identifier-3___ ___BY__ _identifier-5__ ____ ______________| _| _| |_LEADING_| |_literal-1________| |_literal-3____| |_| phrase 1 |__| phrase 1: |__ __BEFORE__ __ _____________ 4__________________________________________________| |_AFTER___| |_INITIAL_____| |_literal-2__| Copyright Course materials may not be produced in whole or in part without the prior written permission.

__

_identifier-

153

Notes:
TALLING Phrase counts the occurrence of a specific character (alphabetic, numeric, or special character) in a data item. Identifier-1: Identifier-1 is the inspected item and can be any of the following: An alphanumeric data item An numeric data item with USAGE DISPLAY An external floating point item Identifier-2 Is the count field, and must be an elementary integer item defined without the symbol P in its PICTURE character-string You must initialize identifier-2 before execution of the INSPECT statement begins. Identifier-3 or literal-1 Is the tallying field (the item whose occurrences will be tallied). Eg: PROCEDURE DIVISION. INSPECT HELLO TALLYING TALLY-COUNT FOR ALL A Let the picture of HELLO be X(20) and suppose its content before the execution of the above statement is as follows : APARNAbKUMARIbAMMAbb If picture of TALLY-COUNT is 9(2) and originally contains 08, then after the execution of the statement, TALLY-COUNT will contain 14, as there are a total of 6 As in HELLO. If ALL in the statement is changed to LEADING , TALLY-COUNT will be increased to 9, as there is only one leading A. if CHARACTERS is specified instead of ALL A, TALLY-COUNT will be increased to 28 as there are a total of 20 characters in HE LLO.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

154

INSPECT REPLACING Statement


This phrase fills all or portions of a data item with specified characters, such as spaces or Zeros. When REPLACING CHARACTERS is used the identifier-5 must be 1 character in length Format:
>>___INSPECT___identifier1___REPLACING______________________________________________>

<___________________________________________________________________________

>_______ __CHARACTERS BY___ __identifier-5__ ____ ___________ ___ | ____________ __| ___> | |_literal-3______| |_| phrase 2 |_| | | <__________________________________________________ | | <_____________ | | |_ ALL_____ _______ identifier-3_ ___BY__ __identifier-5__ _ _________ _| _| _| |_LEADING_| |_literal-1___| |_literal-3______| |_| phrase 1 |_| phrase 1: |___ BEFORE_ __ ________ ________________________________________________| |_AFTER_| |_INITIAL_| |_literal-2___|

__

identifier-4_

INSPECT DATA1 REPLACING ALL BY 0 INSPECT DATA2 REPLACING FIRST ZERO BY SPACE INSPECT DATA3 REPLACING CHARACTER ZERO BY X INSPECT DATA4 REPLACING LEADING 0 BY SPACE

Copyright Course materials may not be produced in whole or in part without the prior written permission.

155

REPLACING Phrase -identifier-3 or literal-1 Is the subject field (the item whose occurrences are replaced). Identifier-3 can be: An elementary alphanumeric data item A numeric data item with USAGE DISPLAY An external floating point item Literal-1 must be non-numeric, and can be any figurative constant that does not begin with the word ALL. If literal-1 is a figurative constant, it is considered to be a 1-character nonnumeric literal. Identifier-5 or literal-3 Is the substitution field Identifier-5 can be: An elementary alphanumeric data item A numeric data item with USAGE DISPLAY An external floating point item Literal-3 must be nonnumeric, and can be any figurative constant that does not begin with the word ALL. The following replacement rules apply: When the subject field is a figurative constant, the single-character substitution field(which must be 1 character in length) replaces each character in the inspected item equivalent to the figurative constant. When the substitution field is a figurative constant, the substitution field replaces each non-overlapping occurrence of the subject field in the inspected item. When the subject and substitution fields are character-strings, the character-string specified in the substitution field replaces each non-overlapping occurrence of the subject field in the inspected item

Copyright Course materials may not be produced in whole or in part without the prior written permission.

156

UNIT 8

SORT / MERGE

Copyright Course materials may not be produced in whole or in part without the prior written permission.

157

SORT/MERGE
SORT Statement MERGE Statement SORT PROCEDURES RELEASE/RETURN Statements

Copyright Course materials may not be produced in whole or in part without the prior written permission.

158

SORT Statement
The SORT statement accepts records, sorts them according to specified keys, and makes the sorted results available for further processing. Format 1: SORT file-name-1 ON ASCENDING/DESCENDING KEY data-name-1 USING file-name-2 GIVING file-name-3. Format 2: SORT file-name-1 ON ASCENDING/DESCENDING KEY data-name-1 INPUT PROCEDURE IS Procedure-name-1[THRU Procredure-name-2] USING file-name-2 GIVING file-name-3. Format 3: SORT file-name-1 ON ASCENDING/DESCENDING KEY data-name-1 INPUT PROCEDURE IS Procedure-name-1[THRU Procredure-name-2] USING file-name-2 OUTPUT PROCEDURE IS Procedure-name-3[THRU Procredure-name-4] GIVING file-name-3. Notes:
The SORT Statement accepts records from one or more files. Sorts them according to the specified key(s), and makes the sorted records available either through an OUTPUT PROCEDURE or in an output file. The SORT Statement can appear any where in the procedure division except in the declarative portion. File-name-1 The name given in the SD entry that describes the records to be sorted. No pair of file-names in a SORT statement can be specified in the same SAME SORT AREA , or Same SORT-MERGE AREA clause. File-names associated with the giving clause (file-name-3) cannot be specified in the SAME AREA clause. File-names associated with the giving clause (file-name-3) can be specified in the SAME AREA clause.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

159

ASCENDING / DESCENDING KEYphrase This Phrase specifies that records be to be processed in ascending or descending sequence (depending on the phrase specified), based on the specified sort keys. When the GIVING phrase is specified , all the sorted records I the file-name-1 are automatically transferred to the output files ( file-name-3).

Copyright Course materials may not be produced in whole or in part without the prior written permission.

160

MERGE Statement
The MERGE statement combines two or more identically sequenced files(that is, files that have already been sorted according to an identical set of ascending/descending keys) on one or more keys and makes records available in merged order to an output procedure or output file. Format:
>>___MERGE__file-name-1____ _____ ___ __ASCENDING__ ___ _______ __data-name-1__| __|_> >___ _____________________________________________________ 2_______> |__ ________________ __SEQUENCE__ ____ _alphabet-name-1_| |_COLLATING____| |_IS_| __USING__file-name-

<__________________ >_____file-name-3__|___________________________________________________________________> >___ __OUTPUT PROCEDURE___ ___ __procedure-name-1__ __________________________ _ _>< |_ |_IS_| |_ _ THROUGH_ procedure-name-2_| _| | |_THRU____| | | <________________ | |_ GIVING___file-name-4__| _________________________________________________________|

Notes:
The MERGE statement combines two or more identically sequenced files(that is, files that have already been sorted according to an identical set of ascending/descending keys) on one or more keys and makes records available in merged order to an output procedure or output file. A MERGE statement can appear anywhere in the Procedure Division except in a Declarative Section. The file names given must be in the SD entry. When the MERGE statement is executed, all records contained in file-name-2, file-name3,., are accepted by the merge program and then merged according to the key(s) specified.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

161

SORT PROCEDURES
Procedures can add, delete, alter or edit the records With SORT .INPUT PROCEDURE you can specify processing to be performed on the records before they are sorted With SORT ..OUTPUT PROCEDURE you can specify processing to be performed on the records after they are sorted In an input procedure the RELEASE statement is used to place a record into the file to be sorted In an output procedure the RETURN statement is used to extract a record from the sorted file Notes:
INPUT PROCEDURE Phrase This phrase specifies the name of a procedure that is to select or modify input records before the sorting operation begins. The input procedure can consist of any procedure needed to select, modify or copy the records that are made available one at a time by the RELEASE statement to the file referenced by file-name-1. The range includes all statements that are executed as the result of a transfer of control by CALL, EXIT, GO TO, and PERFORM statements in the range of the input procedure, as well as all statements in declarative procedures that Sare executed as a result of the execution of statements in the range of the input procedure. The range of the input procedure must not cause the execution of any MERGE, RETURN, or SORT statement. If an input procedure is specified, control is passed to the input procedure before the file referenced by file-name-1 is sequenced by the SORT statement. The compiler inserts a return mechanism at the end of the last statement in the input procedure. When control passes the last statement in the input procedure, the records that have released to the file referenced by file-name-1 are sorted. OUTPUT PROCEDURE Phrase This phrase specifies the name of a procedure that is to select or modify output records from the sorting operation.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

162

The output procedure can consist of any procedure needed to select, modify, or copy the records that are made available one at a time by the RETURN statement in sorted order from the file referenced by file-name-1. The range includes all statements that are executed as the result of a transfer of control by CALL, EXIT, GO TO and PERFORM statements in the range of the output procedure. The range also includes all statements in declarative procedures that are executed as a result of the execution of statements in the range of the output procedure. The range of the output procedure must not cause the execution of any MERGE, RELEASE or SORT statement. If an output procedure is specified, control passes to it after the file referenced by filename-1 has been sequenced by the SORT statement. The compiler inserts a return mechanism at the end of the last statement in the output procedure and when control passes the last statement in the output procedure, the return mechanism provides the termination of the sort and then passes control to the next executable statement after the SORT statement. Before entering the output procedure, the sort procedure reaches a point at which it can select the next record in sorted order when requested. The RETURN statements in the output procedure are the requests for the next record.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

163

RELEASE Statement
The RELEASE statement is only used within the INPUT PROCEDURE of a SORT The RELEASE statement makes the contents of record-name-1 available to the initial phase of the SORT process Upon completion of the INPUT PROCEDURE, the sort file consists of all records placed there by the RELEASE statement Format:
____RELEASE____record-name-1____ ____________________>< _____________________________ |_FROM___identifier-1___________|

Notes:
The RELEASE statement transfers records from an input/output area to the initial phase of a sorting operation. The RELEASE statement can only be used within the range of an INPUT PROCEDURE associated with a SORT statement. Within an INPUT PROCEDURE, at least one RELEASE statement must be specified.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

164

RETURN Statement
The RETURN statement is used only within the OUTPUT PROCEDURE of a SORT or MERGE The RETURN statement acts like a READ and makes the next record from the sort/merge processing available to the application The AT END clause must be specified Format:
>>___RETURN___file-name-1___ ______________ ____ _____________________________ _______> |_ RECORD __| |_INTO___identifier-1___________| >___ _____ 1____________________________________________> |_ AT _| ____END___imperative-statement-

>___ _____________________________________________________ ___ ______________ _____> |_NOT____ _____ __END______imperative-statement-2______| |_ ENDRETURN_| |_AT__|

Notes:
The RETURN statement transfers records from the final phase of a sorting or merging operation to an OUTPUT PROCEDURE. The RETURN statement can be used only within the range of an OUTPUT PROCEDURE associated with a SORT or MERGE statement.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

165

EXAMPLE : SORT
IDENTIFICATION DIVISION. PROGRAM-ID. SORTING. ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT IN-FILE ASSIGN TO DD1 ORGANIZATION IS SEQUENTIAL. SELECT WORK-FILE ASSIGN TO DD2 ORGANIZATION IS SEQUENTIAL. SELECT OUT-FILE ASSIGN TO DD3 ORGANIZATION IS SEQUENTIAL. DATA DIVISION. FILE SECTION. FD IN-FILE. 01 IN-REC. 02 NUM PIC X(2). 02 NAME PIC X(10). 02 ADDR PIC X(10). 02 FILLER PIC X(58). SD WORK-FILE. 01 WORK-REC. 02 WNUM PIC X(2). 02 WNAME PIC X(10). 02 WADDR PIC X(10). 02 FILLER PIC X(58). FD OUT-FILE. 01 OUT-REC PIC X(80). WORKING-STORAGE SECTION. PROCEDURRE DIVISION. SORT WORK-FILE ON ASCENDING KEY WNUM USING IN-FILE GIVING OUTFILE. STOP RUN.

Copyright Course materials may not be produced in whole or in part without the prior written permission.

166

COBOL LAB EXERCISE --- DAY - 1


1. Write a COBOL program, to display << HELLO, WELCOME TO MAINFRAMES>>. 2. Write a COBOL Program, to illustrate the MOVE Verb with the following Data- Items. 01 01 77 77 FLD1 FLD2 FLD3 FLD4 PIC PIC PIC PIC X(10). X(6). 9(8). 9(5).

01 GRP1. 05 05 05 01 GRP2. 05 05 05

AAA BBB CCC AAA BBB CCC

PIC

X(12). PIC A(10). PIC X(10). X(12). PIC A(10). PIC X(10).

PIC

Accept the values for FLD1, FLD2, FLD3, FLD4 through Terminal (I, e JCL). Display the Results. 3. Write a COBOL Program, to illustrate the REDEFINES & RENAMES Clauses.

COBOL LAB EXERCISE --- DAY - 2


Copyright Course materials may not be produced in whole or in part without the prior written. 167

1. Accept the following fields and then perform the ADD, SUBTRACT, MULTIPLY, DIVIDE and operations on those fields. And also use COMPUTE Verb. 01 01 01 77 77 77 FLD1 FLD2 FLD3 FLD4 FLD5 FLD5 PIC PIC PIC PIC PIC PIC 9(2). 9(3). 9(4)V99. 9(5). 9(5)V99. 9(5)V99.

2. Generate a Fibbonacci Series up to N. Accept N through Terminal. 3. Find the number of characters in a given String which can have spaces in middle. 4. Generate an Electricity Bill, the unit price is as follows: 1 to 51 to 101 to 251 to 401 and above 50 units 100 units 250 units 400 units Rs 1.20/unit Rs 2.50/unit Rs 3.50/unit Rs 5.00/unit Rs 7.50/unit

Accept the number units consumed by the customer and display the Customer-id, Name, Address, Number of units consumed and Total price. Use both IF ELSE Statement and EVALUATE Statement.

COBOL LAB EXERCISE ---DAY - 3


1. Create a Sequential File(Physical Sequential Data Set) with the following Record Layout. EMP-NO
Copyright Course materials may not be produced in whole or in part without the prior written.

PIC

X (6).
168

EMP-NAME DESG AGE DEPT

PIC PIC PIC PIC

X (15). X (10). 9 (2). X (8).

Accept the values for above Data items and write into the file. 2. Enter the records to the file which is created by 1st exercise. Read the records from that file and write into a new file and also display them. Update any one record.

COBOL LAB EXERCISE --- DAY - 4


1. Create three Single Dimensional tables of size 10: TAB1, TAB2 and TAB3. Insert first 10 Even numbers into TAB1 and first 10 Odd numbers to TAB2. Add corresponding elements of TAB1 and TAB2, then insert into TAB3. 2. Create three Two Dimensional tables of size 3*3: TAB1, TAB2 and TAB3. Insert first 10 Prime numbers into TAB1 and first 10 Even numbers to TAB2. Perform Addition, Subtraction and multiplication on TAB1, TAB2 and store the resultant value in TAB3.
Copyright Course materials may not be produced in whole or in part without the prior written. 169

3. Accept 12 elements to a single dimensional table and then sort out the elements. Using SEARCH verb find out the given element.

COBOL LAB EXERCISE --- DAY - 5


1. Create a Sequential file (see day1 exercise for record layout), enter the records manually. a) Perform SORT Verb on it b) Perform SORT Verb on it.(Use INPUT PROCEDURE and OUTPUT PROCEDURE) 2. Illustrate STRING, UNSTRING, INSPECT and EXAMINE Verbs. 3. Illustrate CALL Statement

Copyright Course materials may not be produced in whole or in part without the prior written.

170