Cobol

5,536 views

Published on

Published in: Education, Technology
3 Comments
9 Likes
Statistics
Notes
No Downloads
Views
Total views
5,536
On SlideShare
0
From Embeds
0
Number of Embeds
115
Actions
Shares
0
Downloads
291
Comments
3
Likes
9
Embeds 0
No embeds

No notes for slide

Cobol

  1. 1. 1 Table of Contents UNIT 1. Introduction to Language Features COMMON BUSINESS ORIENTED LANGUAGE COBOL PROGRAM ORGANIZATION COBOL LANGUAGE STRUCTURE STRUCTURE OF COBOL PROGRAM CHARACTER SET OF COBOL SAMPLE COBOL PROGRAM CODING FORMAT USER-DEFINED WORDS UNIT 2. The Organization of a COBOL Program IDENTIFICATION DIVISION ENVIRONMENT DIVISION DATA DIVISION DATA-ITEMS LEVEL NUMBERS SPECIAL LEVEL NUMBERS W-S DECLARATIONS FILLER PICTURE CLAUSE USAGE CLAUSE VALUE CLAUSE REDEFINES CLAUSE DULPICATE DATA NAMES RENAMES CLAUSE FIGURATIVE CONSTANTS EDITED FIELDS MORE EDITING CHARACTER EXAMPLES
  2. 2. 2 UNIT 3. PROCEDURE DIVISION PROCEDURE DIVISION COBOL VERBS PARAGRAPHS TERMINATOR STATEMENTS SCOPE TERMINATORS DISPLAY VERB ACCEPT VERB MOVE VERB ELEMENTARY & GROUP MOVES CORRESPONDING PHASE REFERENCE MODIFICATION ADD VERB ADD CORRESPONDING STATEMENT ON SIZE ERROR PHRASE NUMERIC DATA SUBTRACT VERB SUBTRACT CORRESPONDING STATEMENT MULTIPLY VERB DIVIDE VERB COMPUTE STATEMENT PERFORM STATEMENT PERFORM THROUGH PERFORM N TIMES PERFORM…VARYING IN-LINE PERFORM RELATIONAL EXPRESSIONS IF STATEMENT COMPOUND CONDITIONALS CLASS CONDITION CONTINUE & NEXT STATEMENT EVALUATE STATEMENT SET TO TRUE
  3. 3. 3 UNIT 4. FILE HANDLING IN COBOL FILES FIXED VS VARIABLE LENGTH RECORDS FILE-CONTROL-SEQUENTIAL ACCESS MODE FILE STATUS CLAUSE I-O CONTROL PARAGRAPH FILE SECTION FILE OPERATIONS OPEN MODES READ-SEQUENTIAL ACCESS END OF FILE PROCESSING READ – RANDOM ACCESS READ – DYNAMIC ACCESS START STATEMENT WRITE STATEMENT WRITE…FROM READ…INTO REWRITE & DELETE APPENDING TO SEQUENTIAL FILES FILE COMPARISON CLOSE STATEMENT SEQUENTIAL FILES INDEXED FILES INVALID KEY ACCESS MODE: SEQUENTIAL & RANDOM ACCESS MODE: DYNAMIC RELATIVE FILES
  4. 4. 4 UNIT 5. TABLE HANDLING INTRODUCTION: TABLE HANDLING OCCURS CLAUSE SUBSCRIPT INDEXING ONE DIMENSIONAL TABLE TWO DIMENSIONAL TABLE MULTIDIMENTIONAL TABLE TABLE-SORTING SET SEARCH BINARY SEARCH UNIT 6. Library Services COPY STATEMENT NESTED COPY COPY REPLACING COPY PSEUDO-TEST REPLACE PSEUDO-TEST
  5. 5. 5 UNIT 7. CHARACTER HANDLING STRING UNSTRING STATEMENT INSPECT TALLYING STATEMENT INSPECT REPLACING STATEMENT EXAMINE STATEMENT UNIT 8. SORT / MERGE SORT/MERGE SORT STATEMENT MERGE STATEMENT SORT PROCEDURES RELEASE STATEMENT RETURN STATEMENT UNIT 9. CALL and LINKAGE CALL STATEMENT CALL BY CONTENT/REFERENCE LINKAGE SECTION
  6. 6. 6 UNIT 1     Introduction To Language Features
  7. 7. 7 Common Business Oriented Language •1959 – New Language is named COBOL •1960 – Codasyl established COBOL maintenance committee •1961 – 1st version of complier made available. Users started writing programs •1968 –2nd version of cobol was approved and standardized by ANSI •1974 – Revised and released as COBOL-74 •1985- Revised and released as COBOL-85 To meet the increasing demands for a high level language suitable for business data processing, the United States Department of Defense Convened a Conference on 28th and 29th of May 1958. Three committee were formed for the actual design of the language. In September 1959 the short term committee submitted a report to the Defense Directorate thus COBOL came into existence. COBOL is known as a structured programming language because it allows programmers to segregate the modules and put them into different paragraphs in a more efficient way. Some of the features of COBOL are It is English-like and more easily readable Efficient file handling capabilities. More than 70% of business applications are running on COBOL Reduces the efforts required for documentation of the program.
  8. 8. 8 The following features are available with VS COBOL II: - MVS/XA and MVS/ESA support - The compiler and the object programs it produces can be run in either 24- or 31-bit addressing mode COBOL PROGRAM ORGANIZATION Notes: The four divisions of the COBOL source program are : • IDENTIFICATION DIVISION This division’s primary purpose is to name the program • ENVIRONMENT DIVISION This division is primarily used to tell the computer about the input and output devices such as files or printers. IDENTIFICATION DIVISION ENVIRONMENT DIVISION DATA DIVISION PROCEDURE DIVISION
  9. 9. 9 • DATA DIVISION This division describes the data the program will be using and carves out sections of memory to map the data. Here you would distinguish between data, which will be used for a “ scratch pad” area called WORKING-STORAGE and the holding area for data that will be used by the files. • PROCEDURE DIVISION The PROCEDURE DIVISION is the section of our program where the logic or commands reside. This is the logic or rules we will use to manipulate the data defined in the DATA DIVISION to solve a business problem.
  10. 10. 10 Cobol Language Structure . Characters · Character String · COBOL Words · User-Defined Words · Reserved Words · Figurative Words · Special Registers · IBM Extensions · Non-numeric and numeric Literals
  11. 11. 11 Structure of a Cobol Program Examples • Divisions DATA DIVISION • Sections or Paragraphs PROGRAM-ID FILE SECTION, 100-PARA • Statements MOVE A TO B • Sentences IF A>B MOVE A TO B ELSE ADD C TO D Notes: All COBOL programs should follow the structure. Rules of coding varies, depending on the compiler versions but the structure remains same. A period (.) is a must at the end of each sentence and indicates the end of the sentence.
  12. 12. 12 Character Set of COBOL COBOL supports the following characters Numbers : 0-9 Alphabets : a-z, A-Z Spaces or blanks Arithmetic operators : ex: **, *, +, -, / Special characters : ex: - / , ; Notes: The COBOL dictionary words used for coding are called COBOL reserved words and they should not be used as user-defined words. Lower case alphabets can be used for coding depending on the compiler version.comma (,) or space is used as separators for user-defined words.
  13. 13. 13 Sample COBOL Program Columns 1 6 7 8 11 12 72 73 80 * This is a sample program IDENTIFICATION DIVISION. PROGRAM-ID. SAMPLE. ENVIRONMENT DIVISION. DATA DIVISION. WORKING-STORAGE SECTION. 01 A PIC 9(2) VALUE 20. 01 B PIC 9(2) VALUE 3O. 01 C PIC 9(3) VALUE ZEROS. PROCEDURE DIVISION. DISPLAY ‘THE SUM IS’. ADD A ,B GIVING C. DISPLAY C. STOP RUN. Notes: 1-6 -------------- Sequence numbers 7 -------------- Indicator/Comment/Continuation 8-11 -------------- Area A 12-72 -------------- Area B 73-80 -------------- Descriptor This foil shows a sample COBOL program to ‘ADD’ two numbers and ‘DISPLAY’ the sum. SAMPLE is the program name. SAMPLE, A, B AND C are called user-defined words. A, B,C are called variables or data-items.
  14. 14. 14 Coding Format Columns Name Purpose 01-06 07 08-11 12-72 73-80 Sequence Indicator Area A Area B Description Sequence numbers are generated by Cobol Compiler for each line. To mark an asterisk (*) or a slash (/) for comment line, or a hyphen (-) for continuation of a statement. All division headings, section and paragraph headings and ‘01’ level entries should begin from this area. All Cobol statements and sentences should lie within this area Any thing written in this area is ignored. Notes: COBOL coding should follow the standard format. The Screen is divided into different areas for the purposes explained above. All statements indicating action are called COBOL verbs and should begin from 12th column or after. -E.g MOVE, ADD, DIVIDE, STOP RUN
  15. 15. 15 User-defined Words Valid Invalid Reason TOTAL-OF-FIGURES DATA Cobol reserved word 34B100-PARA1 -48B Hyphen in beginning GROSS-PAY GROSS PAY space in b/w 2 words Literals Examples Numeric constants 35, -345.67 Alphanumeric constants ‘Leo talstoy’ ‘ka01-h215’ •Paragraph names, Identifiers, File names can be defined by users. •The terms identifiers, data-names, variables, data-items are often used interchangeably indicates memory.
  16. 16. 16 Notes: All user-defined words should conform to following rules • Length should not exceed 30 characters. • At least one character must be an alphabet. • Spaces and special characters are not allowed. • Word can contain hyphens (-) but not in the beginning or at the end Cannot be a COBOL reserved word
  17. 17. 17 UNIT 2 THE ORGANIZATION OF A COBOL PROGRAM
  18. 18. 18 IDENTIFICATION DIVISION. PROGRAM-ID. <Pgm-name> AUTHOR. <Pgmr-name> DATE –WRITTEN. <Entry> DATE-COMPILED. <Entry> SECURITY. <Entry> Required Required Optional Optional Optional Optional At least one space required after the period Notes: The Identification Division must be the first division in every COBOL source program. It must be coded as IDENTIFICATION DIVISION or ID DIVISION followed by a separator period. IDENTIFICATION DIVISION
  19. 19. 19 ENVIRONMENT DIVISION ENVIRONMENT DIVISION. CONFIGURATION SECTION. SOURCE-COMPUTER. <Entry>. OBJECT-COMPUTER. <Entry>. INPUT-OUTPUT SECTION. FILE-CONTROL. ---------------------------- ---------------------------- I-O-CONTROL. ----------------------------- ----------------------------- Notes: The Environment Division is divided into two sections: • The CONFIGURATION SECTION The Configuration Section is an optional section for programs which describe the computer environment on which the program is compiled and executed. The Configuration Section can be specified only in the ENVIRONMENT DIVISION of the outermost program of a COBOL source program. • The INPUT-OUTPUT SECTION The Input-Output Section of the Environment Division contains two paragraphs: FILE-CONTROL paragraph I-O-CONTROL paragraph
  20. 20. 20 FILE-CONTROL paragraph The keyword FILE-CONTROL can appear only once, at the beginning of the FILE-CONTROL paragraph. It must begin in Area A, and be followed by a separator period. The FILE-CONTROL paragraph is optional. The FILE-CONTROL paragraph associates each file in the COBOL program with an external dataset, and specifies file organization, access mode, and other information. There are three formats for the FILE-CONTROL paragraph: QSAM, SAM, and VSAM sequential file entries VSAM indexed file entries VSAM relative file entries. The FILE-CONTROL paragraph begins with the word "FILE-CONTROL", followed by a separator period. It must contain one and only one entry for each file described in an FD or SD entry in the Data Division. Within each entry, the SELECT clause must appear first, followed by the ASSIGN clause. The other clauses can appear in any order.
  21. 21. 21 I-O-CONTROL paragraph Specifies information needed for efficient transmission of data between the external data set and the COBOL program. The series of entries must end with a separator period The keyword I-O-CONTROL can appear only once, at the beginning of the paragraph. The word I-O-CONTROL must begin in Area A, and must be followed by a separator period. Each clause within the paragraph can be separated from the next by a separator comma or a separator semicolon. The order in which I-O-CONTROL paragraph clauses are written is not significant
  22. 22. 22 DATA DIVISION Data division is the third and most frequently used division in all programs. Every variable required by the program should be declared in appropriate section of the data division, before using in procedure division The Data Division is divided into three sections: . File Section Defines the structure of data files (including sort-merge files). . Working-Storage Section Describes records and subordinate data items that are not part of data files but are required by the program. . Linkage Section Describes data made available by another program. It usually appears in the called program and describes data items that are referred to by the calling and the called programs. Each section has a specific logical function within a COBOL source program, and each can be omitted from the source program when that logical function is not needed. If included, the sections must be written in the order shown.
  23. 23. 23 DATA DIVISION. FILE SECTION. FD . --------------- ---------------- ---------------- WORKING-STORAGE SECTION. DATA TYPES 01 VAR-1 PIC A(5). -Alphabetic 01 ID-1 PIC X(10) -Alphanumeric 01 DATA-NAME PIC 9(5) -Numeric Level number picture data type (length) Clause LINKAGE SECTION. record-description-entry data-item-description-entry
  24. 24. 24 DATA-ITEMS Explicitly identifies the data being described The data-item must be the first word following the level-number. The data-item values can be changed during program execution. A data-item name cannot be the same as a section-name or a paragraph Notes: Data item is a user-defined word which is associated with Level number. COBOL Reserved words should not be Data items.
  25. 25. 25 Level Numbers . Range of level numbers available are 01 to 49 and 66 level specified for RENAMING CLAUSE 77 levels specified exclusively for elementary item 88 levels specified for CONDITION NAMES. . An elementary item can be declared with level numbers . 01 and 77 01 and 77 level entries must begin from area A and other level entries can begin from any where in area A or area B Notes: Level represents the nature of a data item. The level-number specifies the hierarchy of data within a record, and identifies special-purpose data entries. A level- number begins a data description entry, a renamed or redefined item, or a condition-name entry. A level- number has a value taken from the set of integers between 01 and 49, or from one of the special level-numbers, 66, 77, or 88.
  26. 26. 26 Level-number 01 and 77 must begin in Area A and must be followed either by a separator period; or by a space, followed by its associated data-name, FILLER, or appropriate data description clause. Level numbers 02 through 49 can begin in Areas A or B and must be followed by a space or a separator period. Level number 66 and 88 can begin in Areas A or B and must be followed by a space. Single-digit level-numbers 1 through 9 can be substituted for level-numbers 01 through 09. Successive data description entries can start in the same column as the first or they can be indented according to the level-number. Indentation does not affect the magnitude of a level-number. When level-numbers are indented, each new level-number can begin any number of spaces to the right of Area A. The extend of indentation to the right is limited only by the width of Area B. Higher numbered level(s) represent subordinate definition(s). Level numbers need not be consecutive(but should be in ascending order)
  27. 27. 27 Special Level Numbers LEVEL-66 contains a RENAMES clause. It regroups previously defined names LEVEL-77 defines ELEMENTARY items with no subdivision and are unique LEVEL-88 establishes condition-name entries, associated with a VALUE clause 66 data-name-1 renames-clause. 88 condition-name-1 value-clause. Notes: LEVEL-66 regroups previously defined items. A level-66 entry cannot rename another level-66 entry, nor can it rename a level-01, level-77, or level-88 entry. All level-66 entries associated with one record must immediately follow the last data description entry in that record. LEVEL-77 items are ELEMENATARY items with no subdivision. LEVEL-77 names are unique because they can not bequalified. LEVEL-88 describes condition-names. LEVEL-88 can be used to describe both elementary and group items.
  28. 28. 28 Describes the characteristics of the data Picture Clause CODE Meaning A Alphabetic or space B Blanks or spaces G or N Graphical data 9 Indicates a Numeric X Indicates an Alpha Numeric P Indicates the position of the assumed Decimal point when the point lies Outside the data item. V Indicates the position of assumed Decimal point of numeric field. S Indicates whether the data item signed.
  29. 29. 29 Notes: Picture clause specifies the data type of an identifier. Identifier with PIC clause ‘9’ implies that it is numeric data type, which can take art in arithmetic computations. ‘V’ and ‘S’ clauses are allowed with numeric data types only. ‘X’ clause represents an alphanumeric data type which can hold any character including numbers also. ‘A’ clause indicates an alphabetic data type. Group items are always considered as alphanumeric only. Therefore GROSS-PAY, DEDUCTIONS can not be used for computations
  30. 30. 30 W-S Declarations WOKING-STORAGE SECTION. 01 PAY. 05 GROSS-PAY.Alternatively 10 BASIC PIC 9(4)V99. 10 DA PIC 9(4)V99.9(4)V9(2) 10 HRA PIC 9(4)V999999V99 05 DEDUCTIONS. 07 PF-DED PIC 9(3)V99. 07 IT-DED PIC 9(3)V99. 05 NET-PAY PIC 9(4)V99. 05 NAME PIC A(5).AAAAA 05 E-CODE PIC X(6).XXXXXX Notes: Pay, gross-pay, deductions are called group items and they don’t have PICTURE clause. Other elements with picture clause are called elementary items, which cannot be broken further. Pay is a Group item is divided into Gross-pay, Deductions, net-pay, name, e-code further Gross-pay sub-divided into Basic, DA, HRA and DEDUCTIONS sub-divided into PF-DED and IT-DED.
  31. 31. 31 FILLER FILLER is a COBOL Reserved Word used to describe data fields that will not be referenced in the PROCEDURE DIVISION. If the data-name of FILLER clause is omitted, the data item being described is treated as though it was FILLER 01 EMPLOYEE-RECORD. 05 EMPLOYEE-TYPE PIC X. 05 EMPLOYEE-SERIAL PIC X(6). 05 EMPLOYEE-NAME PIC X(30). 05 PIC X(2). 05 EMPLOYEE-ADDRESS PIC X(60). 05 FILLER PIC X(34).
  32. 32. 32 Notes: FILLER is a data item that is not explicitly referred to in a program. The key word FILLER is optional. If specified, FILLER must be the first word following the level-number. IF data-name or FILLER clause is omitted, the data item being described is treated as though FILLER had been specified. The VALUE clause may be used on FILLER items, e.g. to assure BLANKS in header lines between fields. In a MOVE CORRESPONDING statement ,or in an ADD CORRESPONDING or SUBTRACT CORRESPONDING statement ,FILLER items are ignored. In an INITIALIZE statement, elementary FILLER items are ignored.
  33. 33. 33 USAGE Clause <level number> data-name [PIC X(n)] [USAGE] COMP COMP-1 COMP-2 COMP-3 COMP - Binary Representation Size: Half/Full/Double word COMP-1 - Hexa Decimal Representation Size: Full word for Float COMP-2 - Hexa Decimal Representation Size: Double word for Float for float COMP-3 - Packed Decimal Representation Size: round(n/2)+1 Where n is number of digits. Notes: The USAGE clause can be specified for a data description entry with a level-number other than 66 or 88. However, if it is specified at the group level, it applies to each Elementary item in the group. The usage of an elementary item must not contradict the usage of a group to which the elementary item belongs. The USAGE clause specifies the format in which data is represented in storage. The format can be restricted if certain Procedure Division statements When the USAGE clause is not specified at either the group or elementary level, it assumed that the usage is DISPLAY
  34. 34. 34 Computational ( COMP) Usage When usage is specified as COMP, the numeric data item is represented in pure binary. The item must be an integer( no assumed decimal point is allowed). Such that data items are often used as subscripts.The PICTURE of a COMP item should not contain any character other than 9, S. COMPUTATIONAL-1 (COMP-1) Usage If the usage of a numeric data item is specified as COMP-1, it will be represented in one word in the floating –point form. The number is actually represented in Hexa decimal (base 16). Such representation is suitable for arithmetic operations. The PICTURE clause cannot be specified for COMP-1 items. COMPUTATIONAL-2(COMP-2)Usage This usage is same as COMP-1, except that the data is represented internally in two words. The advantages is that this increases the precision of the data which means that more significant digits can be available for the item. The PICTURE clause cannot be specified for COMP-2 items.
  35. 35. 35 COMPUTATIONAL-3(COMP-3)Usage In this form of internal representation the numeric data is the decimal form, but one digit takes half-a-byte. The sign is stored separately as the right most half –a-byte regardless of whether S is specified in the PICTURE or not. The hexa decimal number C or F denotes a positive sign and the Hexa –decimal number D denotes a negative sign. Inorder that data fields can start and end on byte boundaries, numbers with an even number of digits are stored with an extra half-byte of zeroes on the left hand side. PICTURE S9(5)V9(3) USAGE IS COMP-3 Will require 5 bytes to be stored internally. Only the characters 9,S, V and P can be used in the PICTURE of a COMP-3 item.
  36. 36. 36 Value Clause • Value Clause defines the initial value of a data item • Must not be used for items declared in FILE SECTION. • Can also specify FIGURATIVE CONSTANTS. • If defined at the group level can be used for array declaration also EXAMPLES. 01 NUM-1 PIC 9(3) VALUE 245. 01 E-CODE PIC X(6) VALUE “E10K3”. At group level contents 01 GROUP-ITEM VALUE IS ‘ER34155’ 05 E-ITEM-1 PIC X(2). ‘ER’ 05 E-ITEM-2 PIC XXX ‘341’ 05 E-ITEM-3 PIC X(3) ‘55’ • Group item is considered as alphanumeric. Notes: Assigning values to identifiers is called initialization. If variables are not initialized, then they may contain any value, which was stored at the time of last execution of program. It is advised to always initialize working-storage variables.
  37. 37. 37 REDEFINES Clause Two or more data items can share the same working storage area by REDEFINING a storage area. Level number data name-1 REDEFINES data-name-2 • Level numbers of data-name-1 and data-name-2 must be identical • The redefines clause must immediately follow data-name-I • must not be used for level number 66 or 88 items. • Data-name-1 should not contain VALUE clause • Multiple redefinition is allowed Notes: • Two or more storage areas defined in the data sometimes may not be used simultaneously, in such cases, only one storage area can serve the purpose of two or more areas if the area is defined. • The REDEFINES clause used allows the said area to be referred to by more than one data name with different sizes and pictures.
  38. 38. 38 ILLUSTRATES REDEFINES CLAUSE DATA DIVISION. WORKING-STORAGE SECTION. 01 X1 02 Y PIC 99. 02 Y1 REDEFINES Y PIC XX. 01 X3 02 Z PIC X VALUE “M”. 02 ZZ PIC X (25) VALUE ALL “*”. 02 ZZZ PIC X (45) VALUE ALL “- “. 01 X4 REDEFINES X3. 02 FILL1 PIC X. 02 FILL2 PIC X (70). 01 X5 REDEFINES X4. 02 BUFFER PIC X (71). PROCEDURE DIVISION PARA 1. MOVE 20 TO Y. DISPLAY X1. MOVE “A1” TO Y1. DISPLAY X1 DISPLAY X3. DISPLAY X4. DISPLAY X5. STOP RUN.
  39. 39. 39 Duplicate Data Names Are allowed, provided they belong to a group item 01 Pay-Rec. 02 Id-numbers PIC 9(5). 02 Name PIC X (25). 02 Dept PIC X (20). 01 Print-Rec. 02 Filler PIC X (5). 02 Id-numbers PIC X (5) 02 Filler PIC X (5). 02 Name PIC X (25). 02 Dept PIC X (920). MOVE Id-Numbers (OF | IN) Pay-Rec TO Id-Numbers (OF | IN)Print-Rec. * OF and IN are called Qualifiers. To move the data stored in the four fields of Pay-Rec. the four MOVE statements serve the purpose. Using the MOVE CORRESPONDING statement the same can be accomplished.
  40. 40. 40 RENAMES Clause Syntax: 66 data-name-1 RENAMES data-name-2 THRU data-name-3 E.g. : 01 PAY – REC. 02 FIXED-PAY. 05 BASIC PIC 9(6) V99. 05 DA PIC 9(6) V99. 02 ADDITIONAL-PAY. 05 HRD PIC 9(4) V99. 05 INCENT PIC 9(3) V99. 02 DEDUCTIONS. 05 PF PIC 9(3) V99. 05 IT PIC 9(4) V99. 05 OTHER PIC 9(3) V99. 66 PAY-OTHER-THAN-BASIC RENAMES DA THRU INCENT. 66 IT-AND-PF-DEDUCTIONS RENAMES PF THRU IT.
  41. 41. 41 ILLUSTRATES RENAMES CLAUSE DATE DIVISION. WORKING-STORAGE SECTION. 01 PAY 02 FIXED-PAY 10 E-BASIC PIC 9(6). 99 10 E-DA PIC 9(6). 99. 05 ADDL-PAY. 10 HRA PIC 9(4). 99. 10 INCENTIVE PIC 9(3). 99. 05 DEDUCTIONS. 10 E-PF PIC 9(3). 99. 10 E-IT PIC 9(4). 99. 10 OTHERS PIC 9(3). 99. 66 PAY-LESS-BASIC RENAMES E-DA THRU INCENTIVE. 66 IT-AND-PF RENAMES E-PF THRU E-IT.
  42. 42. 42 PROCEDURE DIVISION. MAIN-PARA MOVE-123456.78 TO E-BASIC. MOVE 234567.89 TO E-DA. MOVE 1234.56 TO HRA. MOVE 123.45 TO INCENTIVE. MOVE 123.45 TO E-PF. MOVE 1234.56 TO E-IT. MOVE 123.45 TO OTHERS. DISPLAY PAY. DISPLAY FIXED-PAY. DISPLAY ADDL-PAY. DISPLAY DEDUCTIONS. DISPLAY PAY-LESS-BASIC. DISPLAY IT-AND-PF. STOP RUN.
  43. 43. 43 Figurative Constants •Constants frequently used by most programs Figurative Constants Meaning HIGH-VALUE(S) Represents the highest and lowest LOW-VALUES (S) value in the collating sequence. ZERO, ZEROS, ZEROES One or more Zeroes SPACE (S) One or more blanks Example 01 ID-1 PIC X(3) VALUE SPACES. •Collating sequence is the order in which the characters are compared by the system. Notes: Figurative constants are reserved words that name and refer to specific constant values.
  44. 44. 44 Edited Fields • Move 345.46 to a field of picture 9(3)v99 & display or print You may see different number in result • Characters must be edited before report is taken to suppress leading zeros, to include currency signs or to include date separators. Editing Codes Effect Z Leading Zeros if any will be suppressed * Leading Zeros are replaced by asterisks(*) $ Currency sign appears in the left most of the field. - Appears at left or right of the field as specified in the picture clause if value is negative + Appears if value is positive, else minus sign appears • Editing Codes are specified in the picture clause for variables intended for report purpose. These variables cannot be used for arithmetic calculations.
  45. 45. 45 More Editing Characters EDIT CODES CR or DB . , B 0 -(hyphen) / (slash) BLANK WHEN ZERO MEANING To be specified in the right most position of the pic clause. Appears only if the value is negative ,if value is positive it replaced by two characters. Stands for decimal point. Cannot be specified with V clause Inserted in the position where specified Blank is appeared Zero is appeared. To be specified left most position of pic clause. Used as date separators. Appears where specified. Sets all null values to blanks
  46. 46. 46 EXAMPLES DATA PIC CLAUSE UNEDITED PIC CLAUSE EDITED EDITED VALUE 02346 9(5) ZZ999 2346 0005 9(4) ZZ99 05 03.42 99V99 Z999 003 0.007 9V999 ZV999 007 05634 9(5) **999 *5634 00143 9(5) $9(5) $00143 453 9(3) $**999 $**453 -0453 s9(4) -ZZ9(2) - b453 -0453 s9(4) 9999- 0453- 453 9(3) 999- 453 -453 s9(3) 999+ 453- 70.46 99V99 99.99- 70.46 156758 9(6) 99/99/99 15/67/58 00 99V9 99.9 Blank when zero 0.00 8654 9(4) 99b9b9 86b5b4 24 99 9900 2400
  47. 47. 47 Notes: The above table shows contents of unedited fields in the first column. Contents of edited fields after moving the data-1 shown in last column. Edited fields (Fields with editing codes) cannot take part in arithmetic computations. Moving of numeric edited fields to unedited fields is illegal.
  48. 48. 48 UNIT 3 PROCEDURE DIVISION
  49. 49. 49 PROCEDURE DIVISION PROCEDURE DIVISION[USING <DATA-ITEM1>, <DATA-ITEM2>. MAIN-PARA. DISPLAY ‘ENTER VALUE OF A:’. ACCEPT A. DISPLAY ‘ENTER VALUE OF B:’. ACCEPT A. MOVE A TO B. ADD A TO B. DISPLAY ‘A VALUE :’ A. DISPLAY ‘B VALUE :’ B. --------------------------------- -------------------------------- STOP RUN.
  50. 50. 50 Notes : Procedure Division can consists of Sections (Optional) Paragraphs(Optional) Statements. While coding, we must follow the following Hierarchy: SECTION------- PARAGRAPHS ------ STATEMENTS Or PARAGRAPH------- STATEMENTS Or STATEMENTS
  51. 51. 51 COBOL VERBS All instructions are coded in Procedure division. BASIC COBOL VERBS • MOVE • ACCEPT • DISPLAY • PERFORM • GOTO • STOP RUN • CALL • COPY • SORT • MERGE • FILE OPERATIONS • CHARACTER HANDLING • TABLE HANDLING • CONDITIONS • ARITHMETIC VERBS
  52. 52. 52 Notes: Arithmetic Verbs : ADD, SUBTRACT, MULTIPLY, DIVIDE, COMPUTE Conditions : IF….ELSE, EVALUATE File handling : READ, WRITE, REWRITE, DELETE Character handling : INSPECT, STRING, UNSTRING Table handling : SET, SEARCH
  53. 53. 53 Paragraphs Paragraphs are building blocks of the PROCEDURE DIVISION PROCEDURE DIVISION. MAIN-PARA. STATEMENT1. STATEMENT2. --------------------- --------------------- ---------------------- PARA-100. ----------------------- -------------------------
  54. 54. 54 Notes: A paragraph-name must begin in Area A and must be followed by a separator period. A paragraph-name need not be unique because it can qualified by a SECTION name. Paragraph-names need NOT contain any alphabetic character (i.e. can be all numeric). A paragraph ends at: • The next paragraph-name or section header • The end of the PROCEDURE DIVISION • The Scope terminator END-PARAGRAPH
  55. 55. 55 Terminator statements • EXIT PROGRAM. The EXIT PROGRAM statement specifies the end of a called program and returns control to the calling program • STOP RUN. The STOP RUN statements halts the execution of the object program, and returns control to the system • GOBACK. The GOBACK statement functions like the EXIT PROGRAM statement When it is coded as part of a called program and like the STOP RUN when coded in a main program Notes: If these statements are not the last statements in a sequence, statements following them will not be executed.
  56. 56. 56 Scope Terminators Explicit scope terminators mark the end of certain PROCEDURE DIVISION statements. Explicit scope terminators are COBOL Reserved Words. END-ADD END-SEARCH END-CALL END-MULTIPLY END-START END-COMPUTE END-PERFORM END-STRING END-DELETE END-READ END-DIVIDE END-UNSTRING END-EVALUATE END-REWRITE END-WRITE END-IF An explicit Scope Terminator is paired with the unpaired occurrence of the verb. An implicit Scope Terminator is a separator period.
  57. 57. 57 Notes: Example: PERFORM PARA-1 UNTIL A > 10 STATEMENT1 STATEMENT2 ------------------- ------------------- -------------------- END-PERFORM. Period(.) should not encounter in between PERFORM and END-PERFORM. Since it indicates end of the PERFORM statement, then compiler error will raise.
  58. 58. 58 Display verb The function of the DISPLAY statement is to display low-volume results on the operator’s console or some other hardware device. Syntax : >>____DISPLAY_____ __identifier-1___ __ | _____________________________________________> | _ literal-1______| e.g: PROCEDURE DIVISION. DISP-PARA. DISPLAY SRCH-ARG ‘NOT IN TABLE.’. ---------------------------------- ------------------------------- DISPLAY ‘HELLO HOW ARE YOU’.
  59. 59. 59 Notes: The DISPLAY statement transfers the contents of each operand to the output device. The contents are displayed on the output device in the order, left to right, in which the operands are listed. WITH NO ADVANCING When specified, the positioning of the output device will not be changed in any way following the display of the last operand.
  60. 60. 60 ACCEPT Verb Format 1 transfers data from an input/output device into identifier-1. When the FROM phrase is omitted, the system input device is assumed. Format 1 is useful for exceptional situations in a program when operator intervention (to supply a given message, code, or exception indicator) is required. Format 1 : >>__ACCEPT______identifier-1___ __________________________________________>< | _ FROM__ _mnemonic-name-1___ _| | _ environment-name _ | 77 SEARCH-VALUE PIC X(10). …. ACCEPT SEARCH-VALUE FROM SYSIN.
  61. 61. 61 Notes: The ACCEPT statement transfers data into the specified identifier. There is no editing or error checking of the incoming data. If the source of the ACCEPT statement is a file and identifier-1 is filled without using the full record delimited by the record terminator, the remainder of the input record is used in the next ACCEPT statement for the file. The record delimiter characters are removed from the input data before the input records are moved into the ACCEPT receiving area. If the source of the ACCEPT statement is a terminal, the data entered at the terminal, followed by the enter key, is treated as the input data. If the input data is shorter than identifier-1, the area is padded with spaces.
  62. 62. 62 MOVE Verb MOVE verb is used to copy the contents of an identifier into another identifier. MOVE <identifier-1> Or TO <identifier-2>[<identifier-3>,……….]. <literal-1> E.g.: MOVE A TO B,C,D MOVE dataname-1 to dataname-2 MOVE 345 to num-1 MOVE ‘345’ TO K MOVE ‘XYZ’ TO data-name-1 If the length of the receiving field is less than the length of sending field then truncation occurs.
  63. 63. 63 Notes: The MOVE statement transfers data from one area of storage to one or more other areas. An index data item cannot be specified in a MOVE statement. If the sending field(identifier-1) is reference-modified, subscripted, or is an alphanumeric or alphabetic function-identifier, the reference-modifier, subscript, or function is evaluated only once, immediately before data is moved to the first of the receiving operands.
  64. 64. 64 Elementary & Group Moves The receiving or sending field of a MOVE statement can be either an elementary item or a group item.When both the fields are elementary items the data movement is known as an elementary move. When at least one of the fields is a group item, it is called group move. 01 MSG-FLD PIC X(10). 01 DATA-FLD PIC X(10). 01 OLD-ADDR. 05 NO PIC X(5). 05 NAME PIC X(15). ------------------------------- ------------------------------- 01 NEW-ADDR. 05 N-NO PIC X(5). 05 N-NAME PIC X(15). ------------------------------- ------------------------------- MOVE ‘OUT OF SEQUENCE’ TO MSG-FIELD MOVE SPACES TO OLD-ADDR, NEW-ADDR MOVE DATA-FLD TO MSG-FIELD. MOVE NEW-ADDR TO OLD-ADDR
  65. 65. 65 Notes: Elementary move - Both sending and receiving data items are elementary items - Data conversion may take place, as well as editing or de-editing - On alphabetic moves, all necessary space-fill or truncation will occur Group Move - Both sending and receiving data items are group items - No data conversion takes place
  66. 66. 66 CORRESPONDING Phrase 01 STRUCT-1. 03 FIELD-A PIC 9(9) VALUE 123456789. 03 FIELD-B PIC X(5) VALUE “abcde”. 03 FIELD-C PIC 9(4)V99 VALUE 1234.56. 03 FIELD-D PIC 9(4)V99 VALUE 123456789. 01 STRUCT-2. 10 FIELD-C PIC Z(4).99. 10 FILLER PIC XXX. 10 FIELD-B PIC X(5). 10 FILLER PIC XXX. 10 FIELD-A PIC Z(9) 10 FILLER PIC XXX. MOVE CORRESPONDING STRUCT-1 TO STRUCT-2 Statement moves 3 fields but gives warning. Given the data definitions in the visual, the MOVE CORRESPONDING statements in the visual move three fields ( FIELD-S, FIELS-B and FIELD-C) but gives a warning message similar to the one below
  67. 67. 67 ILLUSTRATES MOVE CORRESPONDING DATA DIVISION WORKING – STORAGE SECTION. 01 DATA-1 05 E-ID PIC 9(5) VALUE 2345. 05 E-NAME PIC X (25) VALUE ALL “N”. 05 E-DEPT PIC X (20) VALUE ALL “D” 05 E-BASIC PIC 9(4) V99 VALUE 1234.67. 01 DATA-2. 05 FILLER PIC X(5) 05 E-ID PIC 9(5) 05 FILLER PIC X(5) 05 E-NAME PIC X (25). 05 FILLER PIC X(5). 05 E-DEPT PIC X(20) 05 FILLER PIC X(5) 05 E-BASIC PIC 9(4). 99
  68. 68. 68 PROCEDURE DIVISION. PARA 1. MOVE E-ID OF DATA-1 TO E-ID OF DATA-2 MOVE E-NAME OF DATA-1 TO E-NAME OF DATA-2. MOVE E-DEPT OF DATA-1 TO E-BASIC OF DATA-2. DISPLAY DATA-1 DISPLAY DATA-2 MOVE SPACES TO DATA-2. MOVE CORRESPONDING DATA-1 TO DATA-2. DISPLAY DATA-1 DISPLAY DATA-2. STOP RUN.
  69. 69. 69 Reference Modification • Reference Modification defines a data item by specifying its leftmost character and optionally, a length MOVE data-name1(begin : [length]) TO data-name2 • If ‘Length’ is omitted, the data item continues to rightmost character of data-name1 (the colon is required). • The data name must have usage DISPLAY. It may be qualified or subscripted. When qualified or subscripted, the reference modification is specified last.
  70. 70. 70 WORKING-STORAGE SECTION. 01 CAT-TYPE PIC X(15) VALUE 'CALICO'. 01 DOG-TYPE PIC X(15) VALUE 'SCHNAUZER'. 01 CAT-ABBREV PIC X(5). 01 DOG-END PIC X(10). PROCEDURE DIVISION. *Reference Modification Example Number 1: (From position 1:For 5 positions.) MOVE CAT-TYPE(1:5) TO CAT-ABBREV. *This will move "CALIC" to CAT-ABBREV. (The letters from position 1 of CAT-TYPE for 5 positions.) DISPLAY CAT-ABBREV.
  71. 71. 71 *Reference Modification Example Number 2: (From position 2:For 4 Bytes.) MOVE CAT-TYPE(2:4) TO CAT-ABBREV. *This will move "ALIC" to CAT-ABBREV2. (The letters from position 2 of CAT-TYPE for 4 positions.) DISPLAY CAT-ABBREV. *Reference Modification Example Number 3: (From position number 5 to the end of the field.) MOVE DOG-TYPE(5:) TO DOG-END. *This will move "AUZER" to DOG-END. (The letters from position 5 of DOG-TYPE to the end of DOG-TYPE.) DISPLAY DOG-END.
  72. 72. 72 ADD Verb All identifiers (or literals) preceding the word TO are added together, and then this sum is added to, and replaces, each identifier-2. The action is repeated in order left-to- right for each identifier-2. Identifiers must be elementary numeric items. Format 1 : >>___ADD_______ identifier-1_ _|__ To _____identifier-2__ _ ______ _______|____> |_literal-1___| |_ROUNDED _| >___ _______________________________________ ___________________________> |_ ____ __SIZE ERROR imperative-statement-1______| >___ ________________________________________ ___________________________> |_ NOT___ ______ ___SIZE ERROR__imperative –statement_2_| >___ _______ ___________________________________________________________> |_ END-ADD_|
  73. 73. 73 In Format 1, all identifiers or literals preceding the key word TO are added together, and this sum is stored in a temporary data item. This| temporary data item is then added to each successive occurrence of identifier-2, in the left-to-right order in which identifier-2 is specified. Identifier must name an elementary numeric item. Literal must be a numeric. The ADD statement sums two or more numeric operands and stores the result. Example : ADD A TO B. ADD 112 TO B. ADD A TO B ON SIZE ERROR GO TO ERR-PARA.
  74. 74. 74 ADD Verb(Continue……) • The operands preceding the GIVING are added together and the sum replaces the value of each identifier-3. • Identifiers must be elementary numeric items, except when following GIVING then they may also be numeric –edited. Format 2 : >>___ADD_______ identifier-1_ _|__ _ _ __ _ identifier2____________________> |_literal-1___| |_TO_| |_literal-2______| >___ GIVING ___________identifier-3__ ______________ _| ________________ > |_ ROUNDED__| >___ _____________________________________________________ __________ > |_ _________ ___SIZE ERROR__imperative –statement_1_| >___ ____________________________ _________________________________ > |_ NOT___ ______ _SIZE ERROR__imperative –statement_2_| |_ ON_| >___ _______ _______________________________________________________ > |_ END-ADD_|
  75. 75. 75 In Format 2, the values of the operands preceding the word GIVING are added together, and the sum is stored as the new value of each data item referenced by identifier-3. Identifier must name an elementary numeric item, except when following the word GIVING. Each identifier following the word GIVING must name an elementary numeric or numeric-edited item Literal must be a numeric. Example : ADD A TO B GIVING C
  76. 76. 76 ADD CORRESPONDING Statement •Elementary data items within identifer-1 are added to, and stored in the corresponding elementary data items with identifer-2.. ADD CORRESPONDING identifiers must be group items Format : >>___ADD_______ CORRESPONDING_ ___identifier-1___ TO___ identifier-2____________> |_CORR___________| >___ ______________ __ ______________________________________ ________________ > |_ ROUNDED__| | _ ___ __SIZE ERROR____ imperative-statement-1_| |_ ON_ | >___ _____________________________________________ ___________________________ > |_NOT___ ______ __SIZE ERROR__imperative –statement_1_| |_ON___| >___ _____________________________________________ ___________________________ > |_ NOT___ ______ _SIZE ERROR__imperative –statement_2_| |_ ON_| >___ _______ __________________________________________________________________ > |_ END-ADD_|
  77. 77. 77 ON SIZE ERROR Phrase • If the value of an arithmetic evaluation exceeds the largest value that can be contained in a result, then a size error condition exists. • The SIZE ERROR condition applies to final results, not intermediate calculations • If ON SIZE ERROR phrase is not specified, then truncation of the results will occur. • If ON SIZE ERROR phrase is specified, the imperative statement (in ON SIZE ERROR) is taken, following which control is transferred to the end of the arithmetic statement. • For ADD CORRESPONDING or SUBTRACT CORRESPONDING, the ON SIZE ERROR imperative is not taken until all individual additions or subtractions have been completed.
  78. 78. 78 A size error condition can occur in three different ways . When the absolute value of the result of an arithmetic evaluation, after decimal point alignment, exceeds the largest value that can be contained in the result field . When division by zero occurs . In an exponential expression, as indicated in the following table The size error condition applies only to final results, not to any intermediate results Size error Action taken when a size error clause is present Action taken when a size error clause is not present Zero raised to zero power The size error imperative is executed The value returned is 1, and message is issued Zero raised to a negative power The size error imperative is executed Program is terminated abnormally A negative number raised to a fractional power The size error imperative is executed The absolute value of the base is used, and a message is issued.
  79. 79. 79 NUMERIC Data Types of numeric items are:  Binary  Packed decimal. (internal decimal)  Floating point representation.  The PICTURE character-string can contain only the symbols 9, P, S, and V  The number of digit positions must range from 1 through 18, inclusive  If unsigned, the contents of the item in standard data format must contain a combination of the Arabic numerals 0-9. If signed, it may also contain a +, -, or other representation of the operation sign Notes: A VALUE clause can specify a figurative constant ZERO
  80. 80. 80 SUBTRACT Verb Format 1 : >>___SUBTRACT_______ identifier-1_ _|__ FROM____________________________> |_literal-1___| > ______identifier-2__ ___ _|________________________________________________> | _ ROUNDED ____| >___ ________________________________________ ___________________________> |_ ____ __SIZE ERROR imperative-statement-1______| |_ON _| >___ ________________________________________ ___________________________> |_ NOT___ ______ ___SIZE ERROR__imperative –statement_2_| >___ _______ _________________________________________________> |_ END-SUBTRACT_| All identifiers or literals preceding the key word FROM are added together and this sum is subtracted from and stored immediately in identifier-2. This process is repeated for each successive occurrence of identifier-2, in the left-to-right order in which identifier-2 is specified.
  81. 81. 81 SUBTRACT Verb(Continue………….) Format 2 : >>___SUBTRACT_______ identifier-1_ _|__ FROM ___ _ identifier-2__ _______________> |_literal-1___| |_literal-2______| >___ GIVING ___________identifier-3__ ______________ _| _________________________ > |_ ROUNDED__| >___ ____________________________________________ ____________________________ > |_ _______ ___SIZE ERROR__imperative –statement_1_| |_ ON _| >___ ____________________________________________ ____________________________ > |_ NOT___ ______ _SIZE ERROR__imperative –statement_2_| |_ ON_| >___ _______ __________________________________________________________________ > |_ END-SUBTRACT_|
  82. 82. 82 All identifier or literals preceding the key word FROM are added together and this sum is subtracted from identifier-2 or literals-2. The result of the subtraction is stored as the new value of each data item referenced by identifier-3. Notes: Example: 1. SUBTRACT A FROM B. The value of A subtttracted from the value of B and then the resultant value will be stored in B. 2. SUBTRACT 9 FROM C. 3. SUBTRACT C FROM 9. Is not valid because 9 is a Literal.
  83. 83. 83 SUBTRACT CORRESPONDING Statement Format : >>___SUBTRACT____ CORRESPONDING_ ___identifier-1__ FROM_________________> |_CORR__________| >___ identfier-2____ __ ___________ _________________________________________ > |_ ROUNDED__| >___ _________________________________________ ____________________________ > |____ ______ __SIZE ERROR__imperative –statement_1_| |_ON___| >___ ________________________________________ ____________________________ > |_ NOT___ ______ _SIZE ERROR__imperative –statement_2_| |_ ON__| >___ _______ ______________________________________________________________ > |_ END-SUBTRACT_| Elementary data items within identifier-1 are subtracted from, and the results are stored in, the corresponding elementary data items within identifier-2.
  84. 84. 84 MULTIPLY Verb Format 1 : >>___MULTIPLY_______ identifier-1___ ___BY____identifier-2___ ______________| __________> |_ literal-1________| >___ _______________________________________________________________________________ > |____ ______ __SIZE ERROR__imperative –statement_1_| |_ON___| >___ _________________________________________________ ____________________________ > |_ NOT___ ______ _SIZE ERROR__imperative –statement_2_| |_ ON__| >___ _______ ________________________________________________________________________ > |_ END-MULTIPLY_| In Format 1, the value of identifier-1 or literal-1 is multiplied by the value of identifier-2; the product is then placed in identifier-2. For each successive occurrence of identifier-2, the multiplication takes place in the left-to-right order in which identifier-2 is specified.
  85. 85. 85 MULTIPLY Verb(Continue…..) Format 2 : >>___MULTIPLY_______ identifier-1_ _|__ BY_______ _ identifier-2__ ______________> |_literal-1___| |_literal-2______| >___ GIVING ___________identifier-3__ ______________ _| _______________________ > |_ ROUNDED__| >___ _____________________________________________________ ________________ > |_ _______ ___SIZE ERROR__imperative –statement_1_| |_ ON _| >___ _____________________________________________________ ________________> |_ NOT___ ______ _SIZE ERROR__imperative –statement_2_| |_ ON_| >___ _______ ______________________________________________________________ > |_ END-MULTIPLY_| In Format 2, the value of identifier-1 or literal-1 is multiplied by the value of identifier-2 or literal-2.The product is then stored in the data item(s) referenced by identifier-3.
  86. 86. 86 DIVIDE Verb Format 1 : >>___DIVIDE_____ _____ identifier-1_ _|__ INTO__________identifier-2____ _____ __ |____> |_literal-1___| |_ROUNDED _| >___ ________________________________________________ ____________________________> |_ ____ __SIZE ERROR imperative-statement-1____________| |_ON _| >___ _________________________________________________ ____________________________> |_ NOT___ ______ ___SIZE ERROR__imperative –statement_2_| |_ON __| >___ _______ ______________________________________________________________________> |_ END-DIVIDE_| In Format 1, the value of identifier-1 or literal is divided into the value of identifier-2, and the quotient is then stored in identifier-2. For each successive occurrence of identifier-2, the division takes place in the left-to-right order in which identifier-2 is specified.
  87. 87. 87 DIVIDE Verb(Continue……) Format 2 : >>___DIVIDE_______ identifier-1_ _|__ INTO_______ _ identifier-2__ ___________________________> |_literal-1___| |_literal-2______| >___ GIVING ___________identifier-3__ ______________ _| ___________________________________ > |_ ROUNDED__| >___ _____________________________________________________ ____________________________ > |_ _______ ___SIZE ERROR__imperative –statement_1_| |_ ON _| >___ _____________________________________________________ ____________________________> |_ NOT___ ______ _SIZE ERROR__imperative –statement_2_| |_ ON_| >___ _______ _________________________________________________ > |_ END-DIVIDE_| In Format 2, the value of identifier-1 or literal-1 is divided into or by the value of identifier-2 or literal-2. The value of the result is stored in each data item referenced by identifier-3.
  88. 88. 88 COMPUTE Verb Format : >>___COMPUTE_______ identifier-1_ ____________ _|____ _ =______ __________________________> |_ ROUNDED _| |_ EQUAL_| >___ arithmetic –expression________________________________________________________________ > >___ _____________________________________________________ ____________________________ > |_ _______ ___SIZE ERROR__imperative –statement_1_| |_ ON _| >___ _____________________________________________________ ____________________________ > |_ NOT___ ______ _SIZE ERROR__imperative –statement_2_| |_ ON_| >___ _______ __________________________________________________ > |_ END-COMPUTE_| The arithmetic expression is calculated and replaces the value for each identifier-1 item. Valid operators allowed in the expression are: + addition - subtraction * multiplication / division ** exponentiation
  89. 89. 89 Notes: The COMPUTE statement assigns the value of an arithmetic expression to one or more data items. With the COMPUTE statement, arithmetic operations can be combined without the restrictions on receiving data items imposed by the rules for the ADD, SUBTRACT, MULTIPLY, and DIVIDE statements.
  90. 90. 90 Must name elementary numeric item(s) or elementary numeric-edited item(s). Can name an elementary floating-point data item. The word EQUAL can be used in place of =. An arithmetic expression ca consist of any of the following: 1. An identifier described as a numeric elementary item 2. A numeric literal 3. The figurative constant ZERO 4. Identifiers are literals, as defined in terms 1,2, and 3, separated by arithmetic operators 5. Two arithmetic expressions, as defined in items 1,2,3, and/or 4, separated by an arithmetic operator 6. An arithmetic expression, as defined in items 1,2,3,4 and/or 5, enclosed in parentheses. When the COMPUTE statement is executed, the value of the arithmetic expression is calculated, and this value is stored as the new value of each data item referenced by identifier-1.
  91. 91. 91 PERFORM Statement PERFORM Paragraph-name/Section-header Transfer the control to the specified paragraph or section and expects the control back after executing the paragraph. PERFORM Para-name-1 [ THROUGH (or) THRU Para-name-n] Notes: PERFORM types • PERFORM para-name • PERFORM para-name N TIMES • PERFORM para-name VARYING K FROM M BY N UNTIL CONDITION K>20 • PERFORM para-name VARYING K FROM M BY N UNTIL CONDITION K>20 AFTER VARYING….
  92. 92. 92 PERFORM THROUGH PROCEDURE DIVISION. 100-MAIN-PARA. PERFORM 200-PARA THRU 500-PARA. STOP RUN. 200-PARA. * Statements. 400-PARA. * Statements 500-PARA. * Statements 300-PARA. * Statement - Not executed All the paragraphs between 200-PARA and 500-PARA are executed.
  93. 93. 93 PERFORM…………N times PERFORM PARA-NAME-1[THROUGH (or) THRU PARA-NAME-N] N TIMES. EX: PERFORM PARA-1000 15 TIMES. PERFORM PARA-1000 THRU PARA-4000 15 TIMES. PARA-1000. ADD A TO B. ------------------------ ------------------------- PARA-2000. SUBTRACT A FROM B. ------------------------------- -------------------------------- PARA-4000. MULTIPLY A BY B. ----------------------------
  94. 94. 94 PERFORM…………VARYING PERFORM PARA-NAME-1 [THRU (or) THROUGH PARA-NAME-N] VARYING { identifier- 1 } {identifier-2 } {Index-name-1} FROM {index-name-2} { Literal-1 } BY {identifier-3 } UNTIL Condition {Literal-2 } EX: 1. PERFORM PARA-2000 THRU PARA-5000 VARYING A FROM M BY N UNTIL A > Y 2. PERFORM para-1 Varying K FROM 10 BY 5 UNTIL K>100 Notes: Example 2 says : Sets the value of K to 10 initially Execute para-1 Check the condition K>100 If condition is true, transfer the control to next line If condition is false, increment K by 5 Execute para-1 again Check the condition K > 100 Repeat steps from 2 through 7 until Condition K > 100 becomes true
  95. 95. 95 Flow Chart for PERFORM ….. VARYING Enter Set identifier –1 to initial value Conditi on Execute range Add increment to - identifier. Exit False
  96. 96. 96 PERFORM with the VARYING-AFTER Option PERFORM PARA-NAME-1 [THRU (or) THROUGH PARA-NAME-N] VARYING { identifier- 1 } {identifier-2 } {Index-name-1} FROM {index-name-2} { Literal-1 } BY {identifier-3 } UNTIL Condition-1 {Literal-2 } AFTER { identifier- 4 } {identifier-5 } {Index-name-3} FROM {index-name-4} { Literal-3 } BY {identifier-6 } UNTIL Condition-2 {Literal-4 } AFTER { identifier- 7 } {identifier-8 } {Index-name-5} FROM {index-name-6} { Literal-5 } BY {identifier-9 } UNTIL Condition-3 {Literal-6 } This form is used when a nested repetition of the range is required while varying more than one identifier.
  97. 97. 97 For example PERFORM RANGE-TO-BE-EXECUTED VARYING I FROM 1 BY 1 UNTIL I > 50 AFTER J FROM 1 BY 1 UNTIL J > 10. The range RANGE-TO-BE-EXECUTED will be performed 500 times,.
  98. 98. 98 In-Line PERFORM The in-line PERFORM will be coded using END-PERFORM. Named Paragraph PERFORM MOVEIT VARYING X FROM 1 BY 1 UNTIL X = 5. . . . MOVEIT. MOVE DATA-FLD (X) TO PRINT (X). In-line PERFORM PERFORM VARYING X FROM 1 BY 1 UNTIL X = 5. MOVE DATA-FLD (X) TO PRINT (X). END-PERFORM. Notes: An In-line PERFORM requires the END-PERFORM terminator. Conversely the END-PERFORM phrase must not be specified when the statement is “PERFORM procedure name…”.
  99. 99. 99 IN-LINE PERFORM Considerations • DO not use for procedures executed from several places/ • Use for procedures referenced only once. • Consider not using if readability is affected , such as multiple-page PERFORM, • No periods may appear within the in-line PERFORM. • Delimited by END-PERFORM. • END-PERFORM cannot be used at end of an out-of-line PERFORM. • The OPTIMIZE compile option may move the PERFORM in-line in the object code at the compile time.
  100. 100. 100 IF .. ELSE Statement The IF statement evaluates a condition and provides for alternative actions in the object program, depending on the evaluation. Format : >>_______IF_____Condition-1____ __________ _____ ___statement-1___|__ ________> |_THEN_____| |_NEXT SENTENCE _| >___ ______________ ____ ________________ ______________________________> | <____________ | | (1) | | _ ELSE__ ___statement-2_|_____ | |___END-IF________| Note : (1) END-IF can be specified with NEXT SENTENCE as an IBM extension.
  101. 101. 101 Notes: The IF statement evaluates a condition and provides for different sets of statements to execute, depending on the evaluation of the IF. Condition can be any simple or complex condition. Statement-1, statement-2 Can be any one of the following: • An imperative statement • An conditional statement • An imperative statement followed by a conditional statement NEXT SENTENCE If the NEXT SENTENCE phrase is specified, and then the END-IF phrase must not be specified. NEXT SENTENCE passes control to the statement after the closest following period. However, if the NEXT SENTENCE phrase is executed, control will not pass to the statement after the closest following period.
  102. 102. 102 Compound Conditionals • Conditional expressions can be “compound” using the AND and OR logical operators • Conditional conditions can also use parentheses to group conditions. IF ITEM-1 = DOMESTIC-ITEM-NO AND ITEM-2 = OVERSEAS-ITEM-NO OR ITEM-1 = OVERSEAS-ITEM-NO AND ITEM-2 = DOMESTIC-ITEM-NO SET MIXED-SHIPMENT-FLAG TO TRUE END-IF ……………. SEARCH TABLEPAIR VARYING NDX WHEN ITEM-1(NDX) = FROM-CITY AND ITEM-2(NDX) = TO-CITY MOVE ……… WHEN ITEM-2(NDX) = FROM-CITY AND ITEM-1(NDX) = TO-CITY MOVE …….. END-SEARCH
  103. 103. 103 Relational Expressions Relational tests (comparisons) can be express as: • IS LESS THAN IS < • IS NOT LESS THAN IS NOT < • GREATER THAN IS > • IS NOT GREATER THAN IS NOT > • IS EQUAL TO IS = • IS NOT EQUAL TO IS NOT = • IS GREATER THAN OR EQUAL TO IS >= • IS LESS THAN OR EQUAL TO IS <=
  104. 104. 104 CONTINUE & NEXT SENTENCE Statement Example 1 - NEXT SENTENCE IF A = B IF C = D NEXT SENTENCE ELSE MOVE MESSAGE-1 TO RPT-MESSAGE-1 END-IF ADD C TO TOTAL DISPLAY TOTAL IF E = F MOVE MESSAGE-4 TO RPT-MESSAGE-2 END-IF END-IF.
  105. 105. 105 Example 2 – CONTINUE IF A=B IF C=D CONTINUE ELSE MOVE MESSAGE-1 TO RPT-MESSAGE-1 END-IF ADD C TO TOTAL DISPLAY TOTAL IF E=F MOVE MESSAGE-4 TO RPT-MESSAGE-2 END-IF END-IF.
  106. 106. 106 EVALUATE Statement • EVALUATE is a great way to implement the “case” programming construct EVALUATE dataname WHEN value-1 ……. WHEN value-2 {THROUGH | THRU} value-3 …. WHEN NOT value-4 …… WHEN OTHER END-EVALUATE EVALUATE dataname WHEN ‘A’ Perform add-trans WHEN ‘D’ Perform delete-trans WHEN ‘U’ WHEN ‘W’ Perform update-trans WHEN OTHER Perform bad-trans END-EVALUATE • Basic EVALUATE Example: The scope of a WHEN clause is all statements UNTIL the next WHEN clause, the END-EVALUATE, or a period
  107. 107. 107 Notes: The EVALUATE statement provides a shorthand notation for a series of nested IF statements. It can evaluate multiple conditions. That is, the IF Statements can be made up of compound conditions. Examples: Working-Storage for all Examples: 01 PLANET. 05 PLANET-NUMBER PIC 9. 05 PLANET-NAME PIC X(7). Evaluate Example Number 1: (Evaluate a PIC 9 field) EVALUATE PLANET-NUMBER WHEN 1 MOVE "Mercury" TO PLANET-NAME WHEN 2 MOVE "Venus " TO PLANET-NAME WHEN 3 MOVE "Earth " TO PLANET-NAME WHEN 4 MOVE "Mars " TO PLANET-NAME WHEN 5 MOVE "Jupiter" TO PLANET-NAME WHEN 6 MOVE "Saturn " TO PLANET-NAME WHEN 7 MOVE "Uranus " TO PLANET-NAME WHEN 8 MOVE "Neptune" TO PLANET-NAME WHEN 9 MOVE "Pluto " TO PLANET-NAME WHEN OTHER MOVE " " TO PLANET-NAME END-EVALUATE.
  108. 108. 108 Evaluate Example Number 2: (Evaluate a PIC X field) EVALUATE PLANET-NAME WHEN "Mercury" MOVE 1 TO PLANET-NUMBER WHEN "Venus " MOVE 2 TO PLANET-NUMBER WHEN "Earth " MOVE 3 TO PLANET-NUMBER WHEN "Mars " MOVE 4 TO PLANET-NUMBER WHEN "Jupiter" MOVE 5 TO PLANET-NUMBER WHEN "Saturn " MOVE 6 TO PLANET-NUMBER WHEN "Uranus " MOVE 7 TO PLANET-NUMBER WHEN "Neptune" MOVE 8 TO PLANET-NUMBER WHEN "Pluto " MOVE 9 TO PLANET-NUMBER WHEN OTHER MOVE 0 TO PLANET-NUMBER END-EVALUATE. Evaluate Example Number 3: Let each of MONTH and NO-OF-Days be two-digited numeric integer fields. The values 1,2,3, etc. for MONTH denote respectively, January, February, March etc. depending on the value of MONTH , we wish to ove 30,31 or 28 to NO-OF-DAYS. For example , if the value of MONTH is 1, we shall move 31; if it is 2, we shall move 28 and so on. The EVALUATE statement for the purpose is as follows: EVALUATE TRUE WHEN MONTH = 4 OR 6 OR 9 OR 11 MOVE 30 TO NO-OF-DAYS WHEN MONTH = 2 MOVE 28 TO NO-OF- DAYS WHEN OTHER MOVE 31 TO NO-OF-DAYS END EVALUATE.
  109. 109. 109 Evaluate Example Number 4: Suppose MARKS contains the marks obtained by a student. GRADE is an one- character alphanumeric field. We wish to calculate GRADE according to the following rules MARKS GRADE 80 – 100 A 60 - 79 B 45 - 59 C 30 - 44 D 0 - 29 E The EVALUATE statement for the purpose is shown below. EVALUATE MARKS WHEN 80 THRU 100 MOVE “A” TO GRADE WHEN 60 THRU 79 MOVE “B” TO GRADE WHEN 45 THRU 59 MOVE “C” TO GRADE WHEN 30 THRU 44 MOVE “D” TO GRADE WHEN ZERO THRU 29 MOVE “E” TO GRADE WHEN OTHER MOVE “W” TO GRADE END-EVALUATE. The literal “W” is moved to GRADE in the case of wrong marks.
  110. 110. 110 ILLUSTRATES CONDITION NAMES DATA DIVISION. WORKING-STORAGE SECTION. 77 MARTIAL-STATUS PIC 9. 88 SINGLE VALUE 0. 88 MARRIED VALUE 1. 88 WIDOWED VALUE 2. 88 DIVORCED VALUE 3. 88 ONCE-MARRIED VALUES ARE 1, 2, 3. 88 VALID-STATUS VALUES ARE 0 THRU 3. 77 AMOUNT PIC 9 (4) VALUE 1000. PROCEDURE DIVISION. MAIN-PARA. DISPLAY “Martial Status:” DISPLAY “0- Single / 1- Married / 2- Widowed / 3- Divorced”. ACCEPT MARTIAL-STATUS. IF NOT VALI-STATUS DISPLAY “Error in Entry”. IF SINGLE SUBTRACT 100 TO AMOUNT. IF MARRIED ADD 100 TO AMOUNT. IF WIDOWED ADD 200 TO AMOUNT. IF DIVORCED SUBTRACT 200 FROM AMOUNT. IF ONCE-MARRIED ADD 250 TO AMOUNT DISPLAY AMOUNT. STOP RUN.
  111. 111. 111 INITIALIZE Statement The INITIALIZE statement sets selected categories of data fields to predetermined values. It is functionally equivalent to one or more MOVE statements. When the REPLACING phrase is not used: SPACE is the implied sending field for alphabetic alphanumeric, alphanumeric-edited, and DBCS items. ZERO is the implied sending field for numeric and numeric-edited items. >>___INITIALIZE____identifier- 1 ________________________________________> >___ ___________________________ _________________ _______>< | < ____________________________________________ __________________ |_REPLACING____ _ALPHABETIC_______ __ _______ __BY____ identifier-2 _ _ | _ | |_ALPHANUMER____| |_DATA_| |_LITERAL-1__| |_NUMERIC __________| |_ALPHANUMERIC-EDITED_| |_NUMERIC-EDITED__| |_ DBCS _____________| |_ EGCS _____________|
  112. 112. 112 Notes: The INITIALIZE statement sets selected categories of data fields to predetermined values. It is functionally equivalent to one or more MOVE statements. A subscripted item can be specified for identifier-1. A complete table can be initialized only by specifying identifier-1 as a group that contains the complete table. The data description entry for identifier-1 must not contain a RENAMES clause. An index data item cannot be an operand of INITIALIZE. Special registers can be specified for identifier-1 and identifier-2 only if they are valid receiving fields or sending fields, respectively, for the implied MOVE statement(s). When the REPLACING phrase is used: The category of identifier-2 or literal-1 must be compatible with the category indicated in the corresponding REPLACING phrase, according to the rules for the NUMERIC category. The same category cannot be repeated in a REPLACING phrase. The Key word following the word REPLACING corresponds to a category of data shown “Classes of Data” visual.
  113. 113. 113 SET TO TRUE Statement When this form of the SET statement is executed, the value associated with a condition-name is placed in its conditional variable according to the rules of the VALUE clause. >>__SET____condition-name-1_|_ TO TRUE_________________________>< condition-name-1: Must be associated with a conditional variable. If more than one literal is specified in the VALUE clause of condition-name-1, its associated conditional variable is set equal to the first literal. 01 CUST-TYPE PIC 99. 88 INACTIVE VALUE 9. 88 SPEC-ACCTS VALUE 20, 11, 40, 44. …… SET INACTIVE TO TRUE SET SPEC-ACCTS TO TRUE
  114. 114. 114 Class Condition · NUMERIC The item entirely contains characters 0 through 9 (with or without a sign determined by its PICTURE clause). It may be USAGE DISPLAY or PACKED DECIMAL. · ALPHABETIC The entire item contains only A through Z, a through z, or spaces · ALPHABETIC-UPPER The entire item contains only A through Z (exclusively upper-case) or spaces. · ALPHABETIC-LOWER The entire item contains only a through z (exclusively lower-case) or spaces. Notes: Ex: 1. IF A IS NUMERIC ---------------------- ----------------------- 2. IF C IS ALPHABETIC ----------------------- ------------------------ Where A and C are Data items.
  115. 115. 115 UNIT 4 FILE HANDLING IN COBOL
  116. 116. 116 FILES   A record is a group of logically or functionally related fields.   A File is a group of Records.   A group of records, which can be created, copied, modified, retrieved and deleted.   E.g.: Details of an employee -Name, Adds, Phone no., Dept no etc… Forms a record     Details of all employees -Group of such record forms a file.      Notes:
  117. 117. 117 Fixed vs Variables Length Records Fixed length records. • Corresponding fields of all the records have same length. Variable length records. • Field lengths may vary from record to record. Figure 4-2 Fixed vs. Variable Length Records Notes: The size of a record is the cumulative size of all the fields in it. If all the records of a file have the same structure then they are called Fixed length-records. For convenience,records of different lengths can be placed together in one file. Then they are known as variable-length-records.
  118. 118. 118 FILE-CONTROL Paragraph Format: SELECT [OPTIONAL] File-name-1 ASSIGN TO Assignment-name-1 [ RESERVE <INTEGER> AREA ] SEQUENTIAL [ ORGANIZATION IS INDEXED RELATIVE SEQUENTIAL [ACCESS MODE IS RANDOM DYNAMIC [FILE STATUS IS Data-name-1] Figure 4-3 FILE-CONTROL - SEQUENTIAL Notes: The FILE-CONTROL paragraph associates each file with an external data-set. FILE_CONTROL paragraph is in INPUT-OUTPUT Section of ENVIRONMENT Division.Not all options are available on all platforms.
  119. 119. 119 SELECT OPTIONAL may be specified only for files opened in the input, I-O, or extended mode. You must specify SELECT OPTIONAL for such input files that are not necessarily present each time the program is executed. The ‘file-name-1’ must be identified by an FD or SD entry in the DATA DIVISION. The ASSIGN clause associates the program’s name for a file with the external name for the actual data file. The RESERVE clause allows you to specify the number of input/output buffers to be allocated at run time for the file. The ORGANIZATION clause identifies the logical structure of the file.
  120. 120. 120 ORGANIZATION IS SEQUENTIAL The Records are stored in contiguous allocation. To access the record in Sequential mode only (I.e. to read the last record, it reads all the records until last record found.)Deletion of record is not possible.Updating is possible but record length should not changed. ORGANIZATION IS INDEXED Each record in the file has one or more embedded keys; each key is associated with an index. An index provides a logical path to the data records, according to the contents of the associated embedded record key data items. Indexed files must be direct-access storage files. Records can be fixed-length or variable-length. Each record in an indexed file must have an embedded prime key data item. When records are inserted, updated, or deleted, they are identified solely by the values of their prime keys. Thus, the value in each prime key data item must be unique and must not be changed when the record is updated.
  121. 121. 121 In addition, each record in an indexed file can contain one or more embedded alternated key data items. Each alternated key provides another means of identifying which record to retrieve. The RECORD KEY clause specifies the data item within the record that is the prime RECORD KEY for an indexed file. The values contained in the prime RECORD KEY data item must be unique among records in the file. The ALTERNATRE RECORD KEY clause specifies a data item within the record that provides an alternated path to the data in an indexed file. Used like the RECORD KEY but for an alternate index. ORGANIZATION IS RELATIVE The INPUT-OUTPUT FILE-CONTROL for Relative record files is very similar to that of indexed files except you use the RELATIVE KEY clause of the ACCESS MODE phrase and each record identified by the Relative Record Number instead of Recoed Key.
  122. 122. 122 ACCESS Mode Meaning Records of the file can be accessed sequentially, starting from first record till the required record is reached. Any record can be accessed directly without beginning from the first record. Records can be accessed both randomly and/or sequentially Modes SEQUENTIAL RANDOM DYNAMIC Notes: The record of a file stored on a magnetic tape can be accessed in sequential mode only. But the records of file stored on magnetic disk can be accessed in all the modes.
  123. 123. 123 FILE STATUS Clause A two-digit number indicates the status of the file. Value Status 00 Successful Completion 10 At end condition 30 Permanent error 34 Boundary violation Notes: Input-Output operations may not be successful thus resulting in termination of the program. The data-name specified in the file-status clause contains the status code and can be referred by the programmer. Depending on the code programmer can take specific actions by transferring the control to error-routine paragraphs. The data name should be declared in working-storage section with alphanumeric data type of two characters.
  124. 124. 124 I-O-CONTROL Paragraph • The Optional I-O-CONTROL paragraph of the Input-Output Section specifies when checkpoints are to be taken and the storage areas to be shared by different files. • Specifies information needed for efficient transmission of data between the external data set and the COBOL program. Notes: The I-O-CONTROL paragraph is optional. The key word I-O-CONTROL can appear only once, at the beginning of the paragraph. The word I-O- CONTROL must begin in Area A, and must be followed by a separator period. Each clause within the paragraph can be separated from the next by a separator comma or a separator semicolon. The order in which I-O-CONTROL paragraph clauses are written is not significant. The I-O- CONTROL paragraph ends with a separator method.
  125. 125. 125 FILE SECTION FILE SECTION. FD File-Name BLOCK CONTAINS m RECORDS RECORD CONTAINS n CHRACTERS LABEL RECORDS ARE STANDARD/ OMMITED 01 File-record-structure. Notes: Each file used in the program should have an FD entry (File Description) in FILE SECTION. • BLOCK CONTAINS clause specifies number of records in the block. • RECORD CONTAINS clause specifies total number of characters in each record. • LABEL RECORDS clause indicates • Disk files if STANDARD option is specified • Print files if OMITTED option is specified • Value clause specifies the name of the physical file and the path • 01 level entry should follow immediately after FD paragraph. Blocking Input-Output operations are slower compared to CPU processing speed. To reduce the CPU waiting time, block of records from the disk can be moved to the memory space called buffer thus reducing number of I-O operations. The Programmer can specify the number of records contained in a block. Suitable block size is to be selected by the programmer.
  126. 126. 126 File Operations Cobol Verbs WRITE REWRITE READ DELETE Meaning Writes the records into file. Required while creating a new file and while Adding new records to an existing file. Rewrites on one or more existing fields of a file. Required while updating a file. Reads the records of a file and make them available to program Deletes the record from a file. Notes: This foil lists the possible operations that can be performed over files. Before doing any operation, files should be opened and they must be closed before exiting the program “OPEN” and “CLOSE” verbs are provided by COBOL.
  127. 127. 127 OPEN MODES Mode INPUT OUTPUT I-O EXTEND Meaning Stands for input mode. Only reading of records possible. Stands for output mode. Only writing new records possible. Stands for Input ---Output mode. All operations possible Stands for extend mode. Only for appending the records in sequential mode. Notes: SYNTAX OPEN Mode File-name1, File-name2. CLOSE File-name1, File-name2 While opening the file the mode must be specified depending on the operation to perform. More than one file can be opened and closed. Further, files can be opened and closed more than once in a program.
  128. 128. 128 READ – Sequential Access • When the READ statement is executed the file must already be open in INPUT or I-O mode • The AT END clause must be before the NOT AT END Format 1: sequential retrieval >>____READ__file-name-1___ _________________ __ __________ ___________________> |_ NEXT __________| |_RECORD__| |_ (1)| |_ PREVIOUS______| >_____ _______________________ ______________________________________________> |____ INTO___identifier-1____| >_____ ___________________________________ __________________________________> |_ ____ __END_imperative –statement-1_| |_ AT _| >_____ ____________________________________________ ____ __________ _______>< |_ NOT___ ______ ___END_imperative-statement-2_| |_END-READ_| Notes: For sequential access, the READ statement makes the next logical record from a file available to the object program. For random access, the READ statement makes a specified record from a direct-access file available to the object program. When the READ statement is executed, the associated file must be open in INPUT or I-O mode. NEXT RECORD Reads the next record in the logical sequence of records. NEXT is optional when ACCESS MODE IS SEQUENTIAL; PREVIOUS RECORD Reads the previous record in the logical sequence of records.
  129. 129. 129 END OF FILE Processing • When the ‘AT END’ condition occurs during sequential processing, the READ statement execution is unsuccessful. The contents of the record area are ‘undefined’ • The following actions take place when ‘AT END’ occurs: - The status indicator is posted. - Control is transferred to the AT END phrase, if it is specified - If AT END is not specified, then USE AFTER STANDARD ERROR could be specified and that procedure is executed. Then control is returned to the statement following the READ.
  130. 130. 130 READ – Random Access Format 2 : Random Retrieval >>_____READ______file-name-1____ __________ ___ _______________ _____________> >____ _____________________________ ________________________________________> |_KEY_____ ___ __data-name-1__| |_TO_| >_____ _______________________________________________ ______________________> |_INVALID_____ ______ ____imperative-statement-3__| |_KEY __| >____ ___________________________________________ ___ ____________ _______>< |_NOT INVALID___ ___ __imperative-statement-4_| |_END-READ__| |_KEY_| - For VSAM INDEXED files, the KEY field contains a data value that will be matched against the key filed in the file records until the first record having an equal value is found. - For VSAM RELATIVE files, the KEY phrase must not be specified. Notes: Format 2 must be specified for indexed and relative files in random access mode, and also for files in the dynamic access mode when record retrieval is random. Execution of the READ statement depends on the file organization.
  131. 131. 131 Indexed Files Execution of a Format 2 READ statement causes the value of the key of reference to be compared with the value of the corresponding key data item in the file records, until the first record having an equal value is found. The file position indicator is positioned to this record, which is then made available. If no record can be so identified, an INVALID KEY condition exists, and READ statement execution is unsuccessful. If the KEY phrase is not specified, the prime RECORD KEY becomes the key of reference for this request. When dynamic access is specified, the prime RECORD KEY is also used as the key of reference for subsequent executions of sequential READ statements, until a different key of reference is established. Relative Files Execution of a Format 2 READ statement sets the file position indicator pointer to the record whose relative record number is contained in the RELATIVE KEY data item, and makes that record available. The KEY phrase must not be specified for relative files.
  132. 132. 132 READ – Dynamic Access • For dynamic access, either sequential or random access possible, depending upon the format of the Read statement • Dynamic access is allowed only for VSAM indexed or VSAM relative organizations. • Dynamic access is established by ACCESS IS DYNAMIC in FILE-CONTROL SELECT statement • The NEXT phrase must be specified for sequential access with dynamic mode. In order to READ NEXT, “position” must have been established in the file by a successful OPEN, START or READ statement
  133. 133. 133 START Statement Format : >>___START___file-name-1___________________________________________________________> >__ _____________________________________________________________________ ________> |_KEY___ ______ ____ __EQUAL___ ___ ________________ _data-name-1____| |__TO _| | |_ TO_| | |_ = ______________________________| |_LESS__ _______ ________________| | |_THAN_| | |_ < ______________________________| |_GREATER__ ____ _____________| | |_THAN_| | |_> _______________________________| |_NOT LESS___ _______ ___________| | |_THAN _| | |_NOT < ___________________________| |_NOT GREATER__ _______ ________| | |_THAN_| | |_NOT > ___________________________| |_LESS_ ____ _ OR EQUAL_ __ _____| | |THAN| |_TO_| | |_ < = _____________________________| |_GREATER__ ____ _OR EQUAL_ __ _| | |_THAN_| TO| |_>+_______________________________| >__ _______________________________________ _____________________________________> |_INVALID___ _____ _imperative-statement-1_| |_KEY_| >__ _______________________________________ ___________ ____________ _____________> |_NOT INVALID___ _____ imperative-statement-1_| |_END-START_| |_KEY_| Notes: The START statement provides a means of positioning within an indexed or relative file for subsequent sequential record retrieval.
  134. 134. 134 When the START statement is executed, the associated indexed or relative file must be open in either INPUT or I-O mode. file-name-1 Must name a file with sequential or dynamic access. File-name-1 must be defined in an FD entry in the Data Division, and must not name a sort file. END-START Phrase This explicit scope terminator delimits the scope of the START statement. END-START converts a conditional START statement to an imperative statement so that it can be nested in another conditional statement. END-START can also be used with an imperative START statement.
  135. 135. 135 WRITE Statement • The WRITE statement releases a logical record for an output or input/output file. • When the WRITE statement is executed: - The associated sequential file must be open in OUTPUT or EXTEND mode. - The associated indexed or relative file must be open in OUTPUT, I-O, or EXTEND mode. • Record-name must be defined in a Data Division FD entry. Record-name can be qualified. It must not be associated with a sort or merge file.
  136. 136. 136 WRITE……….FROM PROCEDURE DIVISION. WRITE File-rec FROM Identifier. • File-rec is record-name declared in FILE-SECTION. • Identifier is a working-storage section variable • The length of the identifier should be equal to the length of the record. Notes: To Create a file, program can accept the data from the terminal into file record and write it. If the data need to be processed, it can be accepted in a W-S identifier. After processing the data the above WRITE……..FROM statement can be issued. Each WRITE statement writes one record at a time.
  137. 137. 137 READ………….INTO PROCEDURE DIVISION. READ FILE-name (INTO W-S-Rec) | (AT END Statement) •File name is defined in SELECT clause. •W-S-Rec is working-Storage section identifier. •INTO clause moves the file record to W-S-rec. •AT END clause if used, indicates the next action after the last record is read. OPEN INPUT Mode Notes: READ statement on sequential files reads one record at a time and makes it available to program. Reading begins from first record and if the READ statement is put in a loop That is executing the statement repeatedly, then it is possible to read consecutive records. Loop can be terminated before AT END condition is reached if required so by the program. If the file is left open next time when the read statement executes, reading continuous from where it was stopped before the termination of loop.
  138. 138. 138 If the file is closed then it is to be opened again before reading it. REWRITE & DELETE REWRITE record-name (FROM identifier) Updates an existing record from W-S identifier. OPEN I-O File-name DELETE record-name ----------------- not allowed Deleting of a record in sequential files not allowed. Notes: It is often required to change the existing data and the process is called UPDATING. COBOL provides REWRITES verb to modify an existing record. For example, changing the address field of an employee requires reading of employee number. Every record to be updated needs to be read first. To search the record of an employee, whose employee number is known, the process is as follows • Store the employee number in a variable • Open the file • Read first record • Compare the variable with Emp-No field of the file • If it matches update his address by REWRITE • Else read next record his address by REWRITE
  139. 139. 139 • Repeat the process until the require record is read. Appending to sequential files Adding new records to the existing file. OPEN EXTEND Mode WRITE records. When new records to be added to file open the file in EXTEND mode EXTEND mode causes the pointer to move to the end of the file.
  140. 140. 140 CLOSE Statement Format : CLOSE File-name-1, [File-name-2 ………….] CLOSE Statement Releases the Resourcces which are assigned to that file. Cannot Close the file which is not opened. After performing the operations on the file (I,e no longer used in a program) needs to be closed but not necessary. If the FILE STATUS clause is specified in the FILE-CONTROL entry, the associated status key is updated when the CLOSE statement is executed. If the file is in an open status and the execution of a CLOSE statement is unsuccessful, the EXCEPTION/ERROR procedure (if specified) for this file is executed.
  141. 141. 141 Sequential Files ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL SELECT file-name ASSIGN TO DEVICE-NAME ORGANIZATION IS SEQUENTIAL. ACCESS MODE IS SEQUENTIAL. Area FILE STATUS IS data-name. B Notes: All the files used in the program should have an entry in FILE CONTROL paragraph. For each file used, there should be one SELECT………..ASSIGN clause. The file-name is select clause is user defined word and can be used throughout the program wherever required. ASSIGN clause specifies the device on which file stored.
  142. 142. 142 EXAMPLE: SEQUENTIAL FILE ID DIVISION. PROGRAM-ID. SEQ1. ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT INFILE ASSIGN TO DDNAME1 ORGANIZATION IS SEQUENTIAL. SELECT OUTFILE ASSIGN TO DDNAME2 ORGANIZATION IS SEQUENTIAL. DATA DIVISION. FILE SECTION. FD INFILE. 01 INREC. 02 ENO PIC X(5). 02 ENAME PIC X(10). 02 EADDRESS PIC X(15). 02 FILLER PIC X(50). FD OUTFILE. 01 OUTREC PIC X(80). WORKING-STORAGE SECTION. 01 EOF PIC X. PROCEDURE DIVISION. OPEN INPUT INFILE OUTPUT OUTFILE. READ INFILE INTO OUTREC AT END MOVE 'Y' TO EOF. PERFORM WRITE-PARA UNTIL EOF = 'Y'. CLOSE INFILE OUTFILE. STOP RUN. READ-PARA. WRITE OUTREC. READ INFILE INTO OUTREC AT END MOVE 'Y' TO EOF.
  143. 143. 143 Indexed Files Index component consists of a index structure with a record key values and addresses of corresponding records. RECORD KEY is one or more fields of the records. Suitable record key is to be chosen by the programmer depending on the functionality of the fields.  E.g : Employee-code,  Job-number. ALTERNATE RECORD KEY can also be chosen. E.g : Employee-name,  Job-name. Indexed files facilitate faster accessing of records compared to that of sequential files. Notes: When an indexed file is created • An index component is also created containing some index tables based on record keys. • A data component is created containing the actual records. Record keys identify every record in the file. The process of accessing a record involves searching for the record key with matching index value. Then locate the record from the corresponding address. This is done by the system itself.
  144. 144. 144 INVALID KEY (READ | WRITE | REWRITE | DELETE) File-name (INVALID KEY Statement) (AT END Statement). Records and indexes of an indexed file are stored in key sequence order to facilitate faster access. Invalid key clause checks whether any input-output operation is violating the Uniqueness of primary keys E.g. add a record with duplicate value. Sequence of the records. E.g.   add a record with key value out of range. Proper read E.g.  try to read a  non-exist record Reading of a record in indexed files required the key value to be provided by the program
  145. 145. 145 ACCESS MODE: SEQUENTIAL & RANDOM ACCESS MODE SEQUENTIAL • READ File-name NEXT RECORD to read sequentially. • DELETE statement should not contain invalid key • AT END clause is required. ACCESS MODE RANDOM • READ File-name INVALID KEY statement • AT END clause not required. Notes: When READ NEXT statement is to be executed each time the records are read consecutively. IF the access mode is RANDOM a record is read from corresponding key value.
  146. 146. 146 ACCESS MODE: DYNAMIC START file-name key (NOT | LESS THAN | GREATER THAN| LESS THAN ) identifier INVALID KEY statement READ file-name NEXT RECORD AT END statement. Notes: In a situation demanding the access of more than one consecutive records from the middle of the file then dynamic access is used. The “START” verb places the read pointer to the record whose key value is compared with an identifier. Record is accessed randomly. ‘READ…NEXT’ can be put into loop for sequential reading. For the Rewrite/ Delete operations the records must be read at first.
  147. 147. 147 IDENTIFICATION DIVISION. PROGRAM-ID. SEQFILE. ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT IND-FILE ASSIGN TO DD1 ORGANIZATION IS INDEXED ACCESS MODE IS RANDOM RECORD KEY IS NUM. SELECT OUT-FILE ASSIGN TO DD2 ORGANIZATION IS INDEXED ACCESS MODE IS DYNAMIC RECORD KEY IS NUM1. DATA DIVISION. FILE SECTION. FD IND-FILE. 01 IND-REC. 02 NUM PIC X(3). 02 NAME PIC X(15). 02 ADDR PIC X(10). 02 FILLER PIC X(52). FD OUT-FILE. 01 OUT-REC. 02 NUM1 PIC X(3). 02 NAME1 PIC X(15). 02 ADDR1 PIC X(10). 02 FILLER PIC X(52). WORKING-STORAGE SECTION. PROCEDURE DIVISION. MAIN-PARA. OPEN INPUT IND-FILE I-O OUT-FILE. MOVE '222' TO NUM. READ IND-FILE RECORD INTO OUT-REC KEY IS NUM INVALID KEY GO TO ERR-PARA. WRITE OUT-REC. PERFORM EXIT-PARA. ERR-PARA. DISPLAY 'KEY NOT FOUND'. PERFORM EXIT-PARA. EXIT-PARA. CLOSE IND-FILE OUT-FILE. STOP RUN. EXAMPLE: INDEXED FILE
  148. 148. 148 Relative Files FILE CONTROL SELECT file-name ASSIGN TO Disk ORGANIZATION IS RELATIVE RELATIVE KEY data-name-1 RRN indicates the offset of a record from the first record of the file. Notes: In relative file Relative Record Number identifies the records of the file. Select clause should specify “RELATIVE KEY”. Value of data-name-1 indicates RRN. Usage of READ/WRITE/ REWRITE/ DELETE statements, ACCESS modes, OPEN modes and START verb, are exactly similar to that for sequential files.
  149. 149. 149 OPERATI ONS I O I-O E I O I-O I O I-O READ X X X X X X WRITE X X X X REWRITE X X X START X X X X DELETE X X READ X X X X WRITE X X X X REWRITE X X START DELETE X X READ X X X X WRITE X X X X REWRITE X X START X X X X DELETE X X A C C E S S M O D E S E Q U E N TI A L R A N D O M D Y N A M IC Open modes File Organization Sequential Relative Indexed
  150. 150. 150 TABLE HANDLING Unit 5
  151. 151. 151 Introduction : Table Handling Consider a situation of accepting 100 numbers from the user , display all The numbers in sorted order. Types of tables • One dimensional table • Two dimensional table • Multidimensional table Table is a list of logically similar items. Notes: Obviously declaring 100 data items in W-S section and sorting them becomes practically impossible. Tables or Arrays provide the solution to handle situations discussed above. If volume of data to be processed is large and if they are not stored in files, then tables are used.
  152. 152. 152 OCCURS Clause Specifies number of occurrences or elements of the table. WORKING-STORAGE SECTION 01 Marks. 02 Mark – Table1 OCCURS 10 TIMES PIC 9(2). Valid 02 Mark – Table2 PIC 9(2) OCCURS 10 TIMES Valid 02 Mark – Table3 PIC 9(2) OCCURS 10TIMES VALUE 10 valid Notes: OCCURS clause causes setting up of area for holding the table elements. Following rules must be followed with the usage of ‘OCCURS’ clause. 1. The Integer must be positive. 2. Clause cannot be specified for an item whose level is 01, 66, 77, 88. 3. Value clause should not be specified with occurs clause. 4. OCCURS clause can be specified for file-section entries for both group items as well as elementary items.
  153. 153. 153 Subscript Indicates the position of an element in the table. PROCEDURE DIVISION Marks – Table (Subscript) Parentheses required Marks Table (I) Valid provided I declared in data division. Marks – Table (5) Valid. Marks – Table (12) Invalid. Notes: • Subscript can be a COBOL variable or a literal. Value of subscript must not exceed the range of no. of occurrences specified by ‘OCCURS’ clause. • If OCCURS clause is specified for a group items subscript should be specified for all elementary items of that group. • Subscript should be specified for only data items defined with OCCURS clause, whenever used in procedure division.
  154. 154. 154 INDEXING • An “index-name” is an identifier that becomes associated with a particular table. The value in an index is the displacement from the beginning of the table based upon the length of the table element. • An “index-name” may appear on an OCCURS clause, e.g. 01 TABLE-OF-MONTHS. 02 MONTHS OCCURS 12 TIMES. PIC X(10) INDEXED BY NDX. • The “index-name” is created by the compiler; it does not have to be defined elsewhere in the program. • The contents of an index may be changed by the SET TO statement • An index may not be used in a MOVE statement or an INITIALIZE statement.
  155. 155. 155 Notes: Indexing allows such operations as table searching and manipulating specific items. To use indexing you associate one or more index-names with an item whose data description entry contains an OCCURS clause. An index associated with an index-name acts as a subscript, and its value corresponds to an occurrence number for the item to which the index-name is associated. The INDEXED BY phrase, by which the index-name is identified and associated with its table, is an optional part of the OCCURS clause. There is no separate entry to describe the index associated with index-name. At run time, the contents of the index corresponds to an occurrence number for that specific dimension of the table with which the index is associated.
  156. 156. 156 One Dimensional Tables Specified by one subscript or index Example: 01 ABC. 02 XYZ PIC X(10) OCCURS 10 TIMES. XYZ(1) WHERE 1 Specifies the first element of XYZ.
  157. 157. 157 Two Dimensional Tables Specified by two subscripts or indexes. Student (3 5) =5th Subject of 3rd Student. Marks (3 5) =5th Marks of 3rd Student. If it requires storing the Marks of N subject for M students then we require two ‘OCCURS’ clauses. Notes: Two dimension tables are used most frequently in applications. Consider for examples, 10 Students of a class appeared for 8 subjects in their annual exams and you need to code a program to store and retrieve the data. Data includes names of all the students, marks and names of corresponding subjects. To store the marks of ‘n’ subjects of one student, one dimension table serves the purpose. If number of students is more than one than for each student there OCCURS ‘n’ subjects and marks. Next foil shows the W-S declarations for this example.
  158. 158. 158 Multidimensional Table Each OCCURS clause adds a dimension in nested occurs. Ex: 01 Multidimensional. 02 First-dim OCCURS 10 TIMES PIC X. 02 Second-dim OCCURS 5 TIMES. 05Second PIC A. 05Third-dim OCCURS 10 TIMES 10Third PIC 5. Notes: COBOL supports multidimensional tables up to 7 levels.
  159. 159. 159 Table-Sorting Use Sorting techniques to sort a table. e.g Bubble sort PERFORM VARYING I FROM 1 BY 1 UNTIL I = N PERFORM J FROM I BY 1 UNTIL J > N IF A[I] > A[J] MOVE A[I] TO TEMP MOVE A[J] TO A[I] MOVE TEMP TO A[J] END-IF END-PERFORM END-PERFORM. I and J are used as subscripts for comparing elements of the table. Notes: Sorting is the process of arranging the elements of table in order. Searching for a particular element of the sorted table, requires less time when compared to searching from an unsorted table. ‘SORT’ verb available in COBOL is limited to File sorting.
  160. 160. 160 SET Verb SET verb initializes and / or changes the value of index. E.g. : SET K To 1 K is initialized to 1 SET K UP BY 2 Value increment by step of 2. SET K DOWN BY 2 Decrements by step of 2 MOVE verb cannot be used for index. E.g. : SET data-name-1, data-name-2 TO K SET verb moves of value of K to data-name-1 and data-name-2. Notes: Even though indexes assume the displacement values for table elements internally, programmer sets the value of index by specifying the position of an element. This means an index indicates the position of an element in the table similar to subscript, but internally it is processed a different manner, but more efficient
  161. 161. 161 SEARCH Verb Searches for a particular value in the table, which has an index. SEARCH Table – name AT END statement WHEN condition statement Ex : SET K TO 1 SEARCH table-name AT END DISPLAY ‘not found’. WHEN field-1 = element (K) DISPLAY element (K). Notes: In the above example, field-1 contains the required value to be searched for in the table, More than one ‘condition’ can be checked, with more than one ‘WHEN’ clause. All valid arithmetic operators can be used. This form of search statement is called serial search.
  162. 162. 162 Binary Search Searches the table previously sorted, by splitting the table. Faster than serial search Only one ‘WHEN’ clause is allowed. SEARCH ALL Table-Name other clauses ………. remain same. WHEN…….… Notes: Before applying ‘SEARCH ALL’ clause the table must be sorted. SEARCH ALL causes the table to split into two halves. Then it determines which half of the table contains the required value by comparing it to the last element of the first half and first element of the second half. Again the selected half-table splits and continues and so on until the value is located.
  163. 163. 163 ILLUSTRATES ONE-DIMENSIONAL ARRAYS DATA DIVISION. WORKING STORAGE SECTION. 77 CT PIC 99 VALUE 0. 01 TAX-RATE. 05 RATE PIC 999 OCCURS 5 TIMES. * There should be a space before and after the braces. 01 MONTH-TABLE. 02 FILLER PIC X(9) VALUE “January”. 02 FILLER PIC X(9) VALUE “February”. 02 FILLER PIC X(9) VALUE “March:” 02 FILLER PIC X(9) VALUE “April”. 02 FILLER PIC X(9) VALUE “May”. 02 FILLER PIC X(9) VALUE “June”. 02 FILLER PIC X(9) VALUE “July”. 02 FILLER PIC X(9) VALUE “August”. 02 FILLER PIC X(9) VALUE “September”. 02 FILLER PIC X(9) VALUE “October”. 02 FILLER PIC X(9) VALUE “November”. 02 FILLER PIC X(9) VALUE “December”. 01 MONTH-NAME REDEFINES MONTH-TABLE. 02 MONTH PIC X(9) OCCURS 12 TIMES.
  164. 164. 164 PROCEDURE DIVISION. 100-MAIN-PARA. PERFORM 200-FILL-PARA VARYING CT FROM 1 BY 1. UNTIL CT>5. PERFORM 300-DISP-PARA VARYING CT FROM 1 BY 1. UNTIL CT>5. PERFORM 400-MNTH-PARA. STOP RUN. 200-FILL-PARA. COMPUTE RATE ( CT ) = CT*100. 300-DISP-PARA. DISPLAY RATE ( CT ). 400-MNTH-PARA. DISPLAY “Month as a number ?” ACCEPT CT. IF CT< 1 OR > 12 DISPLAY “Error in number” ELSE DISPLAY MONTH ( CT ).
  165. 165. 165 ILLUSTRATES SEARCH VERB DATA DIVISION. 01 MONTH-TABLE. 02 FILLER PIC X(9) VALUE “January”. 02 FILLER PIC X(9) VALUE “February”. 02 FILLER PIC X(9) VALUE “March:” 02 FILLER PIC X(9) VALUE “April”. 02 FILLER PIC X(9) VALUE “May”. 02 FILLER PIC X(9) VALUE “June”. 02 FILLER PIC X(9) VALUE “July”. 02 FILLER PIC X(9) VALUE “August”. 02 FILLER PIC X(9) VALUE “September”. 02 FILLER PIC X(9) VALUE “October”. 02 FILLER PIC X(9) VALUE “November”. 02 FILLER PIC X(9) VALUE “December”. 01 MONTH-NAME REDEFINES MONTH-TABLE. 02 MONTH OCCURS 12 TIMES INDEXED BY CT. 05 FIRST-THREE PIC X (3). 05 BALANCE-REST PIC X (6). 77 M-NAME PIC X (9) VALUE SPACES.
  166. 166. 166 PROCEDURE DIVISION. MAIN PARA. DISPLAY “Month’s Name please”. ACCEPT M-NAME. SET CT TO 1. SEARCH MONTH AT END DISPLAY “Not Found”. WHEN M-NAME = MONTH ( CT ). DISPLAY FIRST-THREE ( CT ). STOP RUN.
  167. 167. 167 ILLUSTRATE TWO-DIMENSIONAL ARRAYS DATA DIVISION WORKING-STORAGE SECTION. 01 WORK-AREA 05 MORE DATA PIC A VALUE “Y”. 88 NO-MORE-DATA VALUE “N”. 01 TEMPERATURE-ARRAY. 05 DAY-IN-THE-WEEK OCCURS 24 TIMES. 10 HOURS-IN-THE-DAY OCCURS 24 TIMES. 15 DEGREE-TEMP PIC S9(3). 77 DAY-OF-THE-WEEK PIC 9. 77 TIME-OF-THE-DAY PIC 99. 77 HOUR-COUNT PIC 99. 77 DAY-COUNT PIC 9. 77 TOT-TEMP PIC S999. 77 AVERAGE-TEMP PIC S999. PROCEDURE DIVISION. 100-MAIN-PARA. PERFORM 200-DATA-ACCP-RTN UNTIL NO-MORE-DATA. PERFORM 300-DATA-DISP-RTN. STOP RUN.

×