COBOL

Table of Contents
1. OBJECTIVE...............................................................................................................................................................5 2. INTRODUCTION......................................................................................................................................................6 HISTORY OF COBOL................................................................................................................................................6 ABOUT COBOL..........................................................................................................................................................6 3. PROGRAM STRUCTURE........................................................................................................................................8 REFERENCE FORMAT: -..........................................................................................................................................8 SEQUENCE NUMBER AREA.................................................................................................................................................8 INDICATOR AREA..............................................................................................................................................................8 AREA A..........................................................................................................................................................................9 AREA B...........................................................................................................................................................................9 4. IDENTIFICATION DIVISION...............................................................................................................................10 PROGRAM-ID...........................................................................................................................................................10 5. ENVIRONMENT DIVISION..................................................................................................................................12 CONFIGURATION SECTION: -..............................................................................................................................12 INPUT-OUTPUT SECTION: -..................................................................................................................................13 I-O CONTROL...........................................................................................................................................................14 FILE-CONTROL........................................................................................................................................................14 RECORD FORMAT...................................................................................................................................................14 EFFICIENT FILE ORGANIZATION AND MANAGEMENT................................................................................16 SEQUENTIAL FILE .................................................................................................................................................16 INDEXED FILE ........................................................................................................................................................17 RELATIVE FILE ......................................................................................................................................................18 EXERCISES..................................................................................................................................................................21 6. DATA DIVISION.....................................................................................................................................................22 LEVELS......................................................................................................................................................................22 CONDITION NAMES (88-LEVEL)..........................................................................................................................23 DATA TYPES............................................................................................................................................................23 PICTURE CLAUSE...................................................................................................................................................24 PICTURE STRING - RULES............................................................................................................................................24 FILE SECTION: -.......................................................................................................................................................25 WORKING-STORAGE SECTION: -........................................................................................................................26 REDEFINES...........................................................................................................................................................27 RESTRICTIONS ON REDEFINES.....................................................................................................................................27 EXTERNAL...............................................................................................................................................................28 GLOBAL....................................................................................................................................................................29 JUSTIFIED.............................................................................................................................................................29 SIGN.......................................................................................................................................................................30 SIGN CLAUSE EXAMPLES...............................................................................................................................................31 VALUE CLAUSE: -...................................................................................................................................................31 EDITING: -.............................................................................................................................................................31 LINKAGE SECTION: -.............................................................................................................................................34 USAGE CLAUSE ......................................................................................................................................................35 DISPLAY: -................................................................................................................................................................37 INDEX: -.....................................................................................................................................................................37 POINTER: -................................................................................................................................................................38 SYNCHRONIZED.....................................................................................................................................................39

EXERCISES..................................................................................................................................................................40 7. PROCEDURE DIVISION.......................................................................................................................................41 SECTIONS AND PARAS: -......................................................................................................................................41 RULES FOR SECTION/PARA NAMES: -.........................................................................................................................41 INPUT - OUTPUT VERBS........................................................................................................................................42 ACCEPT.....................................................................................................................................................................42 DISPLAY....................................................................................................................................................................43 DISPLAY - RULES.......................................................................................................................................................43 ARITHMETIC OPERATIONS..................................................................................................................................44 ADD: -........................................................................................................................................................................44 CORRESPONDING: -...............................................................................................................................................45 ADD CORRESPONDING:-.................................................................................................................................................46 ON SIZE ERROR OCCURS..........................................................................................................................................47 ROUNDED PHRASE.....................................................................................................................................................47 SUBTRACT................................................................................................................................................................48 MULTIPLY ...............................................................................................................................................................50 DIVIDE.......................................................................................................................................................................51 COMPUTE.................................................................................................................................................................52 EXERCISES..................................................................................................................................................................53 8. CONTROL FLOW VERBS.....................................................................................................................................55 CONDITIONAL EXPRESSIONS.............................................................................................................................55 RELATION OPERATORS........................................................................................................................................55 CLASS CONDITION.................................................................................................................................................56 SIGN CONDITION....................................................................................................................................................56 COMPLEX CONDITIONS........................................................................................................................................57 LOGICAL OPERATORS...........................................................................................................................................57 GO TO........................................................................................................................................................................58 ALTER........................................................................................................................................................................60 CONTINUE................................................................................................................................................................62 EVALUATE...............................................................................................................................................................63 PERFORM .................................................................................................................................................................65 PERFORM (Basic).................................................................................................................................................66 PERFORM (TIMES option)...................................................................................................................................67 PERFORM (UNTIL option)...................................................................................................................................67 PERFORM (VARYING)..........................................................................................................................................69 EXIT...........................................................................................................................................................................73 EXERCISES..................................................................................................................................................................74 9. NON-NUMERIC DATA MANIPULATION.........................................................................................................75 MOVE.........................................................................................................................................................................75 INITIALIZE................................................................................................................................................................79 INSPECT....................................................................................................................................................................81 STRING......................................................................................................................................................................84 UNSTRING................................................................................................................................................................85 SET.............................................................................................................................................................................86 SET - CONDITION NAME.................................................................................................................................................86 10. SUB-PROGRAM....................................................................................................................................................89 CALL..........................................................................................................................................................................89 CANCEL....................................................................................................................................................................91 ENTRY.......................................................................................................................................................................92

................................................................................................................................................................................................104 DELETE...........................................................148 .................................................................................................................................................................................................................................................................106 INPUT PROCEDURE:-..............................................................................................113 THE END-OF-FILE PHRASE (AT END)....................................................................................................................................................................................................................................................................................................................................................................................................95 START..............................................................................................94 CLOSE..........................................................................................................................................................................................................113 EXCEPTION/ERROR Declarative......................................................................................................................................................................................................................................................... FILE OPERATIONS...130 EXERCISES.............................EXIT PROGRAM..............................................101 REWRITE......................................................................................................................................................................................146 FILE STATUS CODES AND MEANING...................................................................................................................................................................................................................99 WRITE............................................................................................................93 END PROGRAM........................................................................114 FILE STATUS key........................................................................................................................................................134 APPENDIX 1.........................................................................117 FIXED LENGTH TABLES...................................................................................................118 SET.....................................................................................................................................................................................................................................................................................................................................................................................................................................117 VARIABLE LENGTH TABLES................114 EXERCISES........................................................................................................................................................................................................92 GOBACK...........................................................................................................................................................................................................................125 MERGE............................................................................................120 COMPLEX TABLES......................................................................................................................................................................................................................................................................................................................................................................................................................................................115 12...............................................................................................................110 RETURN .............................................................................107 OUTPUT PROCEDURE:-..................................94 OPEN ..........................................................................................................................................................................................................................................................146 REFERENCES....................................................................................................................................................................................................................122 SEARCH................93 11.......................................................................................................................................................................................................................................................................................................111 INPUT/OUTPUT ERROR HANDLING TECHNIQUES........................................................................................................114 INVALID KEY phrase...105 SORT .........116 OCCURS...............94 READ.......................................131 14............................... TABLE HANDLING.......... COMPILER OPTIONS.....................................................................................121 TABLE PROCESSING .....................................................................................................................108 RELEASE........................................................................................................................110 MERGE................................................................................................................................................................................................92 STOP..............................................................................

0 Page 5 of 148 . Objective The main objective of this courseware  To make you learn the Cobol language  To exploit the structured programming of COBOL  To make you develop mainframe applications using COBOL Cognizant Academy Ver 1.Cobol Objective 1.

The IDENTIFICATION DIVISION and ENVIRONMENT DIVISION are the first 2 divisions that need to be defined in the COBOL program. As their names indicate. The principal and interest are added to get amount. IDMS Can handle huge volume of Data COBOL applications can be easily maintained COBOL language consists of 4 major Divisions namely 1. Hence In 1959. PROCEDURE DIVISION. which is used to develop major business applications.0 Page 6 of 148 . why most of business applications are developed using Mainframe COBOL ?     Cobol is English like language hence its easy to learn Can be used with any database like VSAM or DB2. these divisions contain entries that gives the name of the program.Cobol Introduction 2. 1974 Latest COBOL Version in 1985 COBOL II / COBOL 85 ABOUT COBOL  There was a growing need in the early days to have a high level language which will be best suited for Business Applications. Source computer in which the program is written and the object computer in which the program may be run. IDENTIFICATION DIVISION 2. The words PRINCIPAL. The meaning of this statement is quite apparent. It is essential that all the data names which are used in PROCEDURE DIVISION needs to be defined at the outset. This is English like language. INTEREST TO AMOUNT. INTEREST. ENVIRONMENT DIVISION 3. AMOUNT are called Data names. Cognizant Academy Ver 1. Let us consider a statement ADD PRINCIPAL. Introduction HISTORY OF COBOL       Conceived in 1959 Preliminary Version in December 1959 First Standard COBOL in 1961 ANSI Approved Versions in 1968. DATA DIVISION 4. Cobol is a High Level Structured Language. a new language COBOL – COmmon Business Oriented Language emerged. author of the program.

Cognizant Academy Ver 1. These divisions will be explained in detail in the following Chapters. The data that belongs to the input or output record is defined in FILE SECTION and the data names that holds the intermediate results are defined in the WORKING STORAGE SECTION.Cobol Introduction Hence all the data definitions takes place in DATA DIVISION. which specify operations to be performed by the computer. The PROCEDURE DIVISION contains statements. The data definition includes the size of the data item. Hence DATA DIVISION appears before the PROCEDURE DIVISION and it is the third division in the COBOL program. Thus these 4 divisions form the core structure of COBOL program.0 Page 7 of 148 . The last division in the COBOL program is the PROCEDURE DIVISION where the actual algorithm of the program is written. next comes the algorithm. Now that we have defined all the necessary data names and files to be used by the COBOL program. the type and any initial value which needs to be set are defined in DATA DIVISION entries.

entry. Data files. For e. Consider Employee Management System in an Organization.g. interfaces and Reports. An Application contains series of programs.The sequence number area may be used to label a source statement line. PROGRAM STRUCTURE Lets try to develop an application using COBOL program.0 Page 8 of 148 . c lause. 1 6 7 8 11 12 72 73 80 The following areas are described below in terms of a 72-character line: Sequence Number Area Columns 1 through 6: . Indicator Area Column 7: ♦ Any sentence. The content of this area may consist of any character in the character set of the computer. REFERENCE FORMAT: COBOL programs must be written in the COBOL reference format. or phrase that requires more than one line can be continued ♦ ♦ ♦ ♦ ♦ comment line blank line in Area B of the next line which is not a Area A of a continuation line must be blank If no hyphen (-) in indicator Area ♦ ♦ last character of the preceding line is assumed to be followed by a space If hyphen in Indicator Area first non-blank character of this continuation line immediately follows the last nonblank char of continues line ♦ If the continued line contains a non-numeric literal without a closing quotation mark: ♦ literal ♦ ♦ ♦ Continuation line must contain a hyphen in the indicator area First non-blank character must be a quotation mark and Literal continues with the character following the quotation mark all spaces at the end of the continued line (through column 72) are part of the Cognizant Academy Ver 1.Cobol Program Structure 3. Figure 4 shows the reference format for a COBOL source line.

End program header. clauses Continuation lines. sentences.0 Page 9 of 148 . statements. Area B Columns 12 through 72 ♦ ♦ Entries.Cobol Program Structure Area A Columns 8 through 11 The following items must begin in Area A: ♦ ♦ ♦ ♦ ♦ ♦ Division header Section header Paragraph header or paragraph name Level indicator or level-number (01 and 77) DECLARATIVES and END DECLARATIVES. Cognizant Academy Ver 1.

comment.] [INSTALLATION. If the first character is not alphabetic. these are defined in IDENTIFICATION DIVISION which is the First line of the COBOL program. it is converted as follows: 1 through 9 are changed to A through I Anything else is changed to J. ♦ ♦ The first 8 characters of program-name of the outermost program should be unique within the system. but.] [DATE-COMPILED. Program name [AUTHOR. Since the information identify a particular program. There may be several paragraphs in this division of which PROGRAM-ID is essential paragraph. The other paragraphs are optional. comment. Except PROGRAM-ID all the other paragraphs are optional and are mainly for documentation purposes. The first character must be alphabetic. when written. comment.} PROGRAM-ID. there can be comment statements describing the functionality of the program. comment.] PROGRAM-ID The first paragraph of the Identification Division must be the PROGRAM-ID paragraph. Cognizant Academy Ver 1. comment.] [SECURITY. it is changed to zero (0).] [DATE-WRITTEN. must appear in the order shown in the format. The syntax for {IDENTIFICATION DIVISION ID. The system uses the first 8 characters of program-name of the outermost program as the identifying name of the program. Each program has a Program id – Name of the program. ♦ If a hyphen is used in characters 2 through 8 of the program-name of the outermost program. This program names is used to identify the object program. and a change log block giving the details about programmers who changed the program as a part of enhancement to the program. Apart from these statements. Author – Person who is writing the program and other information like date written.0 Page 10 of 148 . date compiled.Cobol Identification Division 4. The Program name is a user-defined word that identifies your program. IDENTIFICATION DIVISION IDENTIFICATION DIVISION is the first division in the COBOL program.

AUTHOR.0 Page 11 of 148 .G:- Identification Division IDENTIFICATION DIVISION. PROGRAM-ID. 01/01/01. ****************************************************************** *********** BRIEF PROGRAM DESCRIPTION ************ * PROGRAM OBJECTIVE: This Program Maintains the Employee file by updating the master file. Cognizant Academy Ver 1.Cobol E. CTS. DATE-WRITTEN. EMPMAINT1. DATE-COMPILED.

CURRENCY can be changed or the DECIMAL POINT can be COMMA. [.Cobol Environment Division 5. Now we need to define the Machine dependent details for our program.This paragraph specified the name of the computer used to execute the The SPECIAL NAMES paragraph can have entries. Among all the divisions this one is the most machine dependent division. SOURCE-COMPUTER. The ENVIRONMENT DIVISION must follow the IDENTIFICATION DIVISION in the COBOL program. DECIMAL-POINT IS COMMA] [. Computer-name. The Environment Division consists of 2 sections The Configuration Section The Input-Output Section CONFIGURATION SECTION: The configuration section appears first.This paragraph specifies the name of the computer used to compile the OBJECT COMPUTER:. ENVIRONMENT DIVISION The identification division gives introduction about the program.0 Page 12 of 148 . Like the be coded COBOL program. Cognizant Academy Ver 1. COBOL program. ALPHABET alphabet-name IS { STANDARD-1 STANDARD-2 EBCDIC NATIVE ♦ ♦ ♦ ♦ In the configuration section at least the source computer and object computer paragraph needs to SOURCE COMPUTER:. These details are given in ENVIRONMENT DIVISION. [ PROGRAM COLLATING SEQUENCE IS alphabet-name]. OBJECT-COMPUTER. The computer and all the peripheral devices required by the program are described in this division. CURRENCY SIGN IS literal-1] [. [SPECIAL-NAMES. Computer-name. which are implementor dependent.

ALPHABET ASCII-order IS STANDARD-1. OBJECT -COMPUTER. Example 2: CONFIGURATION SECTION. VAX-6410 PROGRAM COLLATING SEQUENCE IS ASCII-order. DECIMAL POINT IS COMMA ♦ Environment Division Default collating sequence is EBCDIC on the IBM. the program writes processed data either into a separate file or updates data in the existing file. As a application development programmer. This section contains the information regarding the files to be used by the program and the peripheral device from the file can be accessed. SOURCE-COMPUTER. After data processing. SPECIAL-NAMES.0 Page 13 of 148 . VAX-6410 PROGRAM COLLATING SEQUENCE IS ASCII-order. SPECIAL-NAMES. FILE-CONTROL Cognizant Academy Ver 1. Example 1: CONFIGURATION SECTION. CURRENCY IS DOLLAR.g SPECIAL NAMES. This section has 2 paragraph. SOURCE-COMPUTER. ♦ ♦ I-O CONTROL. OBJECT-COMPUTER. ALPHABET ASCII-order IS STANDARD-1 DECIMAL IS COMMA CURRENCY IS ‘#’ SYMBOLIC CHARACTERS backspc IS 23 INPUT-OUTPUT SECTION: Each application program gets data from some data files and processes data.Cobol ♦ For e. IBM 3090. we should know what are all the data files needed for processing by our program. These files are defined in FILE-CONTROL paragraph of the INPUT-OUTPUT section. Supposing we want ASCII. IBM 3090.

SELECT.This is the name used by COBOL to refer inside the program.Specify RECORDING MODE F . what organization is it. I-O CONTROL is not used these days. Assignmtname1: . OPTIONAL: This key word is used only for input files. which access mode is used to access the files etc.0 Page 14 of 148 . This feature is invalid in COBOL 370.Cobol Environment Division I-O CONTROL. When the key word OPTIONAL is used in the select clause. The syntax is as follows FILE-CONTROL.Max length of 01 level entry is less than BLOCK contains clause size AND either ♦ ♦ Record contains clause has single size (Not a range) All 01 level entry is same and no depending on option Cognizant Academy Ver 1. SELECT SELECT [OPTIONAL] filnam1 ASSIGN TO assignmtname1 [ORGANIZATION IS {SEQUENTIAL. this file need not be present during the execution.DDNAME given in JCL. By medium. . Each data file used by the program should be defined in the FILE-CONTROL paragraph. we also describe what type of file it is. in Mainframe environment. we mean the DDNAMES in run JCL. RELATIVE) ] [ACCESS MODE IS { SEQUENTIAL RANDOM DYNAMIC } ] [FILE STATUS IS dataname-1 [dataname-2] ]. If this keyword is omitted. In this paragraph. RECORD FORMAT ♦ Fixed . the file must be present. This paragraph also gives the medium through which the file can be accessed.This statement gives the relationship between the filename used in the program and the data file used in the JCL. Filname1: . INDEXED.

.Cobol ♦ Unblocked B L O C K E D ♦ Variable .Max length of 01 level entry + 4 is greater than BLOCK contains clause size .Block descriptor field .Can be Fixed or variable .BLOCK contains clause is treated as comment Cognizant Academy Ver 1.Segment descriptor field Undefined Records .Compiler does not derive .Specify RECORDING MODE S .Max length of 01 level entry is less than BLOCK contains clause size AND either ♦ Record contains clause has range ♦ BDW 01 level entry is different or has depending on option RDW Data Record BDW / RDW = 2 byte length + 2 byte System info ♦ Spanned Records .Can be Blocked or Unblocked BDF BDF SDF ♦ SDF Rec segment SDF .Specify RECORDING MODE V Environment Division .Specify RECORDING MODE U .0 Page 15 of 148 .Unspecified characteristics .Max record length is • • As specified in Record Contains or varying clause If omitted max 01 level entry size .Each block on external storage is treated as a logical record.

Either works for an application that uses only sequential access of fixed-length or variable-length records and no insertion of records between existing ones. ♦ A SAM or VSAM sequential file is the simplest file type. Sort Records can be accessed in the order in which they appear in the file Records can be updated Records can be appended but not inserted Records cannot be deleted files etc. It may be used for applications requiring both sequential and random access in the same program. variable.0 Page 16 of 148 . indexed. Depending on the input/output requirements and device types. ♦ If a large percentage of the file is referenced or updated in your application program. intermediate files for processing. transaction files. A VSAM relative file can make use of fixed-length or variable-length records. use indexed or relative access. random. SEQUENTIAL FILE ♦ ♦ ♦ ♦ ♦ The sequential files are used for Reports. or relative. ♦ A VSAM indexed file is the most flexible data set.Cobol Environment Division EFFICIENT FILE ORGANIZATION AND MANAGEMENT The most important activity while designing the COBOL program is the File organization and management. sequential processing is faster than indexed or relative. or dynamic) Record formats (fixed. ♦ A VSAM relative file works well for an application that performs random insert and deletes operations. A indexed file can make use of fixed-length or variable-length records. Cognizant Academy Ver 1. undefined). If a small percentage of records are processed during each run of your application program. SAM and VSAM are the two access methods available with COBOL that will handle the input/output requests to the operating system for the storage and retrieval of records from the input/output devices. spanned. your file organization will either be sequential. For this we need to know ♦ ♦ ♦ ♦ ♦ File type and organization Devices Access modes (sequential.

This is the name referred in the DD Statement in the JCL ORGANIZATION: . ♦ ♦ ♦ ♦ Random Access of Records using a Record Key Records can be Inserted.NT91. // DISP=SHR INDEXED FILE ♦ ♦ The indexed files are the most flexible type of files. Updated and Deleted Indexed Access is faster than Sequential Access Unique or Non-Unique Indexes Cognizant Academy Ver 1. Assignmtname1: . Filname1: . The actual physical arrangement of the records in the main file is not significant to COBOL program.TEST.Cobol Environment Division SELECT [OPTIONAL] filnam1 ASSIGN TO assignmtname1 [ORGANIZATION IS SEQUENTIAL] [ACCESS MODE IS SEQUENTIAL ] [FILE STATUS IS dataname-1 [dataname-2] ]. which means this file is sequential file.G :SELECT MNT91 ASSIGN TO INT91 ORGANIZATION IS SEQUENTIAL ACCESS MODE IS SEQUENTIAL FILE STATUS IS W01-X-FST-NT91. The indexed files can be Master files in the The index component of the file provides the logical arrangement of the main file. JCL required at run time for Files // INT91 DD DSN=CTS.gives the type of file. Here its Sequential.MNT91.0 Page 17 of 148 .INT91. E. ordered by Data base or the History files record key.

RELATIVE FILE ♦ ♦ ♦ Also called Direct Access Files Each record has a unique address and is identified by its Relative Record Number in the file Records can be Accessed Randomly using their Relative Record Numbers Cognizant Academy Ver 1.. [FILE STATUS IS dataname-1 [dataname-2] ]. RANDOM : . ACCESS MODE = SEQUENTIAL – The records can be accessed sequentially. // DISP=SHR ORGANIZATION is INDEXED means it s a VSAM file. Here the file is treated as sequential. DYNAMIC: . The records of the indexed file can be accessed in any mode.G : SELECT B20ASIML ASSIGN TO ISIML ORGANIZATION IS INDEXED ACCESS MODE IS DYNAMIC RECORD KEY IS B20A-G-SIML-KEY FILE STATUS IS W01-X-FST-B20A.. JCL required at run time for Files //ISIML DD DSN=CTS.TEST. assignmtname1 = [label-]DDname E.0 Page 18 of 148 .SIML.The records can be accessed both sequentially and randomly.The records can be accessed in any order by giving the key value to the RECORD KEY variable.Cobol Environment Division SELECT filnam1 ASSIGN TO assignmtname1 [ORGANIZATION IS INDEXED ] [ACCESS MODE IS { SEQUENTIAL RANDOM DYNAMIC } ] RECORD KEY IS data-name-3 ( [ ALTERNATE RECORD KEY IS data-name-4] [WITH DUPLICATES] ) .

VALUE OF REL.Cobol Environment Division SELECT filnam1 ASSIGN TO assignmtname1 [ORGANIZATION IS RELATIVE ] [ACCESS MODE IS { SEQUENTIAL RANDOM DYNAMIC } ] RELATIVE KEY IS dataname-3 [FILE STATUS IS dataname-1 [dataname-2] ]. KEY Table 5.1 . OR RANDOM ORDER OF WRITE INVALID ASC. OR RANDOM SEQ. KEY VALUE VALUE OF REC. NO. assignmtname1 = [label-]DDNAME ACCESS ORG. 12) ♦ ♦ Return code Function code Feedback code 2 byte binary (0 to 5) 2 byte binary (0 to 255) Cognizant Academy Ver 1.File Access Modes File Status [FILE STATUS IS dataname-1 [dataname-2] ] data-name-1 : 2 bytes character data-name-2 : 6 bytes character (For VSAM) 2 byte binary (value 0.0 Page 19 of 148 . REC. KEY ASC. 8. SEQ RELATIVE INDEXED SEQ RANDOM DYNAMIC INVALID SEQ. REL.

B08. // DCB=(RECFM=FB. Cognizant Academy Ver 1.CATLG.NT91. // DISP=SHR //OCATF DD DSN=CTS.TEST. are given in the DD statement. The contents of the current input record. All the files.CATLG). // DISP=(NEW.0 Page 20 of 148 . when the abend took place also appears in the SYSUDUMP.(10.RLSE). // DISP=SHR // INT91 DD DSN=CTS. All the display statement messages appear in the SYSPRINT.LRECL=23) //SYSOUT DD SYSOUT=* //SYSUDUMP DD SYSOUT=* //SYSPRINT DD SYSOUT=* //* The above JCL is the RUNJCL for the application program. which are defined in the select clause in FILE SECTION. // SPACE=(CYL.SIML.CATF.M0101.50). The SYSUDUMP DD statement is where the dump of the data appears when an Abend occurs while executing the program.TEST.Cobol Environment Division RUN JCL for Program Execution //PXXBB398 EXEC PGM=MYPROG //ISIML DD DSN=CTS.

The program EMPMAINT uses employee master file. Write the environment division for the above program The program is written on IBM-3090 machine and run on the same machine. Write the Identification division for following. in a COBOL program? 2. The Employee master file is an indexed file with primary key as employee number.Cobol Exercises EXERCISES 1. 3.0 Page 21 of 148 . the transaction file. Cognizant Academy Ver 1. Also write the execution JCL. Where do you define the files used. error file and card file. error file and card file are all sequential files. employee transaction file. You are developing a program named EMPMAINT.

Our application program needs to know the layout of the files used for it to process the data. 88 The level Number of the Elementary Items is greater than that of the group Item. The DATA DIVISION has the following sections.G. The 05 level numbers are the sub-group items. The data type for the variables is described using Picture Clause. The 10 level numbers are the elementary items. 05 ASSOC-NO 05 ASSOC-NAME. 77. The 01 level number is root in the hierarchy of the logical record The size of the Group item is equal to the sum of the sizes of the elementary or sub-group items. 10 FIRST-NAME 10 LAST-NAME 05 ASSOC-ADDRESS. Cognizant Academy Ver 1. we have defined the environment in which our application program will be executed. ♦ ♦ ♦ FILE SECTION WORKING-STORAGE SECTION LINKAGE SECTION This data division has LEVEL structure. E.0 Page 22 of 148 .Cobol DATA DIVISION 6. 10 ADDR-LINE-1 10 ADDR-LINE-2 10 ADDR-LINE-3 10 TELEPHONE-NO In this example the 01 ASSOC-REC is the root. 01 ASSOC-REC. We define the file layout in the DATA DIVISION. DATA DIVISION Until now. the data files used by the program. LEVELS ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ Mimic the hierarchy in the Logical Record The lowest subdivision is an Elementary Item Elementary items can be combined into group items Elementary Items may form part of one or more Groups Level Numbers 01 to 49.

Cobol 77 Level ♦ ♦ Elementary Data Item not belonging to any group Must begin in Area A

DATA DIVISION

E.G 01 ASSOC-REC. 77 W04-TEMP-I CONDITION NAMES (88-LEVEL) 88 data-name { VALUE IS VALUES ARE } ( lit-1 [THRU lit-2] ) ... ♦ Used for Condition Checking Example: 01 W03-G-FLAG-VAR. 03 W03-G-FLAG-VAR. 05 W03-X-REPTYPE-FLAG PIC X(02) VALUE 'NR'. 88 C03W-NORMAL-REQ-FLAG VALUE 'NR'. 88 C03W-SHOP-BOUND-FLAG VALUE 'SB'. 88 C03W-SHOP-VAR-FLAG VALUE 'SV'. 05 W03-X-REQ-PROCESSED PIC X(01) VALUE 'N'. 88 C03W-REQUEST-PROCESSED-Y VALUE 'Y'. 88 C03W-REQUEST-PROCESSED-N VALUE 'N'. DATA TYPES
♦ ♦ ♦ ♦ ♦ ♦ ♦ Elementary Data Items Alphanumeric Alphabetic Numeric (Zoned, Packed, Binary) Numeric Edited Alphanumeric Edited Group Data Items are Alphanumeric

PIC X(01).

Cognizant Academy

Ver 1.0

Page 23 of 148

Cobol

DATA DIVISION

PICTURE CLAUSE { PICTURE IS pic-string1 PIC } ♦ Specified for every Elementary Item ♦ pic-string1 can contain a maximum of 30 Code Characters ♦ Code Character repetitions can be indicated by an integer within ( ) Code Char 9 X A V P S B 0 / , . * $ + CR DB Meaning Numeric Data Item Any allowable character from the character set a Letter or Space Assumed Decimal Point Position of Assumed Decimal Point when it lies outside Data Item is Signed Inserts space Inserts zero Inserts Slash Inserts Comma Inserts Decimal Point Replaces leading zeros Inserts Currency sign Inserts Sign Sample Picture 9999 XXXX AAAA 99V99 99PPV PPP99 S9(4) XXBXXX 9(5)000 XX/XX/XX 9,999 9,999.99 ****9.99 $9,999.99 +99.99 -99.99 99.99DB 99.99CR

Table 6.1 Code Characters PICTURE String - Rules
♦ ♦ ♦ Code characters can be in lower case Codes usable once or more A B P X Z 9 0 / , + - * $ Codes usable just once -S V . CR DB

Cognizant Academy

Ver 1.0

Page 24 of 148

Cobol

DATA DIVISION

PICTURE String - Rules for data categories
♦ Alphabetic item Only A allowed ♦ Numeric Items 9 P SV PICTURE 9999 S99 S999V9 ♦ Valid Range of Values 0 through 9999 -99 through +99 -999.9 through +999.9

Numeric-edited items - B P V Z 9 0 / , . + - CR DB * $ - At-least one edit char or BLANK WHEN ZERO clause

Alphanumeric items - The symbol X or - Combinations of the symbols A, X, and 9.

Alphanumeric-edited items -A X 9 B 0 / - Must contain at least one A or X, and at least one B or 0 or /.

FILE SECTION: The layouts of the files are described in this section. The files, which are defined in the SELECT clause, should have an FD entry in the FILE SECTION. The record layout for the files is defined in the FD section which is FILE DESCRITPTION entry for the files defined in the SELECT clause. The File description entry is followed by the record description entry, A Record Description entry is a 01 level group item along with its sub divisions. If there are more than one 01 level, this means that the file defined is a Variable file which has different record layouts.

Cognizant Academy

Ver 1.0

Page 25 of 148

RECORDING MODE IS F BLOCK CONTAINS 2 RECORDS.. WORKING-STORAGE SECTION: ♦ ♦ ♦ ♦ ♦ ♦ ♦ This section is used to define the temporary variables in the COBOL program.G. RECORD CONTAINS: The RECORD contains clause gives the physical record.Cobol The syntax of the FD entry is DATA DIVISION FD file-name-1 [ BLOCK CONTAINS [ int1 TO ] int2 { CHARACTERS RECORDS } ] [ RECORDING MODE IS { F V S U } ] [ RECORD { CONTAINS int3 [TO int4] CHARACTERS } ] [ DATA { RECORD IS RECORDS ARE } ( data-name-2 ) . This has to match with record length in the DD statement parameter.0 Page 26 of 148 . E. It is used like a scratch pad inside the program. FD INT91. Succeeds File Section Used for Intermediate Storage Common Practice to Group related items together Cognizant Academy Ver 1. Level 88 is used for Conditional variables. The BLOCK CONTAINS RECORDS clause specifies the number of logical records present in each physical record (the actual data records in the main memory). The data in the working storage may be group item or elementary item.. Level 77 is used to define elementary data item in the working storage section. 01 NT91-HDR PIC X(80). The int1 and int2 specifies the minimum and maximum character sizes of the physical record. ] BLOCK CONTAINS: The BLOCK CONTAINS CHARACTERS clause specifies the size of the physical records.

05 I-ADD-LINE-2 PIC X(30). 05 I-ADD-LINE-3 PIC X(30).Cobol DATA DIVISION ♦ Example 01 I-ADDRESS. 05 I-ADD-LINE-1 PIC X(30). Cognizant Academy Ver 1.0 Page 27 of 148 . Syntax for Data Description Entry level {data-name-1 FILLER} [REDEF clause] [BLANK-WHEN-ZERO clause] [EXTERNAL clause] [GLOBAL clause] [OCCURS clause] [JUST clause] [PIC clause] [SIGN clause] [USAGE clause] [VALUE clause] . REDEFINES level {data-name-1 FILLER} REDEFINES data-name-2 ♦ ♦ Allows the same area of memory to be referenced by more than one data-name with different Multiple 01 levels of same FD are Implicitly Redefined format and sizes Restrictions on REDEFINES ♦ OCCURS and REDEFINES cannot be combined ♦ Qualification of data-name-2 not required ♦ Value Clauses only in Condition Names ♦ Redefinition Ceases Whenever a Level No is <= that of data-name-1 or data-name-2 is encountered ♦ The Size of Data-name-1 must be Less than or equal to Data-name-2 ♦ Data item lengths and types can also be respecified within an area.

MOVE X TO B and MOVE Y TO C. if B REDEFINES C has been specified. could be executed at any point in the program. 10 SALARY PICTURE XXX. 10 YEAR PICTURE XX.0 Page 28 of 148 . ♦ ♦ ♦ When an area is redefined. 10 EMP-NO PICTURE X(6). These items must be described. 10 WAGE PICTURE 999V999. 05 NAME-1 REDEFINES NAME-2. all descriptions of the area are always in effect. elementary numeric or numeric-edited items. redefinition does not cause any data to be erased and never supersedes a previous description. That is. Thus.Cobol DATA DIVISION REDEFINES Examples 05 NAME-2. as USAGE IS DISPLAY ♦ ♦ items The BLANK WHEN ZERO clause specifies that an item contains The BLANK WHEN ZERO clause can be specified only for nothing but spaces when its value is zero. either implicitly or Useful for printing Not allowed on 66 and 88 levels & on POINTER and INDEX data EXTERNAL ♦ This clause indicates that the data item is external to the program and is common to the entire run unit Cognizant Academy Ver 1. 10 SO-SEC-NO PICTURE X(9). 10 MONTH PICTURE XX. BLANK WHEN ZERO ♦ BLANK WHEN { ZERO ZEROS ZEROES } ♦ ♦ explicitly. either of the two procedural statements.

JUSTIFIED { JUSTIFIED JUST} ♦ ♦ ♦ ♦ ♦ RIGHT The JUSTIFIED clause overrides standard positioning rules for a receiving item of the alphabetic or alphanumeric categories Can’t be specified for other categories Does not affect initial values. not valid in Linkage Section All data-names subordinate to or condition-names or indexes associated with a global name are global names. as determined by the VALUE clause Does not affect the setting of conditional variable when the associated condition name is set Items described as USAGE IS POINTER Cognizant Academy Ver 1. The search begins within the program that contains the reference and continues "outward" to containing programs until a match for the GLOBAL name is found.0 Page 29 of 148 . GLOBAL ♦ ♦ ♦ ♦ ♦ This clause indicates that the data item is available to all the nested programs unless it is defined in the contained program Valid only for 01 Level Valid only in Working Storage and File Section.Cobol ♦ ♦ ♦ ♦ ♦ ♦ ♦ Subordinates to an EXTERNAL group item attains EXTERNAL attribute DATA DIVISION All programs referring to the EXTERNAL data item must define same number of standard data format characters (Total length) Name used for the data item cannot be used on another EXTERNAL item within the same program VALUE clause not allowed Allowed only at the 01 Level Not allowed in Linkage and File Section Indexes in an EXTERNAL data record do not possess the external attribute.

use of this clause is prohibited. In these cases. the SIGN clause for the subordinate entry takes precedence for the subordinate entry.0 Page 30 of 148 .Cobol DATA DIVISION JUSTIFIED . 1.Examples 05 align-rt pic x(5) 88 c-rt JUST RIGHT. one whose If a SIGN clause is specified in either an elementary or group entry subordinate to a group item for ♦ ♦ ♦ PICTURE STRING contains an S) which a SIGN clause is specified. SIGN [SIGN IS {LEADING TRAILING} ] [ SEPARATE CHARACTER ] Specifies the position and mode of representation of the operational sign for a numeric entry. The TRAILING phrase indicates that sign is to be stored in the trailing position The LEADING phrase indicates that sign is to be stored in the leading position Cognizant Academy Ver 1. value ‘RT’. MOVE ‘RT’ TO align-rt 2. SET c-rt TO TRUE Value of align-rt Before stmt-1 RTbbb After stmt-1 bbbRT After stmt-2 RTbbb PICTURE [ PICTURE IS string PIC ] ♦ ♦ ♦ ♦ Specifies the characteristics and editing requirements Must be specified for every elementary item except an index data item or the subject of the The PICTURE clause can be specified only at the elementary level The PICTURE character-string can contain a maximum of 30 characters RENAMES clause. ♦ ♦ ♦ The SEPARATE phrase indicates that sign is stores as separately and not in the zoned part. The Sign Clause can be specified for a signed numeric data description entry (that is.

l-V1 K 5 0 77 l-V2 PIC S9(3) SIGN LEADING SEPARATE VALUE -250 l-V2 2 5 0 77 l-V2 PIC S9 (3) SIGN TRAILING VALUE -250 The value stored internally in 3 characters as l-V2 2 5 0 VALUE CLAUSE: The VALUE clause is used to set an initial value to the working storage variable.0 Page 31 of 148 . E.Cobol DATA DIVISION SIGN Clause Examples 77 l-V1 PIC S9(3) SIGN LEADING VALUE K50 K stands for -2. 03 W04-X-PGM-NAME PIC X(08) VALUE 'PXXBB290'. In the above example the variable W04-X-PGM-NAME is set to an initial value of PXXBB290 The alphanumeric items can be initialized to Spaces and numeric items can be initialized to Zeros EDITING: Sometimes the data when written to report needs some editing to be done. 01 W04-G-VAR. 03 W04-X-RUN-TIME PIC X(20) VALUE SPACES. This can be specified only in the working storage variable.G WORKING-STORAGE SECTION. There are 2 Editing done in COBOL Numeric Editing Alphanumeric Editing Cognizant Academy Ver 1. The VALUE Clause can not be a part of RECORD DESCRIPTION entry in the FILE SECTION. 01 W04-TEMP-J PIC 9(02) VALUE ZEROES.

Floating insertion.Cobol DATA DIVISION The Numeric Edit characters are B P V Z 9 0 / .Fixed insertion .B999. .Alphanumeric-edited (Only Simple insertion) ♦ Simple insertion -B0/ only for numeric edited PICTURE X(2)BX(3)BX(4) 9(2)/9(2)/9(2) 99.999 Value of Data 19Mar1995 190395 1234 12345 Edited Result 19 Mar 1995 19/03/95 01.345 Cognizant Academy Ver 1.Numeric-edited (All edits) .0 Page 32 of 148 . 000 12.B000 99. + .CR DB * $ The alphanumeric Edit Characters are A X 9 B 0 / PICTURE Clause Editing ♦ Insertion .Zero suppression and replacement with asterisks or spaces ♦ EDITING ALLOWED ONLY for Categories: .Simple insertion . 234.Special insertion . ♦ Suppression & Replacement .

456 +123.Mutually exclusive PICTURE $$$$.+++ Value of Data .99CR ++.56 -123.CR DB (editing-sign control symbols) PICTURE 999.99 9999.34 123.456 +123.50 .45 +123.99 999.99 ♦ ♦ Fixed Insertion Editing .+ .789 -1234567 0000.99 -$999.45 -123.$ + .99 $.+++. it also represents the actual decimal point for alignment purposes PICTURE 999.23 012.45 -123.99 999.00 Edited Result bbb$.45 $0123.12 bb$0.234 12.45 -123.99DB $9999.55+ -6555.Period (.99CR ♦ Value of Data +6555.234.) is the special insertion symbol.99 -$999.+++.12 bbbb$1.99DB $9999.45 $0123.+++.45 234.5 Edited Result 001.0 Page 33 of 148 .99 999.$$$.45DB $0123.456.56 -$123.556 -6555.45CR Floating Insertion .45 1234.123 .56 b-123.99+ +9999.99CR $9999.99 -$999.99 $$$9.55 1234.12 -1234.555 +1234.Cobol DATA DIVISION ♦ Special Insertion Editing .99 $$.45 Edited Result 555.$$$.567.$$$.99 $9999.45 $0123.999.45 $123.56 -123456.999.234.99 +.78 $1.45 -$123.00CR Bbbbbbb Cognizant Academy Ver 1.$ (currency symbol) Value of Data 1.34 123.

4512. Thus in DATA DIVISION.456 -123. 05 DEPT PIC 9(4).** Bbbbbbb Bbbbbbb $.02 bbbb. 01 SALARY-REC.$$ $$$$.00 0000.00 0000.as floating replacement Z * + .02 0000.90+ $b1. 05 SALARY PIC 9(6).***.***.00 +123.45+ **123.Cobol DATA DIVISION ♦ Zero Suppression and Replacement . Cognizant Academy Ver 1. we have defined data used by our program. Example: LINKAGE SECTION.345.00 bb123.ZZ $$$$.ZZ+ *.56bb $b ***12.678. 05 NAME PIC X(20).** ZZZZ.234.e.**+ $ZZ.***.**+ **.ZZCR $B*.ZZZ.67bbDB The LINKAGE SECTION is used to define any data passed across programs.**BBDB LINKAGE SECTION: - Value of Data 0000. 05 PTR-NEXT-REC POINTER.temporary variables if any.ZZZ.67 Edited Result ****.00 0000.***.345.Z * (Mutually exclusive) .$$ ZZZZ.45 +12345678.00 bb00. i. in WORKING-STORAGE SECTION . the layout of the data passed is defined in the linkage section. in the FILE SECTION – Data file layouts.99 Z.56 -12345.$ are mutually exclusive PICTURE ****.00 0000.99 ZZ99.***.0 Page 34 of 148 .9 +1234. and in the LINKAGE SECTION the layout of the data passed across programs.

Cobol DATA DIVISION USAGE CLAUSE The data can be stored in more than one internal form in the computer. The USAGE clause specifies the format of a data item in computer storage.One or more numeric character positions S :. The PICTURE of a computational item can contain only: ♦ ♦ ♦ ♦ 9 :. ♦ ♦ The maximum length of a computational item is 18 decimal digits.One implied decimal point P :.0 Page 35 of 148 .One operational sign V :. It must be numeric. If the USAGE of a group item is described with any of these items. In COBOL. These are forms of internal representation ♦ ♦ ♦ ♦ Computational Display Pointer Packed – decimal The syntax of the USAGE clause is USAGE IS {BINARY COMP COMPUTATIONAL COMP-1 COMPUTATIONAL-1 COMP-2 COMPUTATIONAL-2 COMP-3 COMPUTATIONAL-3 COMP-4 COMPUTATIONAL-4 DISPLAY INDEX PACKED-DECIMAL POINTER} COMPUTATIONAL: The Computational or COMP phrase has the following 6 formats ♦ A computational item is a value used in arithmetic operations. the elementary items within the group have this usage. a programmer is allowed to specify the internal form of the data item so as to facilitate the use of the data item more efficiently.One or more decimal scaling positions Cognizant Academy Ver 1.

The number of bytes = n+1/2 Where n is the number of places specified in PIC clause For e. Cognizant Academy Ver 1. COMP-2 items are 8 bytes long. COMPUTATIONAL-4 or COMP-4 (Binary) This is the equivalent of BINARY. COMPUTATIONAL-1 or COMP-1 (Floating-Point): Specified for internal floating-point items (single precision). The sign is stored separately as rightmost half-a-byte regardless of whether S is specified in the PIC clause or not. but one digit takes half-a-byte. The PIC clause cannot be specified for this item COMPUTATIONAL-2 or COMP-2 (Long Floating-Point) Specified for internal floating-point items (double precision). The PIC clause cannot be specified COMPUTATIONAL-3 or COMP-3 (Internal Decimal) This is the equivalent of PACKED-DECIMAL. The amount of storage occupied by a binary item depends on the number of decimal digits defined in its PICTURE clause: Digits in PICTURE Clause 1 through 4 5 through 9 10 through 18 Storage Occupied 2 bytes (halfword) 4 bytes (fullword) 8 bytes (doubleword) COMPUTATIONAL or COMP:This is the equivalent of BINARY. In this form of internal representation the numeric data is represented in the decimal form. COMP-1 items are 4 bytes long. plus a sign. which means more significant digits can be available for the item. Negative numbers are represented as the two's complement of the positive number with the same absolute value.Cobol DATA DIVISION BINARY :Specified for binary data items. The advantage is that this increases the precision of the data. Such representation is suitable for Arithmetic operations. The COMPUTATIONAL phrase is synonymous with BINARY.g. Such items have a decimal equivalent consisting of the decimal digits 0 through 9.0 Page 36 of 148 . The number is actually represented in Hexadecimal form. 77 ITEM-1 PIC S9(7) COMP-3 will occupy 4 bytes. The hexadecimal number C or F denotes positive sign and D denotes negative sign.

the elementary items within the group are index data items. or VALUE clauses cannot be used to describe group or elementary items described with the USAGE IS INDEX clause. a SET statement. or indirectly in a MOVE or input/output statement. Cognizant Academy Ver 1. An index data item saves values that represent table occurrences. a relation condition. DISPLAY can be explicit or implicit. An index data item is a 4-byte elementary item (not necessarily connected with any table) that can be used to save index-name values for future reference. when it is referred to directly in a SEARCH or SET statement. The USAGE IS INDEX clause can be written at any level. there is no conversion of values when the statement is executed. Thus. the group itself is not an index data item. such a value corresponds to the occurrence number in a table. PICTURE.0 Page 37 of 148 . This corresponds to the format used for printed output.Cobol DATA DIVISION DISPLAY: The data item is stored in character form. the USING phrase of the Procedure Division header. an index data item can be assigned an index-name value. BLANK WHEN ZERO. or the USING phrase of the CALL statement. 1 character for each 8-bit byte. An index data item can be part of a group item referred to in a MOVE statement or an input/output statement. If a group item is described with the USAGE IS INDEX clause. yet is not necessarily defined as part of any table. An index data item cannot be a conditional variable. USAGE IS DISPLAY is valid for the following types of items: ♦ ♦ ♦ ♦ ♦ ♦ Alphabetic Alphanumeric Alphanumeric-edited Numeric-edited External floating-point External decimal (numeric) INDEX: A data item defined with the INDEX phrase is an index data item. Through a SET statement. JUSTIFIED. The USAGE clause of an elementary item cannot contradict the USAGE clause of a group to which the item belongs. The DATE FORMAT. and the group name cannot be used in SEARCH and SET statements or in relation conditions. Direct references to an index data item can be made only in a SEARCH statement. SYNCHRONIZED.

PICTURE. Cognizant Academy Ver 1. The USAGE clause of an elementary item cannot contradict the USAGE clause of a group to which the item belongs. USAGE IS POINTER is implicitly specified for the ADDRESS OF special register. the group itself is not a pointer data item and cannot be used in the syntax where a pointer data item is allowed. A pointer data item can be written to a data set. JUSTIFIED. A pointer data item can be the subject or object of a REDEFINES clause. A pointer data item does not belong to any class or category. Pointer data items are ignored in CORRESPONDING operations. A VALUE clause for a pointer data item can contain only NULL or NULLS. A pointer data item can only be used: ♦ ♦ ♦ In a SET statement (Format 5 only) In a relation condition In the USING phrase of a CALL statement. A pointer data item cannot be a conditional variable. You can use pointer data items to accomplish limited base addressing. the elementary items within the group are pointer data items. If a group item is described with the USAGE IS POINTER clause. Pointer data items can be compared for equality or moved to other pointer items. POINTER: A data item defined with USAGE IS POINTER is a pointer data item.Cobol DATA DIVISION SYNCHRONIZED can be used with USAGE IS INDEX to obtain efficient use of the index data item. SYNCHRONIZED can be used with USAGE IS POINTER to obtain efficient use of the pointer data item. The DATE FORMAT. but. A pointer data item is a 4-byte elementary item. an ENTRY statement. The USAGE IS POINTER clause can be written at any level except level 88. if a pointer data item is part of a group.0 Page 38 of 148 . upon subsequent reading of the record containing the pointer. or the Procedure Division header. However. there is no conversion of values when the statement is executed. the address contained can no longer represent a valid pointer. Pointer data items can be part of a group that is referred to in a MOVE statement or an input/output statement. and BLANK WHEN ZERO clauses cannot be used to describe group or elementary items defined with the USAGE IS POINTER clause.

It is never required.Cobol DATA DIVISION SYNCHRONIZED [ {SYNCHRONIZED { LEFT SYNC } RIGHT } ] ♦ ♦ Specifies the alignment of an elementary item on a natural boundary in storage. but may improve performance on some systems for binary items used in arithmetic.0 Page 39 of 148 . Cognizant Academy Ver 1.

Date of Birth char 10. employee number char 10. The employee transaction file Employee number char 10. The Card file The employee number char 10. the presence of the employee record in the master file Cognizant Academy Ver 1. Department char 3. Department char 3. run date char 10 c. error description char 40 d. Employee name char 30. next 4 bytes the month and year of joining. Employee name char 30. Write Working storage entries for the following layouts The working storage variables to check the file status of each file.Cobol EXERCISES EXERCISES 1. Designation char 2. The Error file The Record number numeric 8. run date char 10 2. Date of joining char 10 b. Date of Birth char 10. Write File Section entries for the following file a. the next 4 bytes a running sequence number).0 Page 40 of 148 . Designation char 2. The employee Master file Employee number char 10 (employee number consists of first 2 chars as their initials. Date of joining char 10.

] The USING clause is optional. It is used when we need to receive data from a calling program or through JCL using LINKAGE section..Conditional . SECTIONS AND PARAS: ♦ ♦ ♦ ♦ ♦ ♦ SECTION is recognized by keyword SECTION Example MAIN-PROCESS SECTION PARAGRAPHs consist of SENTENCEs Paragraph is Identified by Para Name The scope of the section or paragraph is until the next section or paragraph starts Example READ INT91.Cobol Procedure Division 7. PROCEDURE DIVISION Now we have defined the data variables used in the program. STATEMENT is a syntactically valid combination of words and symbols beginning with a verb STATEMENT can be .Compiler Directing SENTENCE & STATEMENT: - Cognizant Academy Ver 1.0 Page 41 of 148 . 9999-READ-FILE. files used in the program.. We need to process the data available for us to produce the results. The data-name1 is the 01 levels defined in the linkage section. EXIT.Imperative . The order of the variables should be in the order in which it appears in the linkage section. Rules for SECTION/PARA Names: ♦ ♦ ♦ ♦ ♦ ♦ Must not have more than 30 characters Can contain (0-9) DIGITs. 9999-READ-FILE-EXIT. The syntax of procedure division is PROCEDURE DIVISION [USING data-name-1 . (A-Z) LETTERs & Hyphens (-) only Hyphen should be embedded SENTENCE is composed of one or more STATEMENTs.

9(8) ACCEPT . CONSOLE DATE . Mnemonic-Name is as specified in SPECIAL-NAMES Environment-Name can be SYSIN.1 TO 7 (Monday to Sunday) DAY TIME .0 Page 42 of 148 .9(1) DAY-OF-WEEK .OUTPUT VERBS ♦ ♦ The input-output verbs are used for processing datasets Displaying information to and Capturing information from the user ACCEPT ACCEPT identifier1 [ FROM { mnemonic-name environment-name DATE DAY DAY-OF-WEEK TIME } ] ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ Using SPECIAL-NAMES paragraph A mnemonic name can be assigned to each of the environment names.9(6) . Then the ACCEPT statement can be coded as ACCEPT identifier1 FROM OPERATOR. OPERATOR IS CONSOLE can be specified in SPECIAL-NAMES paragraph.YYDDD (Julian) .Example ♦ COBOL statement ACCEPT in-parm ACCEPT in-parm FROM card Cognizant Academy Ver 1.YYMMDD .9(5) . SYSIPT.Cobol Procedure Division INPUT . For instance.HHMMSShs .

[ UPON { mnemonic-name1 environment-name1}] [ WITH NO ADVANCING ] ♦ ♦ ♦ When the UPON is omitted. RECFM can be Fixed or Variable Records are read until identifier is filled or EOF reached Procedure Division DISPLAY DISPLAY { identifier1 literal1 } .Cobol ♦ JCL statement: //SYSIN DD applicable parameters ♦ ♦ ♦ LRECL of DCB parameter can be up to a max of 256. SYSOUT is the default device Mnemonic-name is as specified in SPECIAL-NAMES Environment-name can be SYSOUT.. SYSLIST. SYSPCH.. SYSPUNCH. CONSOLE DISPLAY .0 Page 43 of 148 . SYSLST.1.Example ♦ COBOL statement DISPLAY ‘Return code:’ i-ret-code DISPLAY ‘Return code:’ i-ret-code UPON SYSLIST ♦ JCL statement //SYOUT DD applicable parameters //SYLIST DD applicable parameters ♦ ♦ Default LRECL for SYSOUT is 121 and RECFM is FBA Records will be folded if length > LRECL . DISPLAY . if required Negative signed values cause a low-order sign overpunch POINTERs are converted to an external PIC 9(10) INDEX names can’t be specified Cognizant Academy Ver 1.Rules ♦ ♦ ♦ ♦ Identifier-1 is converted automatically to external format.

lit-3 } GIVING ( id-m [ ROUNDED ] ) .0 Page 44 of 148 .* / ** UNARY : + Precedence ..Exponentiation ....Addition and Subtraction ADD: ♦ ♦ Two or more numeric operands are summed up and stored Rules ...Internal Format Transformation in case of mixed usage clause Format 1 ADD { id-1 lit-1 } ..Literals should be Numeric .Cobol Procedure Division ARITHMETIC OPERATIONS ♦ ♦ ♦ BINARY : + .Elementary Numeric Items .Decimal Point Alignment . [ ON SIZE ERROR imper-stmt1 ] [ NOT ON SIZE ERROR imper-stmt2 ] [ END-ADD ] Format 2 ADD { id-1 TO { id-3 lit-1 } .Multiplication and Division .Unary . [ ON SIZE ERROR imper-stmt1 ] [ NOT ON SIZE ERROR imper-stmt2 ] [ END-ADD ] Cognizant Academy Ver 1.. TO ( id-m [ ROUNDED ] ) .

X(5). X(5).0 Page 45 of 148 .99 X(5). 02 FILLER 02 ID-NUMBER 02 FILLER 02 NAME 02 FILLER 02 DEPARTMENT 02 FILLER 02 BASIC-PAY 02 FILLER 02 DEDUCTIONS 02 FILLER 02 ALLOWANCES 02 FILLER 02 NET-PAY PIC PIC PIC PIC PIC PIC PIC PIC PIC PIC PIC PIC PIC PIC PIC PIC PIC 9(5). X(25). 02 ID-NUMBER 02 NAME 02 DEPARTMENT 02 BASIC-PAY 02 FILLER PRINT-REC. X(5). X(20). then instead of separate MOVE statements. E. 1 PAY-REC. X(5). X(20). X(5).99 1 Cognizant Academy Ver 1.99 X(5). MOVE CORRESPONDING can be used. ZZZZ. X(25). X(24). PIC ZZZZ.Cobol Procedure Division Format 3 ADD { CORRESPONDING CORR } id-1 TO id-2 [ ROUNDED ] [ ON SIZE ERROR imper-stmt1 ] [ NOT ON SIZE ERROR imper-stmt2 ] [ END-ADD ] CORRESPONDING: Quite often it is required to move some of the data item of one group to some other data item of other group. If the names of the corresponding data items are distinct then separate MOVE statements have to be used. PIC ZZZZ. But if the corresponding data items have identical names. Z(5).99.g. ZZZZ. 9999V99.

ITEM-A and ITEM-A(X). ITEM-B and ITEM-B(X). Note that ITEM-1 is valid as either identifier-1 or identifier-2. 10 ITEM-B PIC +99. 10 ITEM-E PIC 9(9) USAGE COMP.Cobol Procedure Division MOVE CORR PAY-REC TO PRINT-REC In the above example the ID-NUMBER. Then. 10 ITEM-E USAGE COMP-1. 10 ITEM-D REDEFINES ITEM-C PIC 9(4). MOVE NAME OF PAY-REC TO NAME OF PRINT-REC. 10 ITEM-A PIC S9(3). 10 ITEM-F USAGE INDEX.9. ITEM-D and ITEM-D(X) are not included because ITEM-D(X) includes a REDEFINES clause in its data description. If any of the individual operations in the ADD CORRESPONDING statement produces a size error condition. Cognizant Academy Ver 1. MOVE DEPARTMENT OF PAY-REC TO DEPARTMENT OF PRINT-REC. NAME. ITEM-F and ITEM-F(X) are not included because they are defined as USAGE IS INDEX. MOVE BASIC-PAY OF PAY-REC TO BASIC-PAY OF PRINT-REC. 10 ITEM-D PIC 9(4). 05 ITEM-2. and ITEM-E and ITEM-E(X) are considered to be corresponding and are added together. 10 ITEM-B PIC +9V9. DEPARTMENT. ADD Corresponding:For example. if two data hierarchies are defined as follows: 05 ITEM-1 OCCURS 6. 10 ITEM-C PIC A(4). 10 ITEM-A PIC 99. This is equivalent to 4 move statements MOVE ID-NUMBER OF PAY-REC TO ID-NUMBER OF PRINT-REC. if ADD CORR ITEM-2 TO ITEM-1(X) is specified. BASIC-PAY of PAY-REC will be moved the same data item of PRINT-REC. imperative-statement-1 in the ON SIZE ERROR phrase is not executed until all of the individual additions are completed.0 Page 46 of 148 . 10 ITEM-C PIC X(4). 10 ITEM-F USAGE INDEX. ITEM-C and ITEM-C(X) are not included because they are not numeric.

the imperative statement in the ON SIZE ERROR phrase is executed.0 Page 47 of 148 . the NOT ON SIZE ERROR phrase is executed. a size error condition does not exist. if specified. the number of places in the fraction of the result of an arithmetic operation is compared with the number of places provided for the fraction of the resultant identifier. ♦ ♦ If the NOT ON SIZE ERROR phrase has been specified and. control is transferred to the end of the arithmetic statement. ♦ If the ROUNDED phrase is specified. Cognizant Academy Ver 1. is ignored. After completion of the execution of the arithmetic operation.Cobol Procedure Division ON SIZE ERROR Occurs ♦ ♦ ♦ When the absolute value of the result of an arithmetic evaluation. after execution of an arithmetic operation. ROUNDED Phrase ♦ After decimal point alignment. the value of the resultant identifier affected by the size error is not altered--that is. the ON SIZE ERROR imperative statement is not executed until all the individual additions or subtractions have been completed. if an individual arithmetic operation causes a size error condition. the error results are not placed in the receiving identifier. and the NOT ON SIZE ERROR phrase. rounding takes place before size error checking. exceeds the largest value that can be contained in the result field When division by zero occurs If the ON SIZE ERROR phrase is specified and a size error condition occurs. For ADD CORRESPONDING and SUBTRACT CORRESPONDING statements. after decimal point alignment.

C. D TO E GIVING X. Z ADD A . C ADD A TO B ROUNDED C ROUNDED ADD A TO B ROUNDED . 05 X-2 PIC 9(3) VALUE 2. X-2 = 11. truncation occurs unless ROUNDED is specified. C ON SIZE ERROR MOVE 1 TO ERR-FLAG ♦ ♦ ADD A. Y Add CORR X to Y (Example) 01 X. 05 X-1 PIC 9(5) VALUE 5. B. the least significant digit of the resultant identifier is increased by 1 whenever the most significant digit of the excess is greater than or equal to 5. When ROUNDED is specified.Cobol ♦ Procedure Division When the size of the fractional result exceeds the number of places provided for its storage. 05 X-3 PIC 9(5) VALUE 12. D TO X. ADD – Examples ♦ ♦ ♦ ♦ ♦ ♦ ADD A TO B ADD 1 TO B ADD A TO B ROUNDED ADD A TO B. C. Under group Y: X-1 = 6. X-3 = 15 SUBTRACT ♦ ♦ ♦ To subtract one or the sum of two or more numeric items from one or more items and set the values of one or more items to the result Valid only for Numeric Items Automatic Decimal Alignment Cognizant Academy Ver 1. Y. 05 X-3 PIC 9(3) VALUE 3. 05 X-2 PIC 9(5) VALUE 9. 01 Y. 05 X-1 PIC 9(3) VALUE 1.0 Page 48 of 148 . After Add. B.

Cobol Procedure Division SUBTRACT { id-1 lit-1 } . FROM ( id-m [ ROUNDED ] ) ...... FROM { id-2 lit-2 } GIVING ( id-m [ ROUNDED ] ) ..0 Page 49 of 148 ... [ ON SIZE ERROR imper-stmt1 ] [ NOT ON SIZE ERROR imper-stmt2 ] [ END-SUBTRACT ] SUBTRACT { id-1 lit-1 } . [ ON SIZE ERROR imper-stmt1 ] [ NOT ON SIZE ERROR imper-stmt2 ] [ END-SUBTRACT ] SUBTRACT { CORRESPONDING CORR } id-1 FROM id-2 [ ROUNDED ] [ ON SIZE ERROR imper-stmt1 ] [ NOT ON SIZE ERROR [ END-SUBTRACT ] SUBTRACT – Examples ♦ SUBTRACT 1 FROM A ♦ SUBTRACT A FROM B ♦ SUBTRACT A B FROM C D ♦ SUBTRACT A B FROM C GIVING D ♦ SUBTRACT A FROM B GIVING CROUNDED ♦ SUBTRACT A FROM B ON SIZE ERROR MOVE 1 TO ERROR-FLAG imper-stmt2 Cognizant Academy Ver 1.

.. [ ON SIZE ERROR imper-stmt1 ] [ NOT ON SIZE ERROR imperative-stmt2 ] [ END-MULTIPLY ] MULTIPLY .Examples ♦ ♦ ♦ ♦ ♦ ♦ MULTIPLY 5 BY A MULTIPLY 5 BY A ROUNDED MULTIPLY A BY B MULTIPLY A BY B GIVING C D MULTIPLY A BY B ON SIZE ERROR MULTIPLY A BY B GIVING C ON SIZE ERROR MOVE 1 TO ERROR-FLAG MOVE 1 TO ERROR-FLAG Cognizant Academy Ver 1..Cobol Procedure Division MULTIPLY MULTIPLY { id-1 lit-1 } BY ( id-2 [ ROUNDED ] ) ..0 Page 50 of 148 . [ ON SIZE ERROR imper-stmt1 ] [ NOT ON SIZE ERROR imperative-stmt2 ] [ END-MULTIPLY ] MULTIPLY { id-1 BY id-2 lit-1 } GIVING id-3 ( [ ROUNDED ] ) .

.1 DIVIDE . [ ON SIZE ERROR imper-stmt1 ] [ NOT ON SIZE ERROR imperative-stmt2 ] [ END-DIVIDE ] BEFORE A B C DIVIDE A INTO B DIVIDE A INTO B ROUNDED DIVIDE A INTO B C DIVIDE A INTO B GIVING C DIVIDE 2 INTO A GIVING B C DIVIDE A BY B GIVING C DIVIDE A BY 5 GIVING B REMAINDER C Table 7. [ ON SIZE ERROR imper-stmt1 ] [ NOT ON SIZE ERROR imperative-stmt2 ] [ END-DIVIDE ] DIVIDE { id-1 {BY { id-2 lit-1 } INTO} lit-2 } GIVING ( id-3 [ ROUNDED ] ) .Cobol Procedure Division DIVIDE DIVIDE { id-1 INTO lit-1 } ( id-2 [ ROUNDED ] ) .0 Page 51 of 148 ..Examples 2 2 2 2 2 6 8 10 9 10 10 2 14 AFTER A B 2 2 2 2 2 6 8 5 5 5 10 1 2 1 C 7 5 1 3 3 Cognizant Academy Ver 1...

. COMPUTE A =B+C*2.0 Page 52 of 148 . Cognizant Academy Ver 1. Data Names & Literals .Shortens Programs .Made up of Operators.Avoids Intermediate data names ♦ EXPRESSIONS ..COST.More than one operation in a single statement .Cobol Procedure Division COMPUTE ♦ COMPUTE . = arithmetic-expression [ ON SIZE ERROR imper-stmt1 ] [ NOT ON SIZE ERROR imperative-stmt2 ] [ END-COMPUTE ] ♦ Examples COMPUTE PROFIT = PRICE .Operators evaluated based on parenthesis and/or precedence COMPUTE id-1 [ ROUNDED ] [ id-2 [ ROUNDED ] ] .

B= 9999.96. 01 C PIC S9(5). 01 VAL-3 PIC 9(5)V99 VALUE 11. A field named NAME contains 40 characters. E. ADD VAL-2.VAL-4 after executing the following statement a.45. C.VAL-3. 01 B PIC 9(5)V99. DIVIDE VAL-3 INTO VAL-4 GIVING VAL-3 ROUNDED MULITPLY VAL-4 BY VALI-1 GIVING VAL-4 ON SIZE ERROR MOVE 1 TO VAL-4 3. What will be the result of the following compute statement 01 A PIC S9(3)V99. b.301.988 COMPUTE A ROUNDED = 999. COMPUTE A = 999. VAL-4 GIVIGN VAL-3 ON SIZE ERROR MOVE ZERO TO VAL-3. A = 1. 01 VAL-4 PIC 9999 VALUE 300.555.5 ON SIZE ERROR MOVE 1 TO B. B.VAL-2.3.0 Page 53 of 148 . D. A field name STRING-1 contains 80 chars.985 COMPUTE B = 8888. What will be contained in VAL-1. 01 VAL-2 PIC 9(5)V999 VALUE 99008. A. D.0 * 4425.25 + 99.99 C = -11115. 01 VAL-1 PIC 999V99 VALUE 999. C. Write the cobol statement to find the number of words in STRING-1 and the length of the individual words 1.Cobol Exercises EXERCISES 1. Write a COBOL statement to change all instances of “MR.5 / 5. The char (/) or (. VAL-2 GIVING VAL-3 ON SIZE ERROR MOVE ZERO TO VAL-3.50 / 5.) is used to indicate the end of a word within these 80 chars. ADD VAL-1. COMPUTE B ROUNDED = C * A COMPUTE B ROUNDED = C ROUNDED * A ROUNDED 4.” by “SRI” and “MRS” by “SMT” Cognizant Academy Ver 1.

COMPUTE TOTAL = AMT-1 + AMT-2 What value will be present in TOTAL. 02 NAME PIC X(20). 02 TOTAL PIC 9(6)V99.Cobol Exercises 2. MOVE 2000 TO AMT-2. INITIALIZE WS-REC-1 REPLACING NUMERIC BY 1000. Cognizant Academy Ver 1. INITIALIZE WS-REC-1. 02 AMT-2 PIC 9(5)V99. 02 AMT-1 PIC 9(5)V99. What will be present after the execution of following statement 1 WS-REC-1.0 Page 54 of 148 .

literal.00 12 +12 are all equal [NOT] > [NOT] < [NOT] = >= <= ♦ For Numeric operands the comparison is algebraic Cognizant Academy Ver 1. Control Flow Verbs CONDITIONAL EXPRESSIONS ♦ Types . operand-2 can be an identifier. Relational Operators Expression IS [NOT] GREATER THAN IS [NOT] LESS THAN IS [NOT] EQUAL TO IS GREATER THAN OR EQUAL TO IS LESS THAN OR EQUAL TO ♦ Example: 012 12. index-name or a pointer.Cobol Control Flow Verbs 8.Relation .Sign .Class . Operands can be an Identifier. arithmetic expression.Condition name ♦ Cause the processing to select between alternate paths depending on the truth value of the expression RELATION OPERATORS ♦ ♦ ♦ ♦ Causes a comparison of two operands. Literal or Arithmetic Syntax operand-1 relop operand-2 Operand-1.0 Page 55 of 148 .

0 Page 56 of 148 .Cobol Control Flow Verbs ♦ Comparison permitted regardless of Usage NON-NUMERIC OPERANDS OR ONE NUMERIC & ONE NON-NUMERIC ♦ ♦ ♦ ♦ ♦ Comparison is made as per the collating sequence If both operands’ Usage are same and relational operator = or NOT = no conversion All other comparison operands with Usage other than display are converted to display Comparison starts from left most character For operands size unequal the comparison proceeds as if the shorter operand had been padded by blanks on the right ♦ Example l-A “JOES” l-B “JOE“ taken as “JOE “ l-A > l-B is TRUE CLASS CONDITION ♦ ♦ ♦ ♦ ♦ Numeric or Alphabetic or user defined class-name check of the operand Numeric test cannot be done for an item declared as alphabetic (PIC A) Alphabetic test cannot be done for item declared as Numeric (PIC 9) Packed-decimal allowed for Numeric test Syntax IF id-1 IS [ NOT ] {NUMERIC ALPHABETIC ALPHABETIC-LOWER ALPHABETIC-UPPER class-name } SIGN CONDITION operand-1 IS [ NOT ] {POSITIVE NEGATIVE ZERO } ♦ ♦ Determines whether algebraic value is less than greater than or equal to zero operand-1 must be a numeric identifier. or arithmetic containing at least one reference to a variable Cognizant Academy Ver 1.

0 Page 57 of 148 . Conditional expression Examples IF ASSOC-AGE > 80 SET SENIOR-ASSOC TO TRUE END-IF IF ASSOC-SAL IS POSITIVE SET DEBIT-AMOUNT TO TRUE END-IF COMPLEX CONDITIONS ♦ Formed by .Logical Connectives ♦ Logical Operators .Abbreviating conditions .Used to combine simple conditions . Syntax : condition-name-1 with the condition-name.Nested IFs .Logical Inclusive .Logical Negation .Logical Conjunction Cognizant Academy Ver 1.Cobol Control Flow Verbs Condition Name ♦ ♦ ♦ ♦ It is a subset of relational condition It tests a conditional variable to determine whether its value is equal to any value(s) associated condition-name is used in conditions as an abbreviation for the relation condition.Combining simple conditions .For negation LOGICAL OPERATORS ♦ ♦ ♦ NOT OR AND .

OR ♦ If a condition is put in parenthesis.Arithmetic Expression .Cobol Control Flow Verbs EVALUATION RULES ♦ Precedence . it is evaluated and its truth value depends on the truth value of its constituents ABBREVIATED COMPOUND CONDITIONS IF A = B AND A = C is same as IF A = B AND = C ♦ relational conditions IF A = B AND A = C is same as IF A = B AND C ♦ ♦ Here identical subjects and relational operators are omitted in a As indicated in the examples compound conditions can be consecutive sequence of relational conditions abbreviated by having implied subjects. The GO TO statement has four formats: Cognizant Academy Ver 1. or.NOT . Here identical subjects are omitted in a consecutive sequence of ♦ A > B OR NOT C OR D Examples = (A>B) OR NOT (A>C) OR (A>D) A > B OR NOT C OR NOT < D = (A>B) OR (A NOT > C) OR (A NOT< D) GO TO The GO TO statement transfers control from one part of the Procedure Division to another.All Relational Operators .AND .0 Page 58 of 148 . implied subjects and relational operators.

Example:IF NOT NUMERIC GO TO 999-ERR-PARA.Cobol Control Flow Verbs Unconditional GO TO: The unconditional GO TO statement transfers control to the first statement in the paragraph or section named in procedure-name The Syntax of the GO TO statement is GO TO procedure-name-1 procedure-name-1 Must name a procedure or a section in the same Procedure Division as the GO TO statement. must be the last statement in the sequence. when it appears in a sequence of imperative statements. Cognizant Academy Ver 1. The number of procedure-names must not exceed 255.0 Page 59 of 148 . control is transferred to the first statement in the procedure named by the second occurrence of procedure-name-1. control is transferred to the first statement in the procedure named by the first occurrence of procedure-name-1 If equal to 2. An unconditional GO TO statement. procedure-name-1 Must be a procedure or a section in the same Procedure Division as the GO TO statement. If equal to 1. Conditional GO TO: GO TO proc-name-1 DEPENDING ON int-1 The conditional GO TO statement transfers control to one of a series of procedures. depending on the value of the identifier. and so forth. which is an integer. identifier-1 Must be a numeric elementary data item.

120-REC-PARA WS-INT-1 = 3.Watch out ♦ Is an obsolete element and encourages the use of unstructured programming practices. 100-HDR-PARA WS-INT-1 = 2. The EVALUATE statement provides similar functionality Cognizant Academy Ver 1. ALTER procedure-name-1 TO PROCEED TO procedure-name-2 ♦ procedure-name-1 must be that contains only one sentence: a GO TO without the DEPENDING ON phrase ALTER . control passes to the next statement in the normal sequence of execution. no control transfer occurs.0 Page 60 of 148 .Cobol Control Flow Verbs If the value of identifier is anything other than a value within the range of 1 through n (where n is the number of procedure-names specified in this GO TO statement). Instead. it will be deleted from the next revision of the COBOL 85 Standard. 130-TRILER-PARA ALTER ♦ ♦ Changes the transfer point specified in a GO TO statement The altered GO TO statement transfers control to the first statement of the paragraph named in the ALTER statement. Example: GO TO 100-HDR-PARA 120-REC-PARA 130-TRILER-PARA DEPENDING ON WS-INT-1 When WS-INT-1 = 1.

GO TO A1-FIRST-TIME. A1-PARA..Example PROCEDURE DIVISION. IF IF condition-1 THEN { statement-1 ... NEXT SENTENCE ] ] [ END-IF ] ♦ next separator period ♦ good programming practice Never use NEXT SENTENCE and Period as IF terminator.0 Page 61 of 148 . GO TO .. INIT W-REC-COUNTER. .. A1-FIRST-TIME.. A1-NEXT-TIME. Cognizant Academy Ver 1. ALTER A1-PARA TO A1-NEXT-TIME.. NEXT SENTENCE } [ ELSE [ statement-2 ..Cobol Control Flow Verbs ALTER . . It is not a NEXT SENTENCE means execution should move to stmt after the statement-1..... is a GO TO form for ALTER and can be used in the above instead of GO TO A1FIRST-TIME.. statement-2 Can be any one of the following: An imperative statement A conditional statement An imperative statement followed by a conditional statement.

0 Page 62 of 148 . It has no effect on the execution of the program. CONTINUE .Cobol Control Flow Verbs EXAMPLE: IF (WS-NT91-CLT NOT EQUAL ‘99999’) AND WS-NT91-SEQ NOT NUMERIC Statements 1 ELSE Statement 2 END-IF Using conditional-names: IF C08W-ERR-OPEN-FLAG GO TO 999-ERR-OPEN-PARA END-IF CONTINUE ♦ Allows you to specify a no operation statement.Example IF YEAR-IS-NOT-LEAP CONTINUE ELSE ADD 1 TO NO-OF-FEB-DAYS END-IF ♦ The above IF usage is preferred compared to IF NOT given below: IF NOT YEAR-IS-NOT-LEAP ADD 1 TO NO-OF-FEB-DAYS END-IF Cognizant Academy Ver 1. ♦ Syntax : CONTINUE ♦ It can be used anywhere a conditional statement or an imperative statement can be used. It indicates that no executable instruction is present.

This comparison proceeds as follows: Cognizant Academy Ver 1. ♦ Provides better readability. That is. ♦ When a satisfiable WHEN is met. ♦ It can evaluate multiple conditions. a range of numeric or nonnumeric values. the IF statements can be made up of compound conditions.0 Page 63 of 148 . processing breaks off from the rest of the evaluate block EVALUATE subject-1 [ALSO subject-2] {{WHEN object-1 [ALSO object-2] imperative-statement-1 ] [WHEN OTHER imperative-statement-2] [ END-EVALUATE Where a subject is { Int-1 Literal –1 Expression TRUE FALSE} And an Object is { ANY condition-1 TRUE FALSE [NOT] { identifier-3 [ { THROUGH literal-3 THRU } { identifier-4 arith-exp-1} literal-4 arith-expr-2} ] } ♦ The execution of the EVALUATE statement operates as if each selection subject and selection object were evaluated and assigned a numeric or nonnumeric value.Cobol Control Flow Verbs EVALUATE ♦ Provides a shorthand notation for a series of nested IF statements. or a truth value ♦ The execution of the EVALUATE statement then proceeds as if the values assigned to the selection subjects and selection objects were compared to determine whether any WHEN phrase satisfies the set of selection subjects.

If the items being compared are assigned numeric or nonnumeric values. subjects.0 Page 64 of 148 . If the selection object being compared is specified by the word ANY. that set of selection objects does not satisfy the set of selection appearance in the source program.Cobol Control Flow Verbs 1. b. or one value in the range of values. the WHEN phrase containing that set of selection objects is selected as the one satisfying the set of selection subjects. c. If the items being compared are assigned truth-values. One of the following conditions must be satisfied if the comparison is to be satisfied: a. assigned to the selection object is equal to the value assigned to the selection subject. the comparison is always satisfied. 4. the comparison is satisfied if the items are assigned identical truth-values. regardless of the value of the selection subject. Cognizant Academy Ver 1. If the above comparison is satisfied for every selection object within the set of selection objects being compared. 2. Each selection object within the set of selection objects for the first WHEN phrase is compared to the selection subject having the same ordinal position within the set of selection subjects. according to the rules for comparison. 3. the comparison is satisfied if the value. or a range of numeric or nonnumeric values. This procedure is repeated for subsequent sets of selection objects in the order of their If the above comparison is not satisfied for every selection object within the set of selection objects being compared. until either a WHEN phrase satisfying the set of selection subjects is selected or until all sets of selection objects are exhausted.

Depending on these values the control passes to the corresponding WHEN. the subject is TRUTH value. Depending on the values the WHEN phrase satisfying the TRUTH value is executed. An out-of-line PERFORM statement (Procedure-name-1 is specified). Cognizant Academy Ver 1.Cobol Control Flow Verbs Example 1 EVALUATE proc-type ALSO cust-type WHEN 1 ALSO 1 MOVE 1 TO RESULT WHEN 3 ALSO 1 THRU 2 MOVE 2 TO RESULT WHEN 2 ALSO 1 MOVE 3 TO RESULT WHEN OTHER MOVE 0 TO RESULT END-EVALUATE In this example subject of Evaluation is an Expression. Example 2 EVALUATE TRUE WHEN l-VALUE < 100 MOVE 1 TO RESULT WHEN l-VALUE < 1000 MOVE 2 TO RESULT WHEN l-VALUE < 10000 WHEN OTHER MOVE 0 TO RESULT END-EVALUATE In this example. If a WHEN does not have a associated imperative statement it is a do-nothing condition (same as coding CONTINUE) PERFORM ♦ ♦ ♦ The PERFORM statement transfers control explicitly to one or more procedures and implicitly returns control to the next executable statement after execution of the specified procedure(s) is completed. An in-line PERFORM statement must be delimited by the END-PERFORM phrase.0 Page 65 of 148 . An in-line PERFORM statement (Procedure-name-1 is omitted).

Overlap Rules ♦ When the performed procedures executes another PERFORM the procedures associated with the 2nd level PERFORM must be totally included in or totally excluded from the procedures of the first level PERFORM statement. if procedurename-1 is specified. imperative-statement-1 and the END-PERFORM phrase must not be specified. This perform is called inline perform statements which does not contain any section name or paragraph name. For example. ♦ ♦ ♦ Executes group of consecutive statements written inline (called INLINE PERFORM) or elsewhere Has four formats Departs from normal sequence of execution and implicit return to next statement after completion (called OUT-OF-LINE PERFORM) in a program PERFORM (Basic) PERFORM { proc-name1[{ THRU proc-name2 THROUGH } ] imp-statement-1 END-PERFORM } ♦ Example 1 (Out-of-line) PERFORM PARA-1 THRU PARA-2 In this example the execution of PERFORM statement will start with execution of first statement in PARA-1 and ends with execution of last statement in PARA-2.Cobol ♦ Control Flow Verbs The in-line and out-of-line PERFORM statements cannot be combined. This transfer of control occurs implicitly ♦ Example 2 (Inline) PERFORM MOVE 1 TO FLAG-1 MOVE 2 TO FLAG-2 END-PERFORM In the above example the control is not transferred anywhere. This perform statement should end with an END-PERFORM statement PERFORM . Cognizant Academy Ver 1. All the paragraphs in between these 2 paragraphs will be executed. And then control returns to the statement next to the perform statement. This will execute the statements within the perform statement.0 Page 66 of 148 .

Rules ♦ ♦ Once the perform statement is initiated any changes to the id-1 will have no effect on the nbr of If identifier-1 is zero or a negative number at the time the PERFORM statement is initiated. It depends on value of the variable I-CNT. If I-CNT is 0 or negative. PERFORM I-CNT TIMES WRITE OUT-REC FROM I-ERR-REC (I-CNT) SUBTRACT 1 FROM I-CNT END-PERFORM In this example the number of times the perform statement is to be executed is not predetermined.Cobol ♦ Two or more such active PERFORM must not have a common exit. Control Flow Verbs PERFORM (TIMES option) PERFORM { proc-name1 [THRU proc-name2] { id-1 TIMES int-1} { id-1 init-1 } TIMES imp-stmt-1 END-PERFORM } PERFORM (TIMES option) .0 Page 67 of 148 . this perform statement is not all executed PERFORM (UNTIL option) PERFORM { proc-name1[THRU proc-name2] until-phrase imp-statement-1 until-phrase END-PERFORM } Cognizant Academy Ver 1. Hence this perform statement will be executed 10 times. control times the para is to be executed passes to the statement following the PERFORM statement. PERFORM (TIMES) Example PERFORM B1-PROCESS THRU B1-PROCESS-EXIT 10 TIMES In this example the number of times perform statement is going to be executed is predetermined.

If neither the TEST BEFORE nor the TEST AFTER phrase is specified. ♦ In either case.1 Flow chart for Perform. If the TEST AFTER phrase is specified. Ente r True Condition EXI T False Executable statements in the perform paragraph Fig 8. control is transferred to the next executable statement following the end of the PERFORM statement. Control is then passed to the next executable statement following the PERFORM statement. ♦ ♦ Here the condition is tested before only at the beginning of each execution by default But this default is overridden by TEST AFTER phrase.. the TEST BEFORE phrase is assumed. the statements to be performed are executed at least once before the condition is tested (corresponds to DO UNTIL). if the condition is true. the procedure(s) referred to are performed until the condition specified by the UNTIL phrase is true.Until Cognizant Academy Ver 1.0 Page 68 of 148 .Cobol Control Flow Verbs ♦ until-phrase UNTIL condition WITH TEST { BEFORE AFTER } ] ♦ In the UNTIL phrase format.

. the WRITE and SUBTRACT statements will be executed until the I-CNT becomes zero.Cobol Control Flow Verbs PERFORM (UNTIL) Example MOVE 10 TO I-CNT PERFORM UNTIL I-CNT = ZERO WRITE OUT-REC FROM I-ERR-REC (I-CNT) SUBTRACT 1 FROM I-CNT END-PERFORM In the above example.. Cognizant Academy Ver 1. the subscript or reference-modifier is evaluated each time the condition is tested. ♦ ♦ After-phrase provides for varying more than one identifier If any of the operands specified in cond-1 or cond-2 is subscripted or reference modified.0 Page 69 of 148 . PERFORM (VARYING) PERFORM { proc-name1[THRU proc-name2] varying-phrase after-phrase varying-phrase imp-stmt-1 END-PERFORM } ♦ varying-phrase [ WITH TEST {BEFORE AFTER } ] VARYING { id-1 FROM { id-2 lit-1 Inx-nm1 } inx-nm-2} BY { id-3 UNTIL cond-1 lit-2 } ♦ after-phrase ( AFTER { id-4 FROM { id-5 lit-1 inx-nm1 } inx-nm-2} BY { id-6 UNTIL cond-2 lit-2 } ) . Here perform will be executed 10 times.

0 Page 70 of 148 . ♦ EXAMPLE:PERFORM PROC1 THRU PROC2 VARYING I FROM 1 BY 1 UNTIL I > 50 AFTER J FROM 1 BY 1 UNTIL J > 10 In the above example the PROC-1 to PROC-2 will be executed 500 times. Thus after this perform statement is executed. First with I as 1 and J varying from 1 to 10 in step of 1. Each time the loop varying J is completed. the statements to be performed are executed at least once. J is initialized before changing the value of I. and BY phrases during execution changes the number of times the procedures are executed. J must vary from 1 to 10. Every time I changes value. all specified conditions are tested before the first execution. if at all. Cognizant Academy Ver 1. When TEST AFTER is indicated. value of I will 51 and that of J will 1 and not 11. FROM. ♦ Changing the values of identifiers and/or index-names in the VARYING. then I as 2 and again J varying from 1 to 10 and so on. before any condition is tested. and the statements to be performed are executed. only when all specified tests fail.Cobol ♦ Control Flow Verbs When TEST BEFORE is indicated.

0 Page 71 of 148 .Cobol Control Flow Verbs Ente r Set Identifier-1 to initial value True Cond1 Exi t False Execute the imperative statement in the perform paragraph Add increment to indentifier-1 Figure 8.2 Flow Chart for Perform…varying… TEST BEFORE Cognizant Academy Ver 1.

with TEST BEFORE Cognizant Academy Ver 1.0 Page 72 of 148 .3 Flow Chart for Perform…varying….After….Cobol Ente r Control Flow Verbs Set Id-1 & id-4 to their respective initial values True Cond1 Exi t False True Cond2 False Execute the imperative statement in the perform paragraph Add increment (id-6) to id-4 Set id-4 to initial value Add increment (id-3) to id-1 Figure 8.

ADD 1 TO A. ....Cobol Control Flow Verbs EXIT ♦ ♦ ♦ ♦ ♦ ♦ Provides a return mechanism for the Perform statement having Exit para as the last paragraph The EXIT statement provides a common end point for a series of paragraph.. IF NOT-VALID-ACTION PERFORM B1-PROCESS-EXIT .Example PROCEDURE DIVISION... B1-PROCESS. Must be preceded by a paragraph name Must be the only statement in the paragraph Falls thru if there is no associated Perform Provides a common exit point for a series of paragraphs (by executing a GO TO PARA-EXIT in the paragraph) EXIT .0 Page 73 of 148 . PERFORM B1-PROCESS UNTIL A > 5. Cognizant Academy Ver 1.... B1-PROCESS-EXIT EXIT. . ….

then rate of interest is 9. If the account code is 120. then rate of interest is 11.5% for all other account codes the rate of interest is 4. Rewrite the following IF statement-using condition names. if the account-code is 130. then the rate of interest is 10 % . Write the evaluate statement for the following When the account code is 100. The following is the information about the patient file Description Name Sex Age Height Weight Length 30 1 (Male – M. Cognizant Academy Ver 1.0 Page 74 of 148 . If the account code is 110. rate of interest is 12%. Female .5%.5%.Cobol Exercises EXERCISES 1. Write the necessary IF statement using suitable condition names. Also indicate how the condition names are to be defined in the DATA DIVISION. IF MARKS >= 90 MOVE “O” TO GRADE ELSE IF MARKS >= 75 MOVE ‘E’ TO GRADE ELSE IF MARKS >= 60 MOVE ‘D’ TO GRADE ELSE IF MARKS >= 50 MOVE ‘C’ TO GRADE ELSE IF MARKS NOT > 40 MOVE ‘B’ TO GRADE ELSE MOVE ‘F’ TO GRADE 2.F) 3 5 with 2 decimal places 3 A paragraph named PROCESS-PARA needs to be executed only if the patient is Male whose age is between 25 and 45 yrs and Height is 160 – 175 cms and weight is 60 – 75 kgs. Also write the record description entry for the patient file 3.

. that character is not moved. or deediting implied by. Alphanumeric or Alphanumeric-Edited: ♦ An elementary move is one in which the receiving item is an elementary item. the receiving item. and the size of the sending item is considered to be 1 less character than the actual size. excess characters on the right are truncated after the receiving item is filled..INITIALIZE Manipulate addresses with pointer data items . If the sending item has an operational sign. If the operational sign occupies a separate character. along with any specified editing in.MOVE Count and replace data items . Cognizant Academy Ver 1.Cobol Non-Numeric Data Manipulation 9.SET Group moves Elementary moves Move corresponding Format conversion for numeric data types Sub-string operation (Move by reference) Data Movement and Sub-string Handling ♦ ♦ ♦ ♦ ♦ MOVE MOVE { id-1 TO id-2 .INSPECT Join data items . and the sending item is an elementary item or a literal. the unsigned value is used.STRING Split data items .0 Page 75 of 148 . lit-1 } ♦ ♦ All identifiers can be either group or elementary items.UNSTRING Initialize variables . The data in the sending item is moved into the data item referenced by each identifier-2 in the order in which it is specified. Any necessary conversion of data from one form of internal representation to another takes place during the move. Non-Numeric Data manipulation ♦ ♦ ♦ ♦ ♦ ♦ Move data items . ♦ ♦ If the size of the sending item is greater than the size of the receiving item.

MOVE {CORRESPONDING CORR} id-1 TO id-2 ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ Both identifiers must be group items Both identifiers following the keyword CORRESPONDING must name group items. A pair of data items (subordinate items). When the sending item is floating-point. the data is moved as if the sending item were described as an unsigned integer. they can contain or be subordinate to items containing a REDEFINES or OCCURS clause in their descriptions. When the sending item is alphanumeric. these identifiers are referred to as identifier-1 and identifier-2. and no operational sign is generated for the receiving item. However. the data is first converted to either a binary or internal decimal representation and is then moved. or USAGE IS INDEX clause in their descriptions. In this discussion.0 Page 76 of 148 . at least one of the data items is an elementary item. Valid and Invalid Elementary Moves Cognizant Academy Ver 1. or 88 item. correspond if the following conditions are true: In a MOVE statement. Identifier-1 and/or identifier-2 can be subordinate to a FILLER item. OCCURS. The subordinate items do not include a REDEFINES. If the sending item is unsigned. Neither identifier-1 nor identifier-2 can be reference-modified. RENAMES. a positive operational sign is generated for the receiving item. Neither identifier-1 nor identifier-2 is described as a level 66. De-editing allows moving a numeric-edited data item into a numeric or numeric-edited receiver. and the move is permitted by the move rules. the sign of the sending item is placed in the receiving item. with any necessary sign conversion. the absolute value of the sending item is moved. one from identifier-1 and one from identifier-2. The subordinate items are not identified by the keyword FILLER. ♦ ♦ ♦ ♦ If the receiving item is unsigned.Cobol Non-Numeric Data Manipulation Numeric or Numeric-edited: ♦ If the receiving item is signed. The compiler accomplishes this by first establishing the unedited value of the numeric-edited item (this value can be signed). Neither identifier-1 nor identifier-2 nor the two subordinate items are described as USAGE IS POINTER items. identifier-1 and identifier-2. 77. then moving the unedited numeric value to the receiving numeric or numericedited data item. nor is either described as a USAGE IS INDEX item.

Includes DBCS data-items.2 Valid Sending and Receiving datatypes of move statement 1. 8. 6.142). Includes non-integer numeric literals (for example. 4.Cobol Non-Numeric Data Manipulation Sending Item Alphabetic and SPACE Alphanume ric(2) Alphanume ric-Edited Numeric Integer and ZERO(5) Numeric Noninteger(6) NumericEdited Alphab etic Yes Yes Yes No No No Aplhanu meric Yes Yes Yes Yes No Yes Receiving Item Alpha Numeric numeric Edited Yes No Yes Yes Yes No Yes Yes(3) No Yes Yes Yes Numeric Edited No Yes(3) No Yes Yes Yes Table 8. external floating-point data items (USAGE DISPLAY). Includes floating-point literals. and SPACE. 2. Figurative constants and nonnumeric literals must consist only of numeric characters and will be treated as numeric integer fields.0 Page 77 of 148 . Cognizant Academy Ver 1. Includes integer numeric literals. 3. Includes nonnumeric literals. 3. Includes DBCS data items. DBCS literals. and internal floating-point data items (USAGE COMP-1 or USAGE COMP-2). Figurative constants and nonnumeric literals must consist only of numeric characters and will be treated as numeric integer fields. 5. The ALL literal cannot be used as a sending item. 7.

will be equal to the number of characters in data-name-1 plus one minus leftmost-characterposition.Reference modification ♦ ♦ ♦ Reference modification defines a data item by specifying a leftmost character and optional length for the data item. 77 first-name pic x(10). Reference modification evaluation .Cobol Non-Numeric Data Manipulation Move . 77 last-name pic x(15).In MOVE CORR . Sub-string.0 Page 78 of 148 . than the length used or equal to the number of characters in data-name-1.must be an arithmetic expression. ♦ Example 77 name pic x(25).For each target variable before the move • MOVE a(b) TO b. Syntax is Dataname-1(character position:length) Leftmost-character-position: .ignored Length.Rules ♦ ♦ TO first-name TO last-name Pointer and Index variables not allowed . MOVE name(1:10) MOVE name(11:) Move .before the move to the 1st target variable . The evaluation of length must result in a positive nonzero integer. The sum of leftmost-character-position and length minus the value one must be less than If length is omitted.For source variable only once . ♦ length ♦ ♦ Must be an arithmetic expression.When not in same group • • ODO object value decides the length Set value prior to MOVE Cognizant Academy Ver 1. The evaluation of leftmostcharacter-position must result in a positive nonzero integer that is less than or equal to the number of characters in the data item referenced by data-name-1. c(b) ♦ Occurs depending on Clause object (ODO) location .

Cobol .Updating ODO object with complex structures INITIALIZE ♦ ♦ ♦ Sets selected categories of data fields to predetermined values. Z(3)9.When in same group • • When no non-subordinate When there are non-subordinates Non-Numeric Data Manipulation . In the above statement A1 and A3 will be initialized to zeroes and A2 and A4 will be initialized to spaces.. It is functionally equivalent to one or more MOVE Can be at .Group level .99. ♦ When id-1 specifies a group item only those items that belong to the category denoted by the REPLACING phrase will be initialized by the value denoted by id-2/lit-1 ♦ Example 01 A. ♦ ♦ Filler will not be affected by INITIALIZE statements If any group denoted by id-1 contains a data item described with REDEFINES clause. INITIALIZE A REPLACING NUMERIC DATA BY 50 In the above example on A1 and A3 will be initialized to 50. then the data items sub ordinate to it will not be initialised. 02 02 02 02 A1 A2 A3 A4 PIC PIC PIC PIC 9(5). X(4).Elementary level INITIALIZE ( id-1 [REPLACING {ALPHABETIC ALPHANUMERIC DATA NUMERIC ALPHANUMERIC-EDITED NUMERIC-EDITED } BY {id-2 lit-1 }] ) . Cognizant Academy Ver 1.0 Page 79 of 148 . 9(3). INITIALIZE A..

02 B REDEFINES A2. with the following Cognizant Academy Ver 1. 03 B2 PIC 9(4)V99. ♦ ♦ Same Category can’t be repeated If the REPLACING phrase is specified: ♦ ♦ ♦ If identifier-1 references a group item. all operations are performed as if a series of MOVE statements had been written. are by identifier-1 is initialized only if it belongs to the category specified in the REPLACING phrase. INITIALIZE A In the above example A1 will be zeroes A2 will be filled with spaces and not zeroes. 02 A2 PIC X(10).Rules ♦ ♦ Category of Id-2 should be compatible that of CORR REPLACING Whether identifier-1 references an elementary or group item. INITIALIZE B This will fill B1 and B2 with zeroes INITIALIZE .0 Page 80 of 148 . each of which had an elementary item as a receiving field. any elementary item within the data item referenced If identifier-1 references an elementary item. that item is initialized only if it belongs to the table items within the group. category specified in the REPLACING phrase. 03 B1 PIC 9(4). All such elementary receiving fields.Cobol Non-Numeric Data Manipulation ♦ Example 1 A. 2 A1 PIC 9(5). including all occurrences of exceptions: ♦ ♦ ♦ Index data items Data items defined with USAGE IS POINTER Elementary FILLER data items affected.

0 Page 81 of 148 . Alpha-numeric and Alpha-numeric edited ZERO is implied source for . identifier-1 can contain a REDEFINES clause or be subordinate to such an item.Elementary items that are not of category mentioned in REPLACING INITIALIZE .) The areas referenced by identifier-1 are initialized in the order (left to right) of the appearance of identifier-1 in the statement. ♦ subordinate to a redefining item. Specifies that characters.Filler .Redefines .Counted (tallied) .Numeric and Numeric edited For Group initialize the following will not participate . or special character) in a data item.Alpha.Replaced . ♦ ♦ ♦ SPACE is implied source for .Examples INITIALIZE id-1 Length of Id-1 9(5) X(5) 99XX9 INSPECT ♦ to be .Pointer variables . It will convert all occurrences of specific characters in a data item to user-supplied replacement characters.Index variables . ♦ ♦ ♦ It will count the occurrence of a specific character (alphabetic. Within a group receiving field. such as spaces or zeros. or groups of characters in a data item are Before 12345 AB123 12AB3 After 00000 Bbbbb Bbbbb Cognizant Academy Ver 1. It will fill all or portions of a data item with specified characters. affected elementary items are initialized in the order of their definition within the group.Cobol ♦ Non-Numeric Data Manipulation Items that are subordinate to identifier-1 and contain a REDEFINES clause. or any items (However.or both. numeric.

When both the TALLYING and REPLACING phrases are specified. The process described in rules 2 and 3 is then repeated.Cobol ♦ ♦ CONVERTING is a special form of replacing Non-Numeric Data Manipulation In the following list of comparison rules. 3. The first comparand is compared with an equal number of leftmost contiguous characters in the inspected item. TALLYING/REPLACING phrase descriptions. 4. The implied character is always considered to match the inspected character in the inspected item. In the inspected item. immediately followed by an INSPECT REPLACING statement. the TALLYING and REPLACING phrases are the items 1. an implied 1-character comparand is used in the process described in rules 2 and 3. If no match is found. 2. If no match occurs for the first comparand. character-for-character. then. 6. the INSPECT being compared: statement is executed as if an INSPECT TALLYING statement were specified. 5. The actions taken in rules 1 through 6 (defined as the comparison cycle) are repeated until the rightmost character in the inspected item has either been matched or has been considered as being in the leftmost character position. tallying or replacing takes place. process described in rules 2 and 3 is then repeated. the first character following the rightmost matching character is now considered to be in the leftmost character position. The comparand matches the inspected characters only if both are equal. the first character following the leftmost inspected character is now considered to be in the leftmost character position. in the inspected item. 7. as described in the following The successive comparand until either a match is found or all comparands have been acted upon. ♦ Format 1 INSPECT id-1 TALLYING id-2 FOR {CHARACTER ALL {id-3 lit-1} LEADING {id-3 lit-1}} [{BEFORE AFTER} INITIAL {id-4 lit-2}] Cognizant Academy Ver 1. Inspection is then terminated. the comparison is repeated for each If a match is found. If the CHARACTERS phrase is specified.0 Page 82 of 148 .

INSPECT data-1 TALLYING countr FOR CHARACTERS AFTER INITIAL "S" REPLACING ALL "A" BY "O" DATA-1 COUNTR DATA-1 Before After After ANSELM SACKET PASSED 3 5 3 ONSELM SOCKET POSSED INSPECT data-1 REPLACING CHARACTERS BY ZEROS BEFORE INITIAL QUOTE.Examples 77 countr PIC 9 VALUE ZERO. 01 data-1 PIC X(6).0 Page 83 of 148 . DATA-1 COUNTR DATA-1 Before After After ANS”LM SACK”T 0 0 000”LM 0000”T Cognizant Academy Ver 1.Cobol Non-Numeric Data Manipulation ♦ INSPECT id-1 Format 2 REPLACING {CHARACTER ALL {id-2 lit-1} LEADING {id-2 lit-1}} BY {id-3 lit-2} [{BEFORE AFTER} INITIAL {id-4 lit-3}] ♦ Format 3 INSPECT id-1 CONVERTING {id-2 lit-1} TO {id-3 lit-2} [{BEFORE AFTER} INITIAL {id-4 lit-3}] INSPECT .

DELIMITED BY {id-2 lit-2 SIZE} INTO id-3 [WITH POINTER id-4 ] [ON OVERFLOW imperative stmt-1] [NOT ON OVERFLOW imperative stmt-2] [END-STRING] STRING . STRING FIELD-1 FIELD-2 FIELD-3 DELIMITED BY ‘ ‘. STRING {id-1 lit-1} .0 Page 84 of 148 ... SPACES.Examples INSPECT data-1 CONVERTING ”abcdefghijklmnopqrstuvwxyz" TO "ABCDEFGHIJKLMNOPQRSTUVWXYZ" AFTER INITIAL "/" BEFORE INITIAL"?" Before a/five/?six r/Rexx/RRRr zfour?inspe After a/FIVE/?six r/REXX/RRRR zfour?inspe STRING ♦ ♦ ♦ Strings together the partial or complete contents of two or more data items or literal into one single One STRING statement can be written instead of a series of MOVE statements. ‘MA IN ‘.Example 77 77 77 77 FIELD-1 FIELD-2 FIELD-3 FIELD-4 PIC PIC PIC PIC X(4) X(6) X(9) X(14) VALUE VALUE VALUE VALUE ‘ABCD’.34.’ INTO FIELD-4 FIELD-4 = ABCDMA121bbbbb Cognizant Academy Ver 1.56’.Cobol Non-Numeric Data Manipulation INSPECT . ‘121. ‘. Process is called concatenation data item.

FIELD-1 does not contain any delimiters.Edited field .With reference modification ♦ Pointer variable must be .Rules ♦ Receiving fields must not be ..Count of the total number of characters transferred .Elementary and Numeric .Number of characters placed in each receiving field . all 4 characters are moved to FIELD-4 First 2 characters of FIELD-2 are moved to FIELD-4 as third character is the delimiter First 3 characters of FIELD-3 are moved to FIELD-4 as 4th character is the delimiter STRING .0 Page 85 of 148 .Large enough to hold max length of receiving field ♦ ON OVERFLOW executed when pointer Value <= 0 or exceeds max length of receiving field UNSTRING ♦ Causes contiguous data in a sending field to be separated and placed into multiple receiving fields: .With Justified clause . [WITH POINTER IN id-7 ] [TALLYING IN id-8 ] [ON OVERFLOW imperative stmt-1] [NOT ON OVERFLOW imperative stmt-2] [END-UNSTRING] Cognizant Academy Ver 1.Cobol Non-Numeric Data Manipulation In the above example.]] INTO ( id-4 [DELIMITER IN id-5] [ COUNT IN id-6] ) ..Special action when all the receiving fields are filled before the end of the sending item ♦ Useful to convert display format data to compact form UNSTRING id-1 [DELIMITED BY ALL {id-2 lit-1} [OR ALL {id-3 lit-2} ...

’ OR SPACE INTO LAST-NM COUNT IN LAST-NM-CNT FIRST-NM COUNT IN FIRST-NM-CNT MID-NM COUNT IN MID-NM-CNT LAST-NM = ‘EDISON’ LAST-NM-CNT = 6 FIRST-NM= ‘THOMAS’ FIRST-NM-CNT = 6 MID-NM = ‘ALVA’ MID-NM-CNT = 4 UNSTRING . SET SET .Cobol Non-Numeric Data Manipulation UNSTRING . the results are the same as if a separate SET statement had been written for each condition-name in the same order in which they are specified in the SET statement. TO TRUE ♦ ♦ ♦ The value associated with a cond-name1 is placed in its conditional variable If more than one Value is defined for the cond-name1 then the 1st is used If multiple condition-names are specified. the number of characters examined is equal to the If the POINTER phrase size of the current data receiving field. THOMAS ALVA ’ UNSTRING FULL-NM DELIMITED BY ‘.0 Page 86 of 148 . SET .Is not specified an implicit value of 1 is assumed If specified.Rules ♦ ♦ ♦ If the DELIMITED BY phrase is not specified.Condition Name Cognizant Academy Ver 1.CONDITION NAME SET cond-name1 .. .. the source field is examined from the relative character position specified by the value in the pointer field.Example FULL-NM = ‘EDISON.

Cobol

Non-Numeric Data Manipulation

Example 77 I-EOF-FLAG PIC x. 88 C-EOF VALUE ‘Y’. SET C-EOF TO TRUE (I-EOF-FLAG will have the value ‘Y’ after the execution of the SET statement) 77 I-ACTION-FLAG PIC X. 88 C-ADD VALUE ‘A’ space. 88 C-DEL VALUE ‘D’. 88 C-MOD VALUE ‘M’. SET C-ADD TO TRUE (Will get value ‘A’ - first lit in value clause) SET - Pointer Data SET { id-1 ADDRESS OF id-2 } ... TO { ADDRESS OF identifier-3 id-4 NULL NULLS }
♦ ♦ ♦ id-1 and id-4 must be POINTERs id-2 and id-3 must be 01 or 77 levels in LINKAGE NULL, NULLS sets the receiving field to contain the value of an invalid address.

SET - Pointer data Example 77 PTR-FIRST USAGE IS POINTER. LINKAGE SECTION. 01 SALARY-REC. 05 PTR-NEXT-REC POINTER. 05 NAME PIC X(20). 05 DEPT PIC 9(4). 05 SALARY PIC 9(6). PROCEDURE DIVISION USING SALARY-REC. SET PTR-FIRST TO ADDRESS OF SALARY-REC DISPLAY NAME DEPT SALARY IF PTR-NEXT-REC NOT = NULL SET ADDRESS OF SALARY-REC TO PTR-NEXT-REC END-IF

Cognizant Academy

Ver 1.0

Page 87 of 148

Cobol

Non-Numeric Data Manipulation

SET – Indexes SET index-name-3
♦ ♦ ♦ ♦

UP BY identifier-3 DOWN BY integer-2

When this form of the SET statement is executed, the value of the receiving field is increased (UP BY) or decreased (DOWN BY) by a value that corresponds to the value in the sending field. The receiving field can be specified by index-name-3. This index-name value both before and after the SET statement execution must correspond to the occurrence numbers in an associated table. The sending field can be specified as identifier-3, which must be an elementary integer data item, or as integer-2, which must be a nonzero integer. When the Format 2 SET statement is executed, the contents of the receiving field are increased (UP BY) or decreased (DOWN BY) by a value that corresponds to the number of occurrences represented by the value of identifier-3 or integer-2. Receiving fields are acted upon in the left-to-right order in which they are specified. The value of the incrementing or decrementing field at the beginning of SET statement execution is used for all receiving fields.

Cognizant Academy

Ver 1.0

Page 88 of 148

Cobol

Sub-Program

10. Sub-Program
CALL
♦ ♦ Transfers control from one object program to another within the run unit. Called program starts executing from:

- Top of program - ENTRY label (not good programming practice) ♦ Transfer control methods - Call nested program - Static call - Dynamic call ♦ Parameters to called program: - By reference - By content ♦ ♦ Use RETURN-CODE special register to pass return codes Return of control depends on the termination stmt issued by the called program

- Stop run unit - Return to called program

CALL { id-1 lit-1} [ USING { [BY REFERENCE ] { id-2 file-name-1 ADDRESS OF id-3} ... BY CONTENT { [LENGTH OF] id-2 ADDRESS OF id-3 lit-1} ... } ... ] [ON {OVERFLOW imperative stmt-1] EXCEPTION } [ NOT ON EXCEPTION imperative stmt-2] [END-CALL]

Cognizant Academy

Ver 1.0

Page 89 of 148

Calling pgm WORKING-STORAGE SECTION. PROGRAM-ID. pic 9(4). pic s9(9)v99 comp-3. CALL l-SUBPGM1 USING BY CONTENT l-PARM1 l-PARM2 BY REFERENCE l-PARM3... CALL l-SUBPGM-1 USING l-PARM1l-PARM2. 1-SUBPGM1. pic s9(9)v99 comp-3. PROCEDURE DIVISION. 01 l-parm1. . 05 l-name 05 l-emp-no 01 l-parm2. 05 l-salary 05 l-hra 05 l-leave 01 l-parm3. pic s9(9)v99 comp-3..0 Page 90 of 148 . pic s9(2)v9 comp-3. 77 l-subpgm-1 pic x(8) value ‘SUBPGM1’. CALL . IDENTIFICATION DIVISION. 05 l-gross 05 l-deduct pic x(30).Examples CALL ‘SUBPGM1’.Cobol Sub-Program CALL . pic s9(9)v99 comp-3. CALL l-SUBPGM1 USING BY CONTENT l-PARM1 l-PARM2 BY REFERENCE l-PARM3. … Cognizant Academy Ver 1.

Cobol Sub-Program LINKAGE SECTION. 01 L-PARM3.Rules ♦ ♦ ♦ ♦ ♦ The correspondence of identifiers in the using clause of called and calling programs is positional File-name in using is only for QSAM files Address of option can be used only for Linkage variables with level 01 or 77 Exception or Overflow cond occurs when the called program cannot be made available. 05 l-gross pic s9(9)v99 comp-3. 05 l-salary pic s9 (9) v99 comp-3. All programs contained in the Canceled program are also canceled. 05 l-name pic x(30). 05 l-deduct pic s9(9)v99 comp-3. 05 l-emp-no pic 9(4). PROCEDURE DIVISION USING L-PARM1 L-PARM2 L-PARM3. 05 l-leave pic s9(2)v9 comp-3. Same as executing an EXIT PROGRAM or GOBACK in the called subprogram if it possesses the INITIAL attrib. Called program must not execute a CALL statement that directly or indirectly calls the calling program (Recursion not allowed) CANCEL CANCEL {id-1 lit-1} ♦ ♦ ♦ Ensures that the next time the referenced subprogram is called it will be entered in its initial state. 01 L-PARM2. Cognizant Academy Ver 1. CALL . 05 l-hra pic s9(9)v99 comp-3.0 Page 91 of 148 . 01 L-PARM1.

Temporarily (Lit-1 option) • literal communicated to operator and execution suspended Cognizant Academy Ver 1.. .0 Page 92 of 148 .NAME (ALIAS) compiler option to generate link-edit ALIAS card for each ENTRY statement.. an implicit EXIT PROGRAM stmt is EXIT PROGRAM stmt in a called program with INITIAL attribute is equivalent to executing a An EXIT PROGRAM executed in a main program has no effect.Cobol Sub-Program ENTRY ENTRY lit-1 [USING id-1 .] ♦ ♦ ♦ Establishes an alternate entry point Execution of the called program begins at the first executable stmt Not a recommended way of entering a program following the ENTRY stmt whose literal corresponds to the CALL stmt literal or identifier Entry .NAME or ALIAS linkage editor control statements.Watch out ♦ ♦ Static calls to alternate entry points work without restriction.Permanently (RUN option) . EXIT PROGRAM EXIT PROGRAM ♦ ♦ ♦ ♦ ♦ Specifies the end of a called program and returns control to the calling program When no CALL statement is active. control passes through the exit point to the next executable When there is no next executable stmt in a called program. stmt executed CANCEL STOP STOP {RUN lit-1} ♦ Halts execution of the program : ♦ . Dynamic calls to alternate entry points require: .

PROGRAM-ID paragraph.STOP RUN statement when coded in a main program. Cognizant Academy Ver 1.0 Page 93 of 148 .EXIT PROGRAM statement when coded in a called program . contain any nested source programs. END PROGRAM END PROGRAM program-name . ♦ ♦ ♦ An END PROGRAM header terminates a nested program or separates one program from another The program-name must be same as the program-name declared in the corresponding An END PROGRAM is optional for the last program in a sequence only if that program does not in a sequence of programs.Cobol Sub-Program • Program execution is resumed only after operator intervention ♦ STOP RUN statement closes all files defined in any of the programs comprising the run unit. GOBACK GOBACK ♦ Functions like: .

File position indicator ♦ to . to the characters with the lowest ordinal position in the collating sequence associated with the file..For KSDS your add must have a record key higher than the highest record in the file When the EXTEND is specified the file positioned immediately after the last record written in the CLOSE CLOSE file-name1 . I-O file-name3 .. Opens the file for processing EXTEND is allowed only for sequential files (not for VSE) OUTPUT clears the file of its existing records Open .. .For VSAM relative files. OUTPUT file-name2 .. FILE OPERATIONS OPEN OPEN { INPUT file-name1 .For ESDS or RRDS file the added records are placed after the last existing records .11. The successful execution of OPEN INPUT or OPEN I-O statement sets the file position indicator OPEN ... EXTEND file-name4 ...1 for non-empty QSAM file .Extend Rules ♦ file . ♦ ♦ Closes the open file Terminates the file processing .. to 1. ♦ ♦ ♦ } ...For VSAM sequential and indexed files..

3.Sequential Read READ file-name-1 NEXT RECORD [ INTO identifier-1 ] [ AT END imperative-stmt-1] [ NOT AT END imperative-stmt-2 ] [ END-READ ] ♦ ♦ ♦ NEXT phrase is optional for SEQUENTIAL access mode & a must for DYNAMIC When the READ NEXT statement is the first statement to be executed after the OPEN statement USAGE:1. The key field of the EMP-MATER file is Emp-no. This is because the alternate key may not be unique. Designation. 2. the next record is the first record in the file Format-2 . search the vsam file for a particular key for processing. we use sequential read of the indexed file on the file. The sequential read is used when the exact key value is not known and if we want to This sequential read is also used when Alternate key is used as key to the indexed file. For E. date-of-joining. When we need to process records with part of the key matching.At termination of run-unit .Random read READ file-name-1 RECORD [ INTO identifier-1 ] [ KEY IS data-name-1 ] [ INVALID KEY imperative-stmt-3 ] [ NOT INVALID KEY imperative-stmt-4 ] [ END-READ ] ♦ Data-name-1 is either a RECORD KEY or ALTERNATE RECORD KEY of the Indexed file .. if we want to process all employees belonging to designation “Associates”. we use sequential read.CANCEL command .G.Return from program with INITIAL attribute READ Format-1 .♦ COBOL performs automatic closing if not closed .

The random read of indexed file is faster. Any subscripting or reference modification associated with identifier-1 is evaluated after the record has been read and immediately before it is moved to the data item. The full key value for the Patient master file is known. is equivalent to the application of the following rules in the order specified: The current record is moved from the record area to the area specified by identifier-1 according to the rules for the MOVE statement without the CORRESPONDING phrase. If the file description entry contains a RECORD IS VARYING clause. The record is available in both the record area and the data item referenced by identifier-1.The prime RECORD KEY data name if KEY phrase not specified ♦ ♦ ♦ The KEY IS phrase can be specified only for indexed files. this key of reference is used for subsequent executions of sequential READ 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. The file position indicator is positioned to this record. an INVALID KEY condition exists. If no record can be so identified.♦ ♦ ♦ The result of the execution of a READ statement with the INTO phrase The execution of the same READ statement without the INTO phrase.Indexed file ♦ Key of reference : . the implied move is a group move. The implied MOVE statement does not occur if the execution of the READ statement was unsuccessful. Here there might be necessary to retrieve a particular patient’s record. until the first record having an equal value is found. Data-name-1 must identify a record key associated with file-name-1 When dynamic access is specified. Hence we use random read in this case. ♦ ♦ This format of READ is used when the ACCESS mode is either random or dynamic USAGE:. The size of the current record is determined by rules specified for the RECORD clause.Data name specified in KEY phrase . The random read can be used in real time systems like Patient monitoring system in hospitals. READ Random . which is then made available. and READ statement execution is unsuccessful.The random reading of indexed file is used when the key value for the file is exactly known. .

these records automatically share the same storage area. only those data items within the range of the current record are replaced. data-name becomes the key of reference for this request. After a READ statement is executed. When dynamic access is specified. 01 RECORD-1 PICTURE X(30). 01 RECORD-2 PICTURE X(20). If the range of the current record exceeds the record description entries for file-name-1. In either of these cases. Multiple Record Processing If more than one record description entry is associated with file-name-1 in the File Description. the record is truncated on the right to the maximum size. Contents of record being read in RECORD-2: 01234567890123456789 . EXAMPLE: The FD entry is: FD INPUT-FILE LABEL RECORDS OMITTED. the prime RECORD KEY becomes the key of reference for this request. that is. Contents of RECORD-1 when READ statement is executed: ABCDEFGHIJKLMNOPQRSTUVWXYZ1234 When the next record from the file is read into RECORD-2. until a different key of reference is established.♦ If the KEY phrase is not specified. the READ statement is successful and an I-O status (04) is set indicating a record length Conflict has occurred. When dynamic access is specified. ♦ KEY Phrase: .When the KEY phrase is specified. READ Random . the prime RECORD KEY is also used as the key of reference for subsequent executions of sequential READ statements.Relative file ♦ ♦ Execution of a Format 2 READ statement reads the record whose relative record number is The KEY phrase must not be specified contained in the RELATIVE KEY data item. this key of reference is used for subsequent executions of sequential READ statements. until a different key of reference is established. data items stored beyond that range are undefined. they are implicitly redefined. The below example illustrates this concept.

or DELETE. If the record is no longer accessible . The successful execution of an OPEN INPUT or OPEN I-O statement for sequential files sets the file position indicator to 1. it has been deleted. In the above example. and READ NEXT statements 2. when we use RECORD-2 layout because this is implicitly redefined item More on File Position Indicators ♦ The file position indicator is a conceptual entity used to facilitate exact specification of the next record to be accessed within a given file during certain sequences of input-output operations. For VSAM relative files. This storage area can hold any characters depending on the sequence of reads and any process done inside the program using RECORD-1. READ. I. Only the OPEN. OPEN. to 1. 3. ♦ ♦ ♦ Indicates the next record to be accessed for sequential COBOL requests You do not specify them anywhere in your program It is set by successful: 1.e. Execution of an OPEN INPUT or OPEN I-O statement sets the file position indicator: 4.But since the record description contains two 01 levels and it’s a variable length file Contents of record area after second READ is executed: 01234567890123456789?????????? The last 10 characters of the record area is undefined. i. WRITE. CLOSE. READ and START statements affect the setting of the file position indicator.e. 5. START. ♦ ♦ ♦ ♦ Subsequent READ or READ NEXT requests then uses & updates it It is not used or affected by the output statements : 6. the file position indicator is updated The file position indicator has no meaning for random processing to point to the next existing record in the file . to the characters with the lowest ordinal position in the collating sequence associated with the file. REWRITE. But this area cannot be accessed. assume there was no processing then the last 10 bytes would contain “UVWXYZ1234”. The concept of a file position indicator has no meaning for a file opened in the output or extends mode. For VSAM sequential and indexed files.

1 File position indicator example START ♦ ♦ ♦ ♦ Enables the positioning of the pointer at a specific point in an indexed or relative file File should be opened in Input or I-O mode Access mode must be Sequential or Dynamic Does not read the record . Assoc # Assoc Name 0004 RAJESH 0010 RAMESH 0015 GOPAL 0016 RAGHAVAN 0100 SARITA 0401 RANI Operation OPEN input READ next READ Key 0100 READ next READ key 0015 READ key 0090 READ next File Position Pointer 0004 0010 0401 end of file 0016 Undefined Undefined Record Area Not defined 0004 Rajesh 0100 Sarita 0401 Rani 0015 Gopal Undefined (Invalid key) Undefined Table 11.READ .Example File. Dynamic Access Record Description: 01 ASSOC-REC 05 ASSOC-NO-KEY PIC 9(4).Indexed. 05 ASSOC-NAME PIC X(10).

File position indicator points to the first record in the file whose key Invalid Key arises if the record position is empty When KEY phrase is not specified KEY EQUAL TO primary key is . the comparison proceeds as if the longer field were truncated on the right to the length of the shorter field. ♦ ♦ effect ♦ The file position indicator points to the first record in the file whose key field satisfies the comparison. If the operands in the comparison are of unequal lengths. a comparison is made PROGRAM COLLATING SEQUENCE clause.START file-name [ KEY IS { EQUAL TO data-name] = GREATER THAN > NOT LESS THAN NOT < THAN } [ INVALID KEY imperative-stmt-1 ] [ NOT INVALID KEY imperative-stmt-2 ] [ END-START ] START . When the KEY phrase is specified. the file position indicator is When the KEY phrase is not specified. KEY IS EQUAL (to the prime positioned at the logical record in the file whose key field satisfies the comparison. has no between the current value in the key data-name and the corresponding key field in the file's index. if specified. All other numeric and nonnumeric comparison rules apply When the START statement is executed.Rules ♦ ♦ implied ♦ field satisfies the comparison ♦ ♦ record key) is implied.

Dynamic Access Record Description: 01 ASSOC-REC 05 ASSOC-NO-KEY PIC 9(4). 05 ASSOC-NAME PIC X(10).2 Illustration of START statement WRITE WRITE rec-name [FROM id-1] [ { BEFORE ADVANCING AFTER } { int-1 { LINE id-2 LINES } mnemonic-name PAGE } ] [AT { END-OF-PAGE stmt-1 EOP } [NOT AT { END-OF-PAGE stmt-2 EOP } [END-WRITE] .START File. Assoc # Assoc Name 0004 RAJESH 0010 RAMESH 0015 GOPAL 0016 RAGHAVAN 0100 SARITA 0401 RANI OPERATION OPEN I-O START ASSOC.NOKEY = 0004 READ NEXT START ASSOC-NOKEY > 0016 READ NEXT START ASSOC-NOKEY > 0401 POINTER VALUE TOP OF FILE 0004 0010 0100 0401 UNKNOWN REC-AREA NOT DEFINED NOT DEFINED 0004 RAJESH 0004 RAJESH 0100 SARITA 0100 SARITA Table 11.Indexed.

in case of Non-Homogeneous Files the Record Layouts must contain a Record Type Field for identification. When AFTER ADVANCING is specified. ♦ The WRITE statement can only be executed for a sequential file opened in OUTPUT or EXTEND mode for a sequential file.End of Page Logic (FD entry for this file must contain a LINAGE clause) ♦ When ADVANCING option is used . When identifier-2 is specified. When BEFORE ADVANCING is specified.Advance and Print . 2. the END-OF-PAGE imperative-statement is executed WRITE for Seq.Print and Advance . From its Record Area defined at 01 Level WRITE for Printer Files ♦ Facilities for Paper Movement are provided . ♦ The various 01 levels defined for the same file implicitly redefine each other.If compile option is NOADV then LRECL of file is same as FD entry record area length • leave the 1st char for printer control .If compile has ADV the LRECL of file should be one more than FD entry record area length . Files ♦ WRITE ASSOC-REC ♦ ♦ First Copy into File Area and then Write WRITE ASSOC-REC FROM COPY-REC Note that File Name is not mentioned in the Write Statement ♦ Facilitates Multiple-Record Type Files also known as Non-Homogeneous Files. the following rules apply: 1. the page is advanced the number of lines equal to the current value in identifier-2.First char of record reserved for printer control . ♦ ♦ File Position is not affected by this statement When END-OF-PAGE is specified. the page is advanced before the line is printed. and the logical end of the printed page is reached during execution of the WRITE statement. 3. the line is printed before the page is advanced. Therefore.♦ ♦ ♦ Releases a record onto the output file ADVANCING phrase is only for Printer Files when this phrase is specified.Advance by given number of lines . Identifier-2 must name an elementary integer data item. That is they share the same record area.Position to New Page .

the procedure is then executed. and an EXCEPTION/ERROR condition exists.For RRDS system returns the RELATIVE KEY if clause is specified in SELECT stmt ♦ When access is random or dynamic . if an explicit or implicit EXCEPTION/ERROR procedure is specified for the file.Invalid key ♦ ♦ ♦ ♦ Not Allowed for ESDS Attempt to write beyond file boundary Record with specified key already present (KSDS. . the results are unpredictable. The contents of record-name are unaffected. if no such procedure is specified. records must be released in ascending order of RECORD KEY values Else INVALID KEY condition will be raised . WRITE . and.For KSDS. the status key is updated.Rules for VSAM ♦ ♦ When access is sequential . WRITE record-name-1. RRDS) FROM phrase: ♦ The result of the execution of the WRITE statement with the FROM identifier-1 phrase is MOVE identifier-1 TO record-name-1.For KSDS populate RECORD key data item and ALTERNATE key data item (if any) .For RRDS populate the RELATIVE key data item ♦ When an attempt is made to write beyond the externally defined boundaries of the file.WRITE for Disk Files WRITE record-name [ FROM id-1 ] [ INVALID KEY imperative-stmt-1 ] [ NOT INVALID KEY imperative-stmt-2 ] [ END-WRITE ] WRITE . equivalent to the execution of the following statements in the order specified. the execution of the WRITE statement is unsuccessful. If specified.

unless the DUPLICATES phrase is specified. as defined in the File-Control entry) to the desired value. record key must be unique. the information is still available in File position ind not affected For Sequential files REWRITE . In this case. If the DUPLICATES phrase is specified. REWRITE REWRITE record-name [ FROM id-1] [ INVALID KEY imperative-stmt-1] [ NOT INVALID KEY imperative-stmt-2 ] [ END-REWRITE ] ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ ♦ Updates an existing record in a file File should be opened in I-O mode When access mode is sequential.INVALID KEY not allowed . and the value of RECORD KEY of the record to be replaced not Value contained in RECORD KEY not = any record in file Duplicate ALTERNATE RECORD KEY when duplicates are not allowed File should be opened in I-O After REWRITE record is not available in the rec area After a REWRITE statement with the FROM phrase is executed.Invalid Key = RECORD KEY data item of the last-retrieved record REWRITE .♦ ♦ Before the WRITE statement is executed.Record length can’t change ♦ For random or dynamic access the record to be rewritten need not be read first . the system stores the records so that later sequential access to the records allows retrieval in the same order in which they were stored. alternate record key values may not be unique. ♦ When ACCESS IS SEQUENTIAL is specified in the File-Control entry.Rules identifier-1 . each alternate data item. you must set the prime record key (the RECORD KEY If the ALTERNATE RECORD KEY clause is also specified in the File-Control entry. records must be released in ascending order of RECORD KEY values.

If the file does not contain such a record. the system removes the record identified by the contents of the prime RECORD KEY data item for VSAM indexed files. ♦ For a file in sequential access mode.INVALID key not allowed ♦ For Random or Dynamic access system removes record pointed by the RECORD key(KSDS) or RELATIVE key(RRDS) . For relative files. an INVALID KEY condition exists. When the DELETE statement is executed. Removes a record from an indexed or relative file For indexed files. the last input/output statement must have been a successfully executed READ . the space is then available for a new record with the DELETE .DELETE DELETE file-name-1 RECORD [ INVALID KEY imperative-stmt-1] [ NOT INVALID KEY imperative-stmt-2] [ END-DELETE ] ♦ ♦ ♦ same RELATIVE KEY value. ♦ For a file in sequential access mode. an EXCEPTIONERROR procedure can be specified. ♦ When the DELETE statement is executed. the system removes the record retrieved by that READ statement. the last input/output statement must have been a successfully executed READ statement. ♦ If the FILE STATUS clause is specified in the File-Control entry. or the RELATIVE KEY data item for VSAM relative files. ♦ The file position indicator is not affected by execution of the DELETE statement. the key can then be reused for record addition. the associated status key is updated when the DELETE statement is executed. However. the INVALID KEY and NOT INVALID KEY phrases must not be specified.Rules ♦ File should opened for I-O ♦ In sequential access mode.

output and the work files before the sorting begins and closed these Example Assume the following record description for the input file In the above format file-1 is the work file . ♦ file ♦ ♦ ♦ ♦ ♦ ♦ File-2 and file-3 are defined in the FD section The work file File-1 is defined in the file section as SD entry sort description entry The format of SD entry is same as the FD entry The sort verb opens input. PIC X(10). 02 ID-NUM 02 NAME 02 DEPARTMENT 02 BASIC-PAY 02 ALLOWANCE 02 DEDUCTION PIC 9(6). works file and sorted output file. SORT file-1 {ON {ASCENDING DESCENDING} KEY id-1. .SORT ♦ While processing sequential files.. file-2 is the unsorted input file. PIC 9(5)V99... file-3 is the sorted output files when sorting is over. PIC 9(4)V99.. it is sometimes necessary that the records should appear in some predetermined sequence. EMP-REC. PIC X(24). Hence this sort requires 3 files for processing – unsorted input file. {USING file-2 {GIVING file-3 ♦ This is a simple sort verb that accepts a input file and creates a sorted output file. The process of sequencing records in file in some predetermined order on some fields is called SORTING ♦ ♦ The fields based on which the records are sequenced are called SORT KEYS. PIC 9(4)V99. The Sort verb needs a work file for sorting the given input file. } . The sequencing can be ascending or descending order of the KEY. FD 1 EMP-FILE.

Editing in this context can mean selection of appropriate records from the input file for sorting. The work file and output files are SORT-FILE and OUTPUT-FILE. arrange BASIC-PAY on descending sequence. PIC X(12). INPUT PROCEDURE:The sort statement before the start of the sorting process implicitly performs the specified input procedure. 02 FILLER 02 DEPARTMENT 02 BASIC-PAY 02 FILLER OUTPUT-FILE OUT-REC PIC X(30). PIC X(10). The sort verb allows user to specify the INPUT & OUTPUT PROCEDURE in the sort statement. FD 1 The sort statement for this is SORT SORT-FILE ON ASCENDING KEY DEPARTMENT DESCENDING KEY BASIC-PAY USING EMP-FILE GIVING OUTPUT-FILE.We want to sort this file on DEPARTMENT on ascending sequence and then within each DEPARTMENT. Sometimes its necessary to edit records before sorting or after sorting before writing it to the output file. The input and output procedures are nothing but sections placed outside the SORT statement. which perform the necessary processing of the records. PIC 9(5)V99. The FD and SD entries for these files are as follows SD 01 SORT-FILE SORT-REC. performs the necessary processing and then release the records to Sorting operation by RELEASE statement which is discussed later in this chapter . a file with variable length records will require some padding with some characters to make it fixed length for the purpose of sorting. This means that the records with same DEPARTMENT value are to be arranged from highest to lowest value of the BASIC-PAY. PIC X(59). For example. This procedure reads the records from input file.

INPUT-OUTPUT SECTION. SELECT EMP-FILE ASSIGN TO EMPMSTR. FILE SECTION.. SELECT EMP-LIST ASSIGN TO REPORT.OUTPUT PROCEDURE:The output procedure is performed implicitly by sort statement in order to perform editing on the sorted records. [WITH DUPLICATES IN ORDER] [COLLATING SEQUENCE IS alphabet-name-1] {USING file-2 INPUT PROCEDURE IS proc-nm-1 [THRU proc-nm-2]} {GIVING file-3 OUTPUT PROCEDURE IS proc-nm-3 [THRU proc-nm-4]} SORT . SELECT SORTED-EMP-FILE ASSIGN TO EMPSORT. CONFIGURATION SECTION. SORT file-1 { ON {ASCENDING DESCENDING} KEY id-1. .. FILE-CONTROL.Examples ♦ SORT sorted-emp-file ASCENDING s-last-nm s-first-nm DESCENDING s-emp-nbr USING emp-file OUTPUT PROCEDURE write-emp-list THRU write-emp-list-exit ENVIRONMENT DIVISION. The output procedure gets the sorted records by means of RETURN statement that is discussed later in this chapter.. } .. DATA DIVISION.

WRITE-EMP-LIST-EXIT.. ♦ Collating Sequences ... 05 S-MID-NM PIC X(20). 05 MID-NM PIC X(20).Default is EBCDIC .. 05 S-EMP-NBR PIC 9(4). WRITE-EMP-LIST. 05 EMP-NBR PIC 9(4). EXIT.. SD SORTED-EMP-FILE LABEL RECORDS ARE OMITTED. 05 FIRST-NM PIC X(20). 05 LAST-NM PIC X(20)..FD EMP-FILE LABEL RECORDS ARE OMITTED. ..COLLATING SEQUENCE option of the SORT statement that is defined in SPECIALNAMES paragraph .. 01 EMP-REC....PROGRAM COLLATING SEQUENCE if specified in the Configuration Section . SORT sorted-emp-file ASCENDING s-last-nm s-first-nm DESCENDING s-emp-nbr USING emp-file OUTPUT PROCEDURE write-emp-list THRU write-emp-list-exit . 05 S-LAST-NM PIC X(20). 05 S-FIRST-NM PIC X(20). 01 SORT-EMP-REC. PROCEDURE DIVISION. .

RETURN sort-file-name-1 [RECORD INTO id-1] [AT END imperative stmt1 ] [NOT AT END imperative stmt2] [END-RETURN] RETURN . read-sorted-rec-exit. at-least one RELEASE stmt must be executed RELEASE . at-least one RETURN stmt must be executed RETURN – Examples read-sorted-rec. . EXIT.RELEASE ♦ Transfers records to the initial phase of sort operation ♦ It’s like WRITE statement RELEASE sort-rec-name-1 [FROM id-1] ♦ If INPUT PROCEDURE is used. RETURN sorted-emp-file AT END SET c-sort-eof TO TRUE END-RETURN .Rules ♦ If OUTPUT PROCEDURE is used.Examples ♦ MOVE emp-rec RELEASE sort-emp-rec ♦ TO sort-emp-rec RELEASE sort-emp-rec FROM emp-rec RETURN ♦ ♦ Transfers records from the final phase of a sorting or merging operation to an OUTPUT It’s like READ statement PROCEDURE.

MERGE Sometimes it becomes necessary to create a new output file from 2 input files.. Each of these files contains zone name. salesman name. } . The file-1 is the work file. The files are sorted on product name. These 2 files needs to be merged and new file needs to be created For example A Company has its marketing operations divided into 2 zones and for each zone there is file. EXIT. SET c-not-sort-eof TO TRUE PERFORM read-sorted-rec THRU read-sorted-rec-exit PERFORM UNTIL c-sort-eof PERFORM string-emp-name THRU string-emp-name-exit MOVE w-emp-name TO rep-name MOVE s-emp-nbr TO rep-emp-nbr WRITE emp-list-rec PERFORM read-sorted-rec THRU read-sorted-rec-exit END-PERFORM . product name and amount of sales for a particular product. .] {GIVING file-4 OUTPUT PROCEDURE IS proc-nm-1 [THRU proc-nm-2]} The input files to be merged through MERGE statement are file-2.WRITE-EMP-LIST. The MERGE verb is used to merge 2 or more identical files sorted on the same field MERGE file-1 { ON {ASCENDING DESCENDING} KEY id-1.. WRITE-EMP-LIST-EXIT.. The file-2 and file-3 should be sorted on the key used to merge these 2 files.. district name. which should be defined in the SD entry.. We need to merge these 2 files into a single file to get a single transaction file to update the master file.. file-3. [COLLATING SEQUENCE IS alphabet-name-1] USING file-2 [file-3 .

Examples MERGE sorted-emp-ph-file ASCENDING s-last-nm s-first-nm DESCENDING s-emp-nbr USING emp-ph-file emp-addon-ph-file GIVING new-emp-ph-file MERGE .PROGRAM COLLATING SEQUENCE specified in the Configuration Section Default is EBCDIC PROCEDURE. .MERGE .Rules ♦ ♦ ♦ ♦ When USING / GIVING option is specified the input / output file(s) to merge must not be open The key used in the MERGE statement cannot be variably located. When the file referenced by filename-1 is merged control passes to first stmt in the OUTPUT Collating Sequences COLLATING SEQUENCE option of MERGE statement that is defined in SPECIAL-NAMES paragraph .

according to your program design. upon end-of-file the phrase is executed. the contents of the associated record area are undefined. . ♦ The end-of-file phrase (AT END) ♦ The EXCEPTION/ERROR declarative ♦ The FILE STATUS key ♦ The INVALID KEY phrase. If you do not code an AT END phrase. and the AT END condition is expected. You code the AT END phrase of the READ statement to handle either case. reading sequentially to the end of a file is done intentionally. Following an AT END condition. however. the condition will reflect an error. suppose you are processing a file containing transactions in order to update a master file: PERFORM UNTIL TRANSACTION-EOF = "TRUE" READ UPDATE-TRANSACTION-FILE INTO WS-TRANSACTION-RECORD AT END DISPLAY "END OF TRANSACTION UPDATE FILE REACHED" MOVE "TRUE" TO TRANSACTION-EOF END READ .INPUT/OUTPUT ERROR HANDLING TECHNIQUES The following are techniques of intercepting and Handling input/output Errors. If you code an AT END phrase. THE END-OF-FILE PHRASE (AT END) An end-of-file condition may or may not represent an error. . the associated ERROR declarative is executed. and attempts to move data to or from the associated record may result in a protection exception. In many designs. END-PERFORM In some cases. . For example.

whereas the ERROR declarative encompasses all forms. whereas ERROR declaratives are more general. In general. WRITE. and DELETE requests for indexed and relative files. You can have: ♦ A single.EXCEPTION/ERROR Declarative You can code one or more ERROR declarative procedures in your program that will be given control if an input/output error occurs. whereas ERROR declaratives are coded separately. INVALID KEY phrase This phrase will be given control in the event that an input/output error occurs because of a faulty index key. and a zero in both digits means "nothing abnormal to report". a zero in the first digit indicates a successful operation. however. I-O. 3. INVALID KEY phrases are specific for one single input/output operation. Establish a FILE STATUS key using the FILE STATUS clause in the FILE-CONTROL and data definitions in the Data Division. If you specify INVALID KEY in a statement that causes an INVALID KEY condition. It is used only when you attempt to write to a disk that is full. any ERROR declaratives you have coded are not executed. You can also include INVALID KEY on WRITE requests for QSAM files. INVALID KEY phrases are coded directly onto the input/output verb. OUTPUT. control is transferred to the INVALID KEY imperative statement. or EXTEND) ♦ Individual procedures for each particular file FILE STATUS key The system updates the FILE STATUS key after each input/output statement executed for a file placing values in the two digits of the file status key. common procedure for the entire program ♦ Group procedures for each file open mode (whether INPUT. REWRITE. START. . INVALID KEY phrases operate for only limited types of errors. You can include INVALID KEY phrases on READ. 2. In this case. In the case of QSAM files. INVALID KEY phrases differ from ERROR declaratives in three ways: 1. the INVALID KEY phrase has limited meaning.

This transaction file records needs to be inserted in the master indexed file if the emp-no is not present and if the emp-status id NA (new active). the record in the indexed file needs to be updated. If the records is present and if the emp-status id is TT the emp record from the master file needs to be deleted as he is an terminated employee. If the record is present. . and the emp status is OA which is old active. Assume there is a Transaction sequential file with record length 80 characters.Cobol EXERCISES EXERCISES 1. Write the COBOL code to do the processing of the transaction and master files. The following are the fields in the transaction file Emp-no 10 chars Emp-name 30 chars Emp-birth-date 8 chars(ddmmyyyy) Emp-designation 8 chars Emp-department 6 chars date-of-joining 8 chars Emp-status 2 chars Gross-salary 8 numeric with 2 decimal The master file is the indexed file with the same fields as above. data division and procedure division entries. COBOL code includes environment division.

This table can be fixed length tables and Variable length tables. ‘DECEMBERb‘. ‘MARCHbbbb‘. A series of totals in the working storage with the same format. The tables or Arrays are define using OCCURS in COBOL. the same data month name is being repeated 12 times. Now lets look at Occurs clause in detail. A table is a list of stored fields that are looked up or referenced by the program. For eg. Table handling Sometimes it becomes necessary to handle group of data consisting of similar items. An array is used to store similar items or elements. ‘AUGUSTbbb‘. Now lets us look at how the table can be defined in COBOL 01 MONTH-TABLE. Such a group is called a Table or Array. . 02 MON-NAME PIC X(9) OCCURS 12 TIMES. The usage of tables can be illustrated by the following example For example when we need to list the months normal way of representing it is 1 MONTH-TABLE. 02 MON-1 02 MON-2 02 MON-3 02 MON-4 02 MON-5 02 MON-6 02 MON-7 02 MON-8 02 MON-9 02 MON-10 02 MON-11 02 MON-12 PIC X(9) PIC X(9) PIC X(9) PIC X(9) PIC X(9) PIC X(9) PIC X(9) PIC X(9) PIC X(9) PIC X(9) PIC X(9) PIC X(9) VALUE VALUE VALUE VALUE VALUE VALUE VALUE VALUE VALUE VALUE VALUE VALUE ‘JANUARYbb‘. ‘JUNEbbbbbb‘. Each element of the table can be referred using a Subscript or an index. ‘OCTOBERbb‘. ‘JULYbbbbbb‘. ‘NOVEMBERb‘. ‘MAY bbbbbb‘. ‘SEPTEMBER‘. ‘APRILbbbb‘. In the above example. Instead of defining the elements like this we can define it as a table with 12 elements. It also eliminates the need for separate entries for repeated data items.Cobol Table Handling 12. ‘FEBRUARYb ‘.

However REDEFINES clause can appear for a group item whose sub item contains occurs clause ♦ The occurs clause is used to define single dimension and multi-dimensional tables. ♦ VALUE clause cannot be specified for associated data name defined with OCCURS clause or any sub item to the occurs clause ♦ REDEFINES and OCCURS clause cannot appear for the same data item. ] ] [ INDEXED BY index-name-1 [ . 77. an index similar to subscript. 66. ] ] OCCURS . But index is referenced in a more efficient manner internally.Has a level number of 01.. ♦ It also eliminates the need for separate entries for repeated data items. INDEX is an offset or displacement of the element from the beginning of the table .Describes a redefined data item FIXED LENGTH TABLES OCCURS integer-2 TIMES [ {ASCENDING KEY IS DESCENDING } dataname-2 [ .Cobol Table Handling OCCURS ♦ Used for defining Tables(Arrays) ♦ The OCCURS clause specifies tables whose elements can be referred to by indexing or subscripting. . ♦ Tables can be Fixed Length or Variable Length ♦ Can’t be defined for a data item which: . An index can be defined for a particular table or dimension of table using INDEXED BY phrase. A subscript is an integer data item. ♦ Occurs clause can be specified for elementary or group item.Index Name ♦ ♦ ♦ ♦ In COBOL... or 88.. INDEXING can do the subscripting of table. Required if item is indexed anywhere in the program Conceptually. The internal representation of a subscript and index are different.

I. The statements like Move or Add cannot be used on Index name is implicitly defined Index name cannot be associated with any other data hierarchy Must be initialized before it can be used using SET and PERFORM VARYING index VARIABLE LENGTH TABLES OCCURS . 77 A1 In this example depending on the value of A1. Table Handling 03 YEAR PIC In the above example the displacement of first element is zero. .... REC-1.3 and so on.Depending On ♦ ♦ 1 When a table of variable size needs to be defined. The syntax is OCCURS int1 TO int2 TIMES DEPENDING ON data-name-1 [ {ASCENDING KEY IS DESCENDING } dataname-2 [ . ] ] ♦ Object of the OCCURS DEPENDING ON (ODO) clause cannot be variably located. ] ] [ INDEXED BY index-name-1 [ .. 02 P2 PIC 99 OCCURS 1 TO 90 TIMES DEPENDING ON A1.2. the index I1 assumes these values for occurrence numbers 1.e. 3rd is 8 and so on. 2nd is 4. Occurs Depending clause may be used EXAMPLE PIC 2 P1 99 PIC XX. the size of the table may vary from 1 to 90.Cobol ♦ Example 9(4) OCCURS 10 TIMES INDEXED BY I1. ♦ ♦ ♦ ♦ ♦ The value of Index item is set by the occurrence number and not the internal value The value of index is set using SET clause.

Cobol ♦ ♦ ♦

Table Handling If subject of OCCURS is defined as EXTERNAL then ODO ought to be defined as EXTERNAL The int-1 and int-2 defined must be positive integers. The data name-1 can be defined at the same level as ODO but it cannot be defined as sub item to

ODO.

♦ Example 01 REC-1. 02 A1 PIC 99. 02 P1 PIC XX. 02 P2 PIC 99 OCCURS 1 TO 90 DEPENDING ON A1. The above example is valid. 01 REC-1. 02 P1 PIC XX. 02 P2 PIC 99 OCCURS 1 TO 90 DEPENDING ON A1. 02 A1 PIC 99. This definition is invalid
♦ ♦ GLOBAL definition needs rules similar to EXTERNAL ODO cannot be REDEFINED

♦ Example. This is invalid 01 REC-1. 02 A1 02 P1 02 P2 02 P3

PIC 99. PIC XX. PIC 99 OCCURS 1 TO 90 TIMES DEPENDING ON A1. REDEFINES P2

Length of group item containing Occurs depending - If ODO is outside the group the ODO value decides - If ODO is inside and group item is sending field then also ODO value decides - If ODO is inside and group item is receiving field then max length of group value used provided there are no non-subordinate to the group item

Cobol

Table Handling

SET SET { id-1 index-name-1 } ... TO { id-2 index-name-2 int-1 } SET index-name-1 ... { UP BY { id-3 DOWN BY } int-1 }

SET - Examples 05 TABLE-ITEM OCCURS 10 INDEXED BY INX-A PIC X (8). ♦ To set the index INX-A to 5th occurrence of TABLE-ITEM use stmt: SET INX-A TO 5 ♦ The Value in INX-A would be (5 - 1) * 8 = 32. ♦ To refer to 6th element we could use relative indexing - TABLE-ITEM (INX-A+1) ♦ Or Set the index first using - SET INX-A UP BY 1 and then refer as TABLE-ITEM(INX-A)

Sending flds Index Name Index data item Integer data item Numeric literal

Index Name V V* V V

Receiving Fields Index Data Item Integer Data Item V* V V* -

Table 12.1 Set - Sending and Receiving Fields

Cobol

Table Handling

Note : * - No Conversion COMPLEX TABLES
♦ Data item with Occurs Depending On is followed by - Non-subordinate item - Non-subordinate item with Occurs Depending On ♦ Data item with Occurs Depending On is nested

01

FILLER. 05 CTR1 05 CTR2 05 FIELD-A. 1 10 TABLE-1. 15 REC-1 OCCURS 1 TO 5 DEPENDING ON CTR1 10 EMP-NR 2 10 TABLE-2 OCCURS 5 3 INDEXED BY INDX. 4 15 TABLE-ITEM 15 20

PIC S99. PIC S99.

PIC X(3). PIC X (5).

PIC 99.

5 REC-2 OCCURS 1 TO 3 DEPENDING ON CTR2. DATA-NUM PIC S99. ♦ Complex ODO item

1 - A group item of variable length 2 - An elementary data item following, and not subordinate to, a variable length table (variably located item) 3 - A group item following, and not subordinate to, a variable-length table 4 - An index name for a table that has variable length elements 5 - An element of a table that has variable-length elements

01 TABLE-RECORD. 77 INT-DATA-1 PIC 99. 10 EMP-NAME PIC X (20).In the example if the value of the ODO object CTR2 is changed then the offset in index INDX is no longer valid for the table TABLE-2. 10 EMP-NO PIC 9(6).Example WORKING STORAGE SECTION. .After changing ODO object. TABLE PROCESSING Now we have seen how to define tables of various sizes and dimension. . 15 WEEK-NO PIC 99. 10 WEEK-RECORD OCCURS 52 ASCENDING KEY IS WEEK-NO INDEXED BY C. SET INT-DATA-1 TO INDX MOVE NEW-VALUE TO CTR2 SET INDX TO INT-DATA-1 OCCURS .If you want to preserve the contents of these items. we now see how to process these tables using PERFORM verb. 77 NEW-VALUE PIC S99. ♦ To avoid making this error : . 05 EMP-TABLE OCCURS 100 ASCENDING KEY IS WAGE-RATE EMP-NO INDEXED BY A. 15 ABSENCES PIC 99. 10 WAGE-RATE PIC 9999V99. prior to the change in the ODO object.Save the value of index as an occurrence number before changing ODO object.. ♦ Careful when using complex-ODO index names. save all non subordinate items following the variable item and after the change in the ODO object. .Cobol Table Handling Watch out. ♦ The location of non-subordinate items following the item with OCCURS clause is affected by new .. restore the value of index name from the integer data item value of the ODO object. restore all the items back. B.

MOVE 1 TO A1. . This is one form of PERFORM statement used for FIXED length tables. PERFORM ADD-PRICE-PARA 36 TIMES. Now we want to find the average price of the product for a period. Now we want to find the price of a product for period 011999 (mmyyyy) MOVE 1 TO A1 PERFORM FIND-PRICE-PARA UNTIL (PERIOD = ‘011999’ OR A1 > 36) FIND-PRICE-PARA IF PERIOD = ‘011999’ MOVE PROD-PRICE (A1) TO PRICE-1 END-IF ADD 1 TO A1 In this form. 10 PERIOD PIC X (10). 10 PROD-PRICE PIC S9 (7) V99. PRICE-1 PIC S9 (7) V99. COMPUTE TOTAL = PROD-PRICE (A1) + TOTAL ADD 1 TO A1.Cobol Table Handling EXAMPLE: Consider the following example 77 01 1 A1 PIC 99. The same fixed length table can be defined as variable length table. the paragraph is executed repetitively until the period id 011999 or until the subscript of the table is greater than the maximum table limits. MOVE ZERO TO TOTAL. COMPUTE AVERAGE = TOTAL / 36 ADD-PRICE-PARA. 05 PRODUCT-CODE PIC X (6) 05 PRICE-REC OCCURS 36 TIMES. DATA-REC.

01 DATA-REC.Cobol In this case again we want to find the price of a product for period 011999(mmyyyy) Table Handling 77 PRICE-1 PIC S9 (7) V99. PERFORM FIND-PRICE-PARA VARYING INX-1 BY 1 UNTIL INX-1 > TAB-CNT OR PERIOD = ‘011999’ FIND-PRICE-PARA IF PERIOD = ‘011999’ MOVE PROD-PRICE(INX-1) END-IF TO PRICE-1 In the above statement the increment of the INDEX is not given explicitly. The sorted table reduces the time of search. PROCEDURE DIVISION. 05 TAB-CNT PIC S9(04) COMP. . The data have to be sorted in the correct order (ascending or descending) by the programmer. The example for SORTED TABLES 02 ASSOC-DATA OCCURS 10 TIMES ASCENDING KEY IS A-NAME INDEXED BY INX-1. PIC 9(04). SET INX-1 TO 1. when a search is performed on the table. ♦ ♦ ♦ Either fixed length or variable length the table can be in the sorted order by defining a key for the table. 05 DATA-TABLE OCCURS 1 TO 37 TIMES DEPENDING ON TAB-CNT INDEXED BY INX-1. It is done automatically. 07 PROD-PRICE PIC S9(7)V9(02). 05 PRODUCT PIC X(10). 07 PERIOD PIC X(6). 05 A-NAME 05 A-NUM ♦ PIC X(20).

SEARCH VARYING Linear Search . If none of the conditions are satisfied the index is incremented by 1 automatically. clause have been satisfied or not. valid only for sorted tables with key specified. then execution is transferred to next statement. The value of the index remains set at the point where the condition has been satisfied. If these statements are not present. The increment of the index or id-2 is taken care of by the The search statement can be performed on he table defined by OCCURS and INDEXED BY The search verb starts with initial value of index and tests whether condition stated in the when search statement itself. the statements following the WHEN clause is executed. [ END-SEARCH ] ♦ ♦ ♦ ♦ ♦ ♦ ♦ This search is serial search or linear search. The process is continued until the index value exceeds the size of the table and the search is terminated. .Cobol Table Handling SEARCH ♦ ♦ To search a table element that satisfies a specified condition Options .. phrase.Sequential SEARCH id-1 [ VARYING { id-2 index-name-1 } ] [ AT END imperative-statement-1 ] WHEN condition-1 { imper-stmt2 NEXT SENTENCE } [ WHEN condition-2 { imper-stmt3 NEXT SENTENCE } ] . The table may sorted or not WHENs are performed one after another for each table entry until TRUE or NO more WHEN cond AT END executed if no match Set starting points of id-2 or index.SEARCH ALL Binary Search.. SEARCH . When one of conditions is satisfied before the index value reaches the size of the table.

10 ASSOC-NUM PIC 9(4). the index contains unpredictable ♦ values. 05 ASSOC-TABLE OCCURS 350 TIMES INDEXED BY I-1. ♦ Example 77 NAME PIC X(20). 10 ASSOC-NAME PIC X (20). . SEARCH ASSOC-TABLE AT END DISPLAY ‘NAME NOT FOUND’ WHEN NAME = ASSOC-NAME (I-1) DISPLAY ‘NAME FOUND’.Cobol ♦ Table Handling When the SEARCH terminates without finding the necessary value. SET I-1 TO 1.

1 Flow Chart for SEARCH with Varying and When option .Cobol Table Handling START If the value of index associated with id-1 is > size of the table YES Execute imperative statement-1 Go to next executabl e statement NO Go to next executabl e statement Is condition-1 true? YES Execute imperative statement-2 NO Is condition2 true? YES Execute imperative statement-3 Go to next executabl e statement NO Index associated with id-1 is incremented by 1 id-2/index-name-1 is incremented by 1 Figure 12.

. the item to be searched is present. but if set it must not be greater than the Duplicate index will indicate the first entry it encountered Unpredictable results if table is not in sorted order done on the table elements. ♦ ♦ ♦ ♦ This type of search minimizes the number of comparison that needs to be Initial setting of index ignored. Then again the half which is selected is split into 2 and the comparison is done to determine in which half the item to be searched is present. { imper-stmt2 NEXT SENTENCE } [ END-SEARCH ] Equal-clause can be { id-2 lit-1 arithexp-1} ♦ ♦ ♦ ♦ This SEARCH all is the Binary search. Now a single comparison with this item determines whether the item is present or not. the table is split into 2 halves and determines in which half table is arranged in the sorted order depending on the definition of the table. it is assumed that at the time of search the In this search. For this search the table needs to be in sorted order using ASCENDING/DESCENDING option in occurs clause When the binary search is used. maximum size ..Cobol Table Handling SEARCH ALL SEARCH ALL id-1 [ AT END imperative-statement-1 ] WHEN { dataname-1= equal-clause Condition-name-1} [ AND { dataname-1= equal-clause Condition-name-1} ] . Like wise the search continues until the item to be searched is found or the final division is just a single item. Then item to be searched is compared with the last item of the first half or first item of the second to determine in which the item to be searched is likely to be present.

Cobol Table Handling 77 NAME PIC X(20). 05 ASSOC-TABLE OCCURS 350 TIMES ASCENDING KEY IS A-NAME INDEXED BY I-1. SEARCH ALL ASSOC-TABLE AT END DISPLAY ‘NAME NOT FOUND’ WHEN NAME = A-NAME(I-1) DISPLAY ‘NAME FOUND’ . 10 A-NUM PIC 9(4). 10 A-NAME PIC X(20).

Examples MERGE sorted-emp-ph-file ASCENDING s-last-nm s-first-nm DESCENDING s-emp-nbr USING emp-ph-file emp-addon-ph-file GIVING new-emp-ph-file MERGE ..Rules ♦ ♦ ♦ ♦ When USING / GIVING option is specified the input / output file(s) to merge The key used in the MERGE statement cannot be variably located.... When the file referenced by filename-1 is merged control passes to first Collating Sequences SPECIAL-NAMES paragraph .] {GIVING file-4 OUTPUT PROCEDURE IS proc-nm-1 [THRU proc-nm-2]} MERGE . [COLLATING SEQUENCE IS alphabet-name-1] USING file-2 [file-3 .. COLLATING SEQUENCE option of MERGE statement that is defined in .Cobol Table Handling MERGE ♦ Combines two or more identically sorted files and makes records available in merged order MERGE file-1 { ON {ASCENDING DESCENDING} KEY id-1.PROGRAM COLLATING SEQUENCE specified in the Configuration Section Default is EBCDIC must not be open stmt in the OUTPUT PROCEDURE.. } .

half-yearly. Write the table structure with policy number. b. GO TO PARA-2 PARA-1. This is a variable length table 2. quarterly or annual premium. 77 I PIC 99. Store these totals in 2 tables . 77 TOTAL PIC 99. period and premium as fields. 4. Write the data division statements for the following table. PERFORM PARA-AGAIN VARYING I FROM 1 BY 1 UNTIL I > 4 AFTER J FROM 0 BY –1 UNTIL J < -2 AFTER K FROM 1 BY 2 UNTIL K > 8. 13. A table contains the monthly sales data for 12 months of the year and for the 4 sales zones where each zone has 8 districts.Cobol Exercises EXERCISES 1. b. The period depends on the policy. ADD A (I) TO TOTAL. PARA-2. The insurance company maintains the premium paid by the policy holders on a periodic basis. Compiler Directive . 3. a. 01 TABLE-2 REDEFINES TABLE-1. PERFORM PROCESS-ROUTINE VARYING A FROM 1 BY 1 UNTIL A = 15. 02 FILLER PIC X (9) VALUE IS “123456789”. 02 A OCCURS 9 TIMES PIC 9. 5. PERFORM PARA-1 VARYING I FROM 1 BY 2 UNTIL I > 9. How many times is the procedure named PARA-AGAIN executed? Which data name varied least rapidly and which varied most rapidly. The following are DATA DIVISION entries. PERFORM PROCESS-ROUTINE VARYING A FROM 1 BY 1 UNITL A > 15. The following is a PROCEDURE DIVISION statement. How many times will the procedure named PROCESS-ROUTINE be executed by the following PERFORM statements? a. The table contains marks of student for the each month for the whole year. Indicate how many elements of the array A would be added to TOTAL and what will be the final value of TOTAL when the control goes to PARA-2 in the following program segment? MOVE ZERO TO TOTAL.COPY . 1 TABLE-1. Write the Data division entries to define all these tables. The marks will be 3 digits. It can be a monthly. The premium is 13 digits with 2 decimal places.one district total and the other containing the zone totals. Write the PROCEDURE DIVISION statements to find the total sale of each district within each zone and then find the total sale of each zone.

] . or a (except COPY). These entries and procedures can then be saved in user-created libraries. 02 :TAG:-HOURS PIC S999 OCCURS 1 TO 52 TIMES DEPENDING ON :TAG:-WEEK OF :TAG:.. ♦ op-1 and op-2 can be either pseudo-text. The effect of processing a COPY statement is that the library text associated with text-name is copied into the source program. COBOL word Compiler Directive COPY – Example 01 :TAG:. Prewritten source program entries can be included in a source program at compile time. COPY PAYLIB REPLACING ==:TAG:== BY ==Payroll==. COPY { text-name lit-1 } [ { OF { lib-name IN } lit-2 } ] [ SUPPRESS ] [ REPLACING ( op-1 BY op-2 ) . Compilation of the source program containing COPY statements is logically equivalent to processing all COPY statements before processing the resulting source program. 02 :TAG:-GROSS-PAY PIC 9(5)V99. or procedures without re-coding them. inclusive. a literal.. 02 :TAG:-WEEK PIC S99. Thus. record descriptions. A COPY statement can appear in the source program anywhere a character string or a separator can appear. an installation can use standard file descriptions. beginning with the word COPY and ending with the period.Cobol Exercises The COPY statement is a library statement that places prewritten text in a COBOL program. . they can then be included in the source program by means of the COPY statement. the library text is copied unchanged Each COPY statement must be preceded by a space and ended with a separator period. an identifier. logically replacing the entire COPY statement. When the REPLACING phrase is not specified.

02 PAYROLL-HOURS PIC S999 OCCURS 1 TO 52 TIMES DEPENDING ON PAYROLL-WEEK OF PAYROLL.Specified then listing will not contain the statement within the COPY member .Can’t contain REPLACING option .Cobol Compiler Directives 01 PAYROLL. Compiler Directive COPY . 02 PAYROLL-GROSS-PAY PIC S9(5)V99.If not then listing will contain the statements with a C after the source program line number . 02 PAYROLL-WEEK PIC S99.Rules ♦ ♦ ♦ Copy statement can be nested but Should not cause recursion If SUPPRESS .

OBJECT . OFFSET. FLAGMIG.LINECOUNT (44) . DYNAM. FLAGSTD.DUMP. DATA.Cobol Compiler Options 14.RENT.FDUMP. but not fixed. Compiler Options ♦ ♦ Helps to control the compilation Specify these options in . SSRANGE. DECK. OPTIMIZE.There are default options when compiler is installed .PARM field of the JCL . FLAG. LIST.ADV. NAME. SIZE . SEQUENCE. CMPR2. FLAGSAA. TEST .APOST. XREF ♦ ♦ Debugging Literal delimiters .XREF/NOXREF . fixed by your installation . and diagnostics .Level 2: Those on PROCESS (or CBL) stmt . NUMBER. QUOTE. Watch out Precedence of Compiler Options . ZWB ♦ Maps. TRUNC. FASTSRT.CBL or PROCESS statement in program ♦ ♦ ♦ ♦ Most of the options come in pairs Some options have sub-parameters. SOURCE. MAP. RESIDENT.Level 4: (Lowest precedence) Installation defaults. OUTDD.Level 3: Those on the JCL PARM .0 Page 134 of 148 . LINECOUNT.COMPILE. SPACE. VBREF. TERMINAL. ADW. NUMPROC . listing. DBCS Cognizant Academy Ver 1. ♦ ♦ ♦ Object code generation Use of virtual storage Object code execution .Level 1: (Highest precedence) Installation defaults. LANGUAGE.BUFSIZE.

ADVANCING in your source code.Cobol ♦ ♦ . Valid COBOL source programs that compiled successfully under VS COBOL II Release 2 will also compile successfully under IBM COBOL for MVS & VM with CMPR2 in effect and will provide compatible results. All diagnostics and object code will be generated.LIB ♦ . IBM COBOL for MVS & VM uses these services for all storage requests. Do not try to run the object code generated if the compilation resulted in serious errors--the results could be unpredictable or an abnormal termination could occur. Compiler Options .EXIT ♦ ADV / NOADV Default is: ADV Provision of User Exit Reserved word list Processing of COPY ETC.0 Page 135 of 148 .. the compiler adds 1 byte to the record length to account for the printer control character. ♦ DATA(24/31) Default is: DATA(31) Language Environment provides services that control the storage used at run time. ♦ COMPILE / NOCOMPILE (W/E/S) Default is: NOCOMPILE(S) Abbreviations are: C / NOC Use the COMPILE option only if you want to force full compilation even in the presence of serious errors.WORD ADV has meaning only if you use WRITE . With ADV in effect. For reentrant programs. Cognizant Academy Ver 1. Use NOADV if you have already adjusted your record length to include 1 byte for the printer control character ♦ CMPR2 / NOCMPR2 Default is: NOCMPR2 Use CMPR2 when you want the compiler to generate code that is compatible with code generated by VS COBOL II Release 2. . . the DATA (24|31) compiler option and the HEAP run-time option control whether storage for dynamic data areas (such as WORKING-STORAGE section and FD record areas) is obtained from below the 16-megabyte line or from unrestricted storage.

. be certain that SYSPUNCH is defined in your JCL for compilation. DATA(31) has no effect ♦ DECK / NODECK Default is: NODECK Abbreviations are: D / NOD Use DECK to produce object code in the form of 80-column card images. However.Cobol Compiler Options When you specify the run-time option HEAP (BELOW).. .SYSPUNCH ddname must for DECK opt ♦ DYNAM / NODYNAM Default is: NODYNAM Abbreviations are: DYN / NODYN Use DYNAM to cause separately compiled programs invoked through the CALL literal statement to be loaded dynamically at run time. the DATA (24|31) compiler option has no effect.With NORENT compiler option. This ensures that the data will be addressable by the called program. Specify the DATA (24) compiler option for programs running in 31-bit addressing mode that is passing data parameters to programs in 24-bit addressing mode. If you use the DECK option. storage for dynamic data areas is allocated from below the line if you compiled the program with the DATA (24) compiler option or from unrestricted storage if you compiled with the DATA (31) compiler option. Any CALL identifier statements that cannot be resolved in your program are also handled as dynamic calls. with HEAP (ANYWHERE) as the run-time option.DYNAM forced RESIDENT option Cognizant Academy Ver 1.0 Page 136 of 148 . the storage for all dynamic data areas is allocated from below the 16-megabyte line. DYNAM causes dynamic loads (for CALL) and deletes (for CANCEL) of separately compiled programs at object time.

or U Use FLAG (x) to produce diagnostic messages for errors of a severity level x or above at the end of the source listing. or REPLACE statements. include in your JCL DD statements for the library or libraries from which the compiler can take the copied code. y) to produce diagnostic messages for errors of severity level x or above at the end of the source listing.Default is: NOLIB Abbreviation is: None If your program uses COPY. W. W. y). or U y:.Cobol ♦ FLAG(x. and also include a JCL DD statement to allocate SYSUT5. In addition. .Control listing of error messages ♦ LIB / NOLIB . To use FLAG (x..I.0 Page 137 of 148 . you need to specify the LIB compiler option. for COPY and BASIS statements.Allocate . Use FLAG (x. you must also specify the SOURCE compiler option. NOFLAG will not suppress error messages for compiler options.y) / NOFLAG Compiler Options Default is: FLAG(I) Abbreviations are: F / NOF x :. with error messages of severity y and above to be embedded directly in the source listing. S. E.I. The message code is then followed by the message text Use NOFLAG to suppress error flagging. Error messages in the source listing are set off by embedding the statement number in an arrow that points to the message code. You will also get these in your output listing: ♦ ♦ ♦ ♦ Global tables Literal pools Information about Working-Storage Size of the program's Working-Storage and its location in the object code if the program is compiled with the NORENT option . S. BASIS.SYSLIB and SYSUT5 ddnames ♦ LIST / NOLIST Default is: NOLIST Use LIST to produce a listing of the assembler-language expansion of your source code. The severity coded for y must not be lower than the severity coded for x. E.LIST and OFFSET are mutually exclusive and if both given LIST ignored Cognizant Academy Ver 1.

0 Page 138 of 148 . and XREF listings. LIST. If you are doing a batch compilation and LIB and NUMBER are in effect. WORKING-STORAGE SECTION. the compiler generates line numbers for your source statements and uses those numbers as references in listings. the compiler assigns to it a line number with a value one number higher than the line number of the preceding statement. When a line number is found to be out of sequence. Use NONUMBER if you do not have line numbers in your source code. and the sequence is checked according to numeric collating sequence. or if you want the compiler to ignore the line numbers you do have in your source code. ♦ NUMBER / NONUMBER Default is: NONUMBER Abbreviations are: NUM / NONUM Use NUMBER if you have line numbers in your source code and want those numbers to be used in error messages and MAP. you can also print an embedded MAP report in the source code listing. columns 1 through 6 are checked to make sure that they contain only numbers. Sequence checking continues with the next statement. The condensed MAP information is printed to the right of data-name definitions in the FILE SECTION. be sure that your source program line numbers and the COPY member line numbers are coordinated. based on the newly assigned value of the previous line. The sequence numbers of the entire input file must be in ascending order. Map output includes: ♦ ♦ ♦ ♦ ♦ DATA DIVISION map Global tables Literal pools Nested program structure map. all programs in the batch compile will be treated as a single input file. If you request NUMBER. If you use COPY statements and NUMBER is in effect. and program attributes Size of the program's Working-Storage and its location in the object code if the program is compiled with the NORENT option By selecting the MAP option. and LINKAGE SECTION of the DATA DIVISION. With NONUMBER in effect. Cognizant Academy Ver 1.Cobol ♦ MAP / NOMAP Compiler Options Default is: NOMAP Use MAP to produce a listing of the items you defined in the DATA DIVISION.

the following are produced: ♦ ♦ ♦ Global tables Literal pools Size of the program's Working-Storage. Some implicit sign repair might occur during conversion. Numeric comparisons are performed by a decimal compare. This option is not as efficient as NUMPROC (PFD).OFFSET & LIST are mutually exclusive. operations. With OFFSET. object code size will be increased. include a SYSLIN DD statement in your JCL for compilation. In addition. The only difference between DECK and OBJECT is in the routing of the data sets: ♦ ♦ ♦ DECK output goes to the data set associated with SYSPUNCH ddname. . not a logical compare. NUMPROC (PFD) is a performance option that can be used to bypass invalid sign processing. If you specify OBJECT. statement references.mutually exclusive OFFSET / NOOFFSET Default is: NOOFFSET Abbreviations are: OFF / NOOFF Use OFFSET to produce a condensed PROCEDURE DIVISION listing. Using NUMPROC (PFD) can affect class tests for numeric data Use NUMPROC (MIG) to aid in-migrating OS/VS COBOL programs to IBM COBOL for MVS & VM. Cognizant Academy Ver 1. OBJECT / NOOBJECT Default is: OBJECT Abbreviations are: OBJ / NOOBJ Use OBJECT to place the generated object code on disk or tape to be later used as input for the linkage editor. NOOBJECT & TEST . the condensed PROCEDURE DIVISION listing will contain line numbers. When NUMPROC (MIG) is in effect. and the location of the first instruction generated for each statement.Cobol ♦ NUMPROC(PFD or NOPFD or MIG) Compiler Options Default is: NUMPROC(NOPFD) Use NUMPROC (NOPFD) if you want the compiler to perform invalid sign processing. and its location in the object code if the program is compiled with the NORENT option. and there could be an increase in run-time overhead to validate all signed data. the following processing occurs: ♦ ♦ ♦ ♦ ♦ Preferred signs are created only on the output of MOVE statements and arithmetic No explicit sign repair is done on input. OBJECT output goes to the data set associated with SYSLIN ddname.0 Page 139 of 148 .

But when the program is ready for final test. However.0 Page 140 of 148 . if a program is used frequently without recompilation. For unit testing your programs. Eliminate duplicate computations (such as subscript computations and repeated statements) that have no effect on the results of the program. Aggregate moves of contiguous items (such as those that often occur with the use of MOVE CORRESPONDING) into a single move. eliminating the need for linkage code. The FULL suboption requests that the compilers discard any unreferenced data items from the DATA DIVISION. is further discussed in "PERFORM Procedure Integration" If procedure integration cannot be done.mutually exclusive ♦ OUTDD(ddname) . so that the tested code and the production code are identical. code that can never be performed (unreachable code elimination). Both the source and target must be contiguous for the moves to be aggregated. known as procedure integration. and identify with a warning message. the optimizer uses the simplest linkage possible (perhaps as few as two instructions) to get to and from the called program. including those generated by the compiler that are not evident from looking at the source program. the overhead for OPTIMIZE might outweigh its benefits if you re-compile frequently. specify OPTIMIZE. OPTIMIZE & TEST . The purpose of the OPTIMIZE compiler option is to do the following: Eliminate unnecessary transfers of control or simplify inefficient branches. Eliminate constant conditional expressions. unless you are using the assembler language expansion (LIST option) to fine tune your program.To get run-time DISPLAY output on a data set other than SYSOUT Cognizant Academy Ver 1. Simplify the compiled code for both a PERFORM statement and a CALL statement to a contained (nested) program. Delete from the program. Eliminate constant computations by performing them when the program is compiled. and suppress generation of code to initialize these data items to their VALUE clauses. Where possible. You might also want to use the option during development.Cobol ♦ OPTIMIZE / NOOPTIMIZE Compiler Options The COBOL optimizer is activated when you use the OPTIMIZE compiler option. you might find it easier to debug code that has not been optimized. the optimizer places the statement inline. This optimization.

TEST has two suboptions. SOURCE must be specified if you want embedded messages in the source listing.Have RESIDENT option for all programs in a unit unless the run-time option MIXRES has been specified. or neither of the suboptions: Cognizant Academy Ver 1. just one of the suboptions. ♦ RENT / NORENT . you can specify both. The amount of debugging support available depends on which TEST suboptions you use. The delimiter character used as the opening delimiter for a literal must be used as the closing delimiter for that literal. ♦ SPACE (1/2/3) . double. ♦ TEST / NOTEST Default is: NOTEST Use TEST to produce object code that enables Debug Tool to perform batch and interactive debugging. The TEST option also allows you to request that symbolic variable be included in the formatted dump produced by Language Environment.0 Page 141 of 148 . ♦ SOURCE / NOSOURCE Default is: SOURCE Abbreviations are: S / NOS Use SOURCE to get a listing of your source program.Cobol ♦ QUOTE / APOST Compiler Options Default is: QUOTE Abbreviations are: Q / APOST Use QUOTE if you want the figurative constant [ALL] QUOTE or [ALL] QUOTES to represent one or more quotation mark (") characters. regardless of whether the APOST or QUOTE option is in effect. Use NOTEST if you do not want to generate object code with debugging information and do not want the formatted dump to include symbolic variables. Note: Either quotes or apostrophes can be used as literal delimiters.object code is to be reentrant . Use APOST if you want the figurative constant [ALL] QUOTE or [ALL] QUOTES to represent one or more apostrophe (') characters. or triple spacing in your source code listing. This listing will include any statements embedded by PROCESS or COPY statements.to select single. Use NOSOURCE to suppress the source code from the compiler output listing.

SYM: .Hooks will be generated at all program entry and exit points. and CALL statements.Dictionary and calculation tables will be generated.The hook-location suboption controls where compiled-in hooks will be generated to provide information to the debugger. hooks will be generated at all date processing statements.No hooks will be generated. if the DATEPROC option is in effect. if the DATEPROC option is in effect.Use it while testing Cognizant Academy Ver 1.Hooks will be generated at all statements. The reference modification starting position is not greater than the current length of the The reference modification length value (if specified) is greater than or equal to 1.0 Page 142 of 148 .Hooks will be generated at all program entry and exit points and at all path points. Reference modification expressions will be checked to ensure that: ♦ ♦ ♦ ♦ The reference modification starting position is greater than or equal to 1. and at all program entry and exit points. In addition. all path points. A path point is anywhere in a program where the logic flow is not necessarily sequential or can change. PATH: .Hooks will be generated at every statement and label. an area beyond the end of the subject data item. Variable-length items will also be checked to ensure that the reference is within their maximum defined length. hooks will be generated at all date processing statements. STMT: . the effective address is checked to ensure that it does not cause a reference outside the region of the table. . BLOCK: . ALL: . In addition. Symbol: . as well as at all program entry and exit point. PERFORM loops. ON SIZE ERROR phrases. Some examples of path points are IF-THEN-ELSE constructs. ♦ SSRANGE / NOSSRANGE Default is: NOSSRANGE Abbreviations are: SSR / NOSSR Use SSRANGE to generate code that checks if subscripts (including ALL subscripts) or indexes try to reference an area outside the region of the table. NOSYM: .Dictionary and calculation tables will not be generated. rather.Cobol Compiler Options Hook: . The reference modification starting position and length value (if specified) do not reference subject data item. Each subscript or index is not individually checked for validity.The symbol-table suboption controls whether dictionary tables will be generated. NONE: .

fullwords. When TRUNC (OPT) is specified. with no truncation. boundaries. either truncating to the number of digits in the PICTURE clause. When TRUNC (STD) is in effect. When TRUNC (BIN) is in effect: BINARY receiving fields are truncated only at halfword. or the sending field in the MOVE statement. TRUNC (BIN) :♦ ♦ ♦ ♦ ♦ The TRUNC(BIN) option applies to all COBOL language that processes USAGE BINARY data. or to the size of the binary field in storage (halfword. The results are manipulated in the most optimal way. TRUNC (OPT): . fullword. Use NOVBREF for more efficient compilation. fullword.Cobol ♦ TRUNC (OPT or STD or BIN) Compiler Options Default is: TRUNC(STD) TRUNC (STD): Use TRUNC(STD) to control the way arithmetic fields are truncated during MOVE and arithmetic operations. is truncated to the number of digits in the PICTURE clause of the BINARY receiving field.TRUNC (OPT) is a performance option. receiver is numeric. TRUNC (STD) applies only to USAGE BINARY receiving fields in MOVE statements and arithmetic expressions. VBREF also produces a summary of how many times each verb was used in the program. the final result of an arithmetic expression. the compiler assumes that the data conforms to PICTURE and USAGE specifications of the USAGE BINARY receiving fields in MOVE statements and arithmetic expressions.0 Page 143 of 148 . VBREF / NOVBREF Default is: NOVBREF Use VBREF to get a cross-reference among all verb types used in the source program and the line numbers in which they are used. Cognizant Academy Ver 1. or doublewords when the The full binary content of the field is significant. or doubleword). or doubleword BINARY sending fields are handled as halfwords. DISPLAY will convert the entire content of the binary field. TRUNC (BIN) has no effect when the receiver is not numeric.

On the right of source lines that reference intrinsic functions. EBCDIC data-names and procedure-names are listed in alphanumeric order. XREF (FULL). IGYC are the first 4 standard characters of the name. XREF (SHORT) applies to DBCS data names and procedure-names as well as EBCDIC names. Use XREF to get a sorted cross-reference listing. If you use XREF and SOURCE. DBCS data-names and procedure-names are listed based on their physical order in the program. and appear before the EBCDIC data-names and procedure-names. and if a program name is external (EXT). or XREF (SHORT). If you use XREF and NOSOURCE.Are the ending characters of the name of the reserved word table (IGYCxxxx) to be used in your compilation. External program names are identified as such. (UND or DUP will be printed). Also included is a section listing all the program names that are referenced in your program. Use WORD(xxxx) to specify that an alternate reserved word table is to be used during compilation. Information included in the embedded references lets you know if an identifier is undefined or defined more than once. DBCS data-names and procedure-names are ordered as specified by the DBCS ordering program. XREF (SHORT) will print only the explicitly referenced variables in the cross-reference listing.Cobol ♦ WORD(xxxx) / NOWORD Default is: NOWORD Abbreviations are: WD / NOWD Compiler Options xxxx :. NOXREF suppresses this listing.0 Page 144 of 148 . and xxxx can be 1 to 4 characters in length. you'll get only the sorted cross-reference listing. Line number references or other information. Alternate reserved word tables provide changes to the IBM-supplied default reserved word table. In this case. if an item is implicitly defined (IMP). Cognizant Academy Ver 1. the letters 'IFN' will appear with the line numbers of the location where the function's arguments are defined. and the line number where they are defined. cross-reference information will also be printed on the same line as the original source in the listing. ♦ XREF(FULL or SHORT) / NOXREF Default is: NOXREF Abbreviations are: X / NOX You can choose XREF. unless the DBCSXREF installation option is selected with a DBCS ordering program. will appear on the right hand side of the listing page. such as special registers or figurative constants.

OBJECT' ♦ CBL LIST. ZWB affects how the program runs.Cobol ♦ ZWB / NOZWB Compiler Options Default is: ZWB With ZWB.OBJECT IDENTIFICATION DIVISION. the same COBOL source program can give different results. Such items always have their sign removed before the comparison is made to the alphanumeric field. Cognizant Academy Ver 1. its use in comparisons is not affected by ZWB. Compiler option .Coding Example ♦ //COB EXEC PGM=IGYCRCTL.OBJECT IDENTIFICATION DIVISION. // PARM='LIST. Use NOZWB if you want to test input numeric fields for SPACES. the compiler removes the sign from a signed external decimal (DISPLAY) field when comparing this field to an alphanumeric elementary field during execution. If the external decimal item is a scaled item (contains the symbol 'P' in its PICTURE characterstring). depending on the option setting. PROGRAM-ID. NOCOMPILE (S).NOCOMPILE(S). ♦ PROCESS LIST. myprog. myprog.0 Page 145 of 148 . PROGRAM-ID.NOCOMPILE(S).

Implementor defined (VSAM) ♦ Successful Completion-0 0 .Optional file not present ♦ At end condition-1 0 .Logic error 9 .Status key 2 ♦ Status key 1 tells the type of error ♦ Status key 2 gives the detail ♦ Status key 1 0 .Due to boundary violation 5 .Duplicate .Successful Completion 1 .Status key 1 .Relative key > max possible ♦ Invalid Key-2 1 .Invalid open mode on open 8 .End of file 4 .0 Page 146 of 148 .Ascending key violation/Rewrite change primary Key 2 . (Re) Write 2 .At end condition 2 . Alternate or relative key) 3 .Cobol APPENDIX 1 APPENDIX 1 FILE STATUS CODES AND MEANING ♦ 2 char code .No further info 1 .Open of file closed with lock 9 .Read.Write beyond boundary ♦ Permanent error-3 0 .no further info 4 .Invalid key condition 3 .Length error for Fixed files 5 .Record not found 4 .DCB conflict during open ♦ Logic error-4 Cognizant Academy Ver 1.Duplicate key when not allowed (Primary.File not available (ddname not found/defined) 7 .Permanent error condition 4 .

File verified APPENDIX 1 Cognizant Academy Ver 1.0 Page 147 of 148 .Rewrite or Delete after unsuccessful Read 4 .Password failure 2 .Close of file not in open stat 3 .Read on file not opened for Input or I-O 8 .Invalid/Incomplete file info 6 .Write on file not opened for Output or I-O or Extend 9 .9(VSAM) 0 .Cobol 1 .Open of file in open status 2 .No position for Read next 7 .No DDname found 7 .Resource not available 4 .No further info 1 .No file position for cmpr2 opt 5 .Rewrite changed record len or Write record len > max 5 .Logic error 3 .Open successful.Rewrite on file not opened for I-O ♦ Implementor def.

Anne prince .Nancy stern .Philippakis and Kazmier .Roy & Dastidar . 2. .Paul N.guide for programmers 2 ed.Cobol References References 1. 4. 3. . Stern and Stern Structured COBOL Programming Structured COBOL COBOL Programming How to design & develop COBOL programs VS COBOL II .

Sign up to vote on this title
UsefulNot useful

Master Your Semester with Scribd & The New York Times

Special offer for students: Only $4.99/month.

Master Your Semester with a Special Offer from Scribd & The New York Times

Cancel anytime.