Top Banner
COBOL Programming Last Printed: 06/06/22 CONTENTS 1. What is a program?..............................................4 1.1. What is COBOL?...............................................4 1.2. Course Conventions...........................................6 1.3. Glossary.....................................................6 1.4. General rules for columns....................................6 2. Overview of a COBOL Program.....................................7 3. IDENTIFICATION DIVISION.........................................8 4. ENVIRONMENT DIVISION............................................9 5. DATA DIVISION..................................................10 5.1. Level Number................................................10 5.2. Name........................................................10 5.3. Picture.....................................................10 6. WORKING-STORAGE SECTION........................................11 6.1. Example.....................................................11 6.2. FILLER......................................................12 6.3. VALUE.......................................................12 6.4. Spacing.....................................................12 7. PROCEDURE DIVISION.............................................13 7.1. ACCEPT......................................................13 7.2. ACCEPT.... FROM.............................................14 7.3. DISPLAY.....................................................15 7.4. GOBACK......................................................15 8. FURTHER DATA DIVISION..........................................16 8.1. FILE DEFINITION.............................................16 8.2. RECORD DESCRIPTION..........................................17 9. FURTHER PROCEDURE DIVISION.....................................19 9.1. File Handling Verbs - OPEN..................................19 9.2. READ........................................................19 9.3. WRITE.......................................................20 9.4. CLOSE.......................................................20 10. Data Handling Verbs...........................................21 10.1. MOVE......................................................21 10.2. MOVE - Other Considerations...............................22 11. PERFORM.......................................................23 11.1. Sections..................................................23 11.2. PERFORM with UNTIL phrase.................................25 11.3. PERFORM with TIMES phrase.................................26 12. Decimal Point.................................................27 12.1. MOVE and Decimal Points...................................27 13. Signed Fields.................................................28 13.1. IF........................................................29 13.2. GO TO.....................................................30 13.3. PARM......................................................31 14. Explicit Scope Terminators....................................32 15. INITIALIZE....................................................33 16. CONDITION-NAMES (88 LEVEL)....................................34 17. SET TO TRUE...................................................35 18. In-Line PERFORM...............................................37 IT TRAINING 1
124
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: COBOL

COBOL Programming Last Printed: 08/04/23

CONTENTS

1. What is a program?...........................................................................................................41.1. What is COBOL?........................................................................................................41.2. Course Conventions...................................................................................................61.3. Glossary..................................................................................................................... 61.4. General rules for columns...........................................................................................6

2. Overview of a COBOL Program.........................................................................................73. IDENTIFICATION DIVISION..............................................................................................84. ENVIRONMENT DIVISION...............................................................................................95. DATA DIVISION..............................................................................................................10

5.1. Level Number...........................................................................................................105.2. Name........................................................................................................................ 105.3. Picture...................................................................................................................... 10

6. WORKING-STORAGE SECTION....................................................................................116.1. Example.................................................................................................................... 116.2. FILLER..................................................................................................................... 126.3. VALUE...................................................................................................................... 126.4. Spacing..................................................................................................................... 12

7. PROCEDURE DIVISION.................................................................................................137.1. ACCEPT...................................................................................................................137.2. ACCEPT.... FROM...................................................................................................147.3. DISPLAY.................................................................................................................. 157.4. GOBACK..................................................................................................................15

8. FURTHER DATA DIVISION............................................................................................168.1. FILE DEFINITION.....................................................................................................168.2. RECORD DESCRIPTION.........................................................................................17

9. FURTHER PROCEDURE DIVISION...............................................................................199.1. File Handling Verbs - OPEN.....................................................................................199.2. READ....................................................................................................................... 199.3. WRITE...................................................................................................................... 209.4. CLOSE.....................................................................................................................20

10. Data Handling Verbs....................................................................................................2110.1. MOVE................................................................................................................... 2110.2. MOVE - Other Considerations..............................................................................22

11. PERFORM................................................................................................................... 2311.1. Sections................................................................................................................2311.2. PERFORM with UNTIL phrase.............................................................................2511.3. PERFORM with TIMES phrase.............................................................................26

12. Decimal Point...............................................................................................................2712.1. MOVE and Decimal Points....................................................................................27

13. Signed Fields...............................................................................................................2813.1. IF........................................................................................................................... 2913.2. GO TO.................................................................................................................. 3013.3. PARM....................................................................................................................31

14. Explicit Scope Terminators...........................................................................................3215. INITIALIZE................................................................................................................... 3316. CONDITION-NAMES (88 LEVEL)................................................................................3417. SET TO TRUE.............................................................................................................3518. In-Line PERFORM.......................................................................................................3719. Figurative Constants - 1...............................................................................................38

19.1. ZERO....................................................................................................................3819.2. SPACE or SPACES..............................................................................................38

20. VALUE......................................................................................................................... 3921. READ ... INTO..............................................................................................................4022. WRITE ... FROM..........................................................................................................4023. PRINTING.................................................................................................................... 4124. Naming Standards for Print Fields...............................................................................4325. Editing fields.................................................................................................................43

25.1. Z (Suppression)....................................................................................................44

IT TRAINING 1

Page 2: COBOL

COBOL Programming Last Printed: 08/04/23

25.2. * Cheque Protect (Replacement).........................................................................4425.3. £ Fixed (Insertion).................................................................................................4425.4. £ Floating (Replacement).....................................................................................4525.5. Plus and Minus Signs (Insertion)..........................................................................4525.6. + or - Fixed (Insertion)...........................................................................................4525.7. + and - Floating (Replacement).............................................................................4625.8. Credit or Debit Indicators (Insertion).....................................................................4625.9. Blank Spaces (Insertion).......................................................................................4625.10. Commas (Insertion)..............................................................................................4725.11. Slash (Insertion)....................................................................................................4725.12. Full Stop or Decimal Point (Insertion)...................................................................4825.13. BLANK WHEN ZERO...........................................................................................48

26. Figurative Constants 2.................................................................................................4926.1. HIGH-VALUE or HIGH-VALUES...........................................................................4926.2. LOW-VALUE or LOW-VALUES............................................................................4926.3. ALL....................................................................................................................... 49

27. COPY........................................................................................................................... 5028. Arithmetic Verbs...........................................................................................................51

28.1. ADD...................................................................................................................... 5128.2. ROUNDED............................................................................................................5228.3. ON SIZE ERROR..................................................................................................5328.4. SUBTRACT...........................................................................................................5428.5. MULTIPLY............................................................................................................5528.6. DIVIDE.................................................................................................................. 56

29. Conditions.................................................................................................................... 5729.1. IF ... ELSE.............................................................................................................5729.2. IF ... AND..............................................................................................................5729.3. IF ... OR................................................................................................................5829.4. IF....NOT...............................................................................................................5829.5. IF - Testing Field Contents....................................................................................59

30. COMPUTE................................................................................................................... 6030.1. IF and Arithmetic Expressions..............................................................................60

31. EVALUATE.................................................................................................................. 6132. Numeric fields..............................................................................................................63

32.1. PACKED-DECIMAL..............................................................................................6332.1.1. Decimal point in a packed decimal field.............................................................6332.1.2. Length of a packed decimal field.......................................................................63

32.2. BINARY.................................................................................................................6432.2.1. Binary Fields and Length...................................................................................6432.2.2. Decimal point in a binary field............................................................................64

32.3. Choice of numeric fields........................................................................................6532.3.1. Zoned decimal...................................................................................................6532.3.2. Packed decimal.................................................................................................6532.3.3. Binary................................................................................................................65

33. File Handling................................................................................................................6633.1. Implicit Redefinition...............................................................................................66

34. Variable Length Records..............................................................................................6835. REDEFINES.................................................................................................................69

35.1. Further Examples..................................................................................................7036. OCCURS, SUBSCRIPTS and TABLES.......................................................................71

36.1. Further Considerations..........................................................................................7337. OCCURS DEPENDING ON.........................................................................................74

37.1. Length Calculation................................................................................................7537.2. Further Considerations..........................................................................................76

38. APPLY WRITE ONLY..................................................................................................7739. PERFORM VARYING..................................................................................................7840. STRING....................................................................................................................... 79

40.1. Further Considerations..........................................................................................8041. UNSTRING.................................................................................................................. 80

41.1. Further Considerations..........................................................................................80

IT TRAINING 2

Page 3: COBOL

COBOL Programming Last Printed: 08/04/23

42. NORWICH UNION DATES..........................................................................................8143. GO TO....DEPENDING................................................................................................8244. COBOL Subroutines....................................................................................................83

44.1. CALL..................................................................................................................... 8344.1.1. Further Consideration........................................................................................84

44.2. Link Editing...........................................................................................................8445. INSPECT...................................................................................................................... 8546. REFERENCE MODIFICATION....................................................................................8547. INDEXED.....................................................................................................................86

47.1. Further Considerations..........................................................................................8648. Modifying Indexes........................................................................................................87

48.1. SET....................................................................................................................... 8748.2. SEARCH...............................................................................................................8848.3. Serial Search........................................................................................................8948.4. Binary Search.......................................................................................................9048.5. Comparison Between Subscripting and Indexing..................................................9248.6. Further Considerations..........................................................................................94

49. INDEX.......................................................................................................................... 95

IT TRAINING 3

Page 4: COBOL

COBOL Programming Last Printed: 08/04/23

1. What is a program? A program is a collection of statements written in a language the computer understands. A computer executes program statements one after another in sequence until it reaches the end of the program unless some statement in the program alters the order of execution.

1.1. What is COBOL?In 1959 it was decided that it would be desirable to produce a common programming language for business applications. Until 1959 each computer had its own specific language which was either numeric or machine code.

The benefits of this common language would be:

1. It would be machine independent and thus transfer of programs between machines would be easier.

2. The language would be in English narrative form.3. Relatively inexperienced personnel could write programs.4. Training of personnel could be speeded up.5. The language should be designed so that new facilities can be added when

necessary.

From the above aims COBOL was designed.

COBOL stands for COmmon Business Oriented Language (or COmmercial Business Oriented Language in some texts).

The language emphasises the description and handling of data items and of input/output records. Instead of extensive algebraic or logical processing, COBOL applications manipulate large files of data in a relatively simple way.

Today COBOL is available on a large range of machines. It is produced to American National Standards Institute (ANSI) specifications. The benefit of the standard is that the same COBOL instructions work in the same way on every machine.

COBOL is an English based language that can be self-documenting. Like any language it has its own grammar or syntax rules which must be adhered to. It is part of the COBOL syntax that instructions are written in the correct place and throughout this course column positions will be given. The general rule is one COBOL statement per line but the exact layout of statements will be described (where applicable) later in the course.

The current version of COBOL is COBOL 85. It got that name from the year in which the standard was adopted. The marketing name for COBOL 85 is COBOL II. Before this version everyone was using COBOL 74 but calling it COBOL or OS/VS COBOL (on the mainframe).

COBOL II is a licensed program that prepares COBOL programs for execution in an IBM processor. COBOL II extends many of the capabilities of any previous COBOL product, allowing for improved programmer productivity, application efficiency, debugging and maintenance.

To coincide with the implementation of COBOL II, Norwich Union introduced a revised set of COBOL Programming Standards. These standards apply to all COBOL code that should be written in COBOL II (on the mainframe) or COBOL/2 (on the PC).

The purpose of the standards is to ensure that all COBOL programs written within NU are a consistent style. By adhering to the standards, programmers will ensure that their programs are written and maintained in the most efficient way.

IT TRAINING 4

Page 5: COBOL

COBOL Programming Last Printed: 08/04/23

Some of the changes to the standards are due to Norwich Union's adoption of Systems Application Architecture (SAA) - IBM's family of standard interfaces that enable software to be written independently of hardware and operating system. At its simplest it means that systems written to the SAA standards should run virtually unchanged on IBM mainframes and micros. The standards therefore state that all code written should be SAA compliant. Exceptions have only been made to provide existing functionality and where there is considerable advantage to be gained from using non-SAA code.

IT TRAINING 5

Page 6: COBOL

COBOL Programming Last Printed: 08/04/23

1.2. Course Conventions.

Actual COBOL code examples are in Courier Font.

The programmer must supply words in lower case within a code example or format.

Words in brackets within a code example or format are optional.

1.3. Glossary.

A COBOL sentence must end with a full stop. A sentence consists of one or more COBOL statements.

Integer means a whole number with no sign or decimal point.

A numeric literal consists of the digits 0-9. If a sign + or - is included it must be the leftmost character. A decimal point may be included too.

A non-numeric literal consists of any character from the EBCDIC character set, enclosed in quotes ('), with a maximum length of 120 characters.

A dataname is a programmer-defined word that names a data item:

its name may contain 1 to 30 characters (A-Z, 0-9 or - (hyphen), but it can not begin or end with a hyphen).

it must contain at least 1 alphabetic character and must be unique within a program.

it must not be a COBOL reserved word.

An identifier is one or more words making a unique reference to a data item through qualification, subscripting or indexing.

1.4. General rules for columns.

Columns 1 to 6 are reserved for line numbers. By putting a * in column 7 the remainder of the line is then regarded as documentation and is ignored by the compiler.

All divisions, sections and paragraphs, file descriptions and record names must begin in what is known as region A (columns 8, 9, 10 and 11). Everything else must be in columns 12 to 72 (known as section B). Everything past column 72 is treated as a comment and is ignored by the compiler.

Numbers *A B comments

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

IT TRAINING 6

Page 7: COBOL

COBOL Programming Last Printed: 08/04/23

2. Overview of a COBOL Program.

A COBOL program consists of COBOL statements. These statements have to conform to certain rules, which will be given when the statements are described. The position of statements will be given where appropriate.

A COBOL program is divided into 4 divisions:

IDENTIFICATION DIVISIONENVIRONMENT DIVISIONDATA DIVISIONPROCEDURE DIVISION

IDENTIFICATION DIVISION

This division names the program and the author and gives the date the program was written. It should also contain comments giving a brief description of the program. When a program is amended due to maintenance a note of the date and a brief description of the amendment will also be given here.

ENVIRONMENT DIVISION

This division describes where to find any files your program will use by defining the relationship between hardware devices and the files that use those devices.

DATA DIVISION

The data division is a repository of information about the data the program uses. This division will contain a description of all the files the program accesses. Any work fields and constants will also be described here. All statements in this division relate to the format in which data is input, stored or output.

PROCEDURE DIVISION

This contains the program logic. The COBOL verbs are used here to tell the computer how to manipulate the data you have described. This division is normally subdivided into sections, each section apart from the first doing a particular task. The first section is the control section and it defines the order in which the program works. The technique of dividing a program into sections is called structuring.

IT TRAINING 7

Page 8: COBOL

COBOL Programming Last Printed: 08/04/23

3. IDENTIFICATION DIVISION .

This division in most programs will be in the following form.

IDENTIFICATION DIVISION.starting in column 8

PROGRAM-ID. starting in column 8

This is followed on the next line by the name of the program starting in column 26. The form of program names is:

Pppsxxxx

P indicates that this is a program name.pp is the project code, e.g. TR for Training, MO for Motor.s is the suite indicator, for example:

M monthly U utilityA ad-hoc D daily W weekly M monthly Q quarterly U utility (not usually in production)R request (i.e. production but run on request) Y yearlyX one off (production but only run once)

xxxx alphanumeric identifier to give uniqueness within suite.

Example. PTRA025

NB.Program names are always given in the program specification.

AUTHOR. starting in column 8

The programmer’s name is on the next line starting in column 26. Do not use just initials.

DATE-WRITTEN.starting in column 8

This is followed on the next line, starting in column 26, by the date the program was written usually only months and years. E.g. AUGUST 1996.

The IDENTIFICATION DIVISION ends with a comment box (NB. a comment line starts with a * in column 7). Comments are enclosed in a box of asterisks. The comment here will give a brief description of the program. An amendment log skeleton should be coded containing the following information:

Date DP131 number (if used) Programmer Name (RACFID) Description of the change(s)

in ascending chronological order. For examples of identification division layouts see either the Norwich Union COBOL II Programming Standards or the example programs from this course.

IT TRAINING 8

Page 9: COBOL

COBOL Programming Last Printed: 08/04/23

4. ENVIRONMENT DIVISION .

ENVIRONMENT DIVISION. starts in column 8

INPUT-OUTPUT SECTION.

This section names the files that the program handles i.e. reads and writes to. The SELECT .. ASSIGN statements links a filename to a DD name. DD names provide the link between the file referenced within the program and the actual data sets. This means a program is written to operate on a certain type of file, e.g. a motor mainfile, whilst the actual data set does not have to be defined until runtime.

INPUT-OUTPUT SECTION.starts in column 8

FILE-CONTROL. starts in column 8

SELECT filename ASSIGN ddname.starts in column 12

There has to be a SELECT statement for each file in the program. Sometimes the select statement requires additional information. This will be described, where appropriate later in this course.

Filename will be the same as the file definition (FD) statement and be in the form: PP-<meaningful-name>-FILE. where PP is Project code. e.g. TR-ACCOUNT-FILE.

NB. Meaningful name should not be longer than 8 characters.

DDnames will be in the form:

AAnn AA is LP for print files UT for a disk or tape sequential file DA for VSAM files ST for Sort Files nn is in the range 01 - 09 for input 11 - 19 for output 21 - 29 for input/output e.g. UT11, DA21, LP11

IT TRAINING 9

Page 10: COBOL

COBOL Programming Last Printed: 08/04/23

5. DATA DIVISION .

The data division contains descriptions of all data fields referenced in the program. Each data field consists of a level number, name and data description.

5.1. Level NumberLevel numbers within the data division are used to indicate which data items are sub components of others. Level numbers range from 01 to 49, with 01 always being used to denote the highest level. At Norwich Union we only use the odd level numbers (01, 03, 05, etc.). Level number 01 should start in column 8, level 03 in column 12 and subsequent numbers indented by two - e.g. 05 in column 14, 07 in column 16, etc.

5.2. NameThe next component of a data field is its name. The rules for data names are as follows:

The first character must be alphabetic It cannot be a COBOL reserved word Cannot contain spaces Hyphens must be embedded Must be unique within a program

The programmer has the responsibility for inventing these names and they should convey the meaning and nature of the data. The NU programming standards dictate that all data names within the working storage section conform to the following rules:

The first character must be a W The next characters give guidance to the section in which the data item is used in the

form of the section number The next character will be a hyphen The remainder of the data name should be meaningful, using hyphens to replace

spaces

5.3. PictureA description of the type and size of data it will hold complete the data field. We will consider two types of data - numeric and alphanumeric. Numeric data consists of digits 0 to 9 with or without a sign. Alphabetic data consists of any characters in the EBCDIC characterset.The information is held as a PICTURE clause. There are two characters that are used to represent the data held within a field - 9 and X. Numeric data is represented by a 9 in the picture clause and alphanumeric by an X.

For example, a one character numeric field can hold any number from 0 to 9 and would have this picture clause:

PICTURE IS 9

The phrase 'picture is' is normally abbreviated to PIC, hence PIC 9. If the field needed to hold a larger number, say 76, then the number of characters would have to be extended to two, a PIC 99, which has the range 00 to 99.

Alphanumeric data follows the same principles. A field to hold a six letter word has the picture:

PIC XXXXXX

Where the descriptor is repeated a shorter notation can be used. In this case PIC X(6) would mean the same. This applies to numeric data as well, e.g. a 7 digit numeric field is shown as a PIC 9(7).

IT TRAINING 10

Page 11: COBOL

COBOL Programming Last Printed: 08/04/23

6. WORKING-STORAGE SECTION.

The Working-Storage Section describes data fields that are developed and processed by the program. It also describes data items whose values are assigned in the source program and do not change during execution of the object program (i.e. constants).

The format of this section is as follows: WORKING-STORAGE SECTION.

starts in column 8

This is followed by descriptions of the Working-Storage fields.

6.1. ExampleA data item to contain a count of the number of policies that is referenced most often in the section with the number 70 could be:

W70-POLICY-COUNT

Even though COBOL would be happy with it being called A. By using these conventions and meaningful names the program is easier to maintain.

Data fields example, assuming this data is need in the section with the number 30:

FIELD NAME FIELD TYPE LENGTH Possible dataname PICTURE

Name Alphanumeric 32 bytes W30-NAME PIC X(32)Staff Number Numeric 2 bytes W30-STAFF-NUMBER PIC 99Date Numeric 8 bytes W30-DATE PIC 9(8)Hours Numeric 3 bytes W30-HOURS PIC 9(3)

Fields beginning with the same Wnn prefixes are grouped together under an 01 level called Wnn-WORKFIELDS (e.g.W30-WORKFIELDS). Using the previous example the data structure would look like this:

01 W30-WORKFIELDS. 03 W30-NAME PIC X(32). 03 W30-STAFF-NUMBER PIC 99. 03 W30-DATE PIC 9(8). 03 W30-HOURS PIC 9(3).

NB. Each line is terminated by a full stop.

COLUMN POSITIONS

In this example W30-WORKFIELDS consists of 4 further fields. Each of these further fields, known as elementary items, has a picture. One character in these fields takes up one byte of storage so the length of W30-NAME is 32 bytes, W30-DATE is 8 bytes, etc. The length of W30-WORKFIELDS is the total length of the fields within it (i.e. 45 bytes). W30-WORKFIELDS is known as a group field. Group fields can consist of further group fields and elementary fields.

IT TRAINING 11

Page 12: COBOL

COBOL Programming Last Printed: 08/04/23

If, for example, we know that the date component is in the following format DDMMYYYY then we could split up the field into further elementary fields:

03 W30-DATE. 05 W30-DAY PIC 99. 05 W30-MONTH PIC 99. 05 W30-YEAR PIC 9(4).

The total length of W30-DATE is still 8 bytes but now we can directly access the year component of it for calculation purposes.

The working storage section should always begin with a literal in the form:

01 FILLER PIC X(25) VALUE '<PROGRAM> W-S STARTS HERE'.

The length of this field should the total of the program name, spaces and other words with in the quotes.

6.2. FILLERWhen a field is not going to be referenced a special dataname of FILLER is used. The following rules apply to FILLER:

It may not be referenced by a COBOL verb. it may appear many times in a program and is therefore not unique. It can be at any level. Always described as an alphanumeric (i.e. PIC X(n)) field. If several adjacent fields are not to be referenced in the program, their total length can

be summed and described in one FILLER.

6.3. VALUETo give a value at the start of the program to a field in WORKING-STORAGE. Its use is normally used to set up fields that will retain the value for all the time the program is executing. The VALUE clause follows the picture in column 55. If the data that is to be held in the field as a result of the VALUE clause contains anything non-numeric it must be held in single quotes (APOSTS). Numeric information does not need the quotes.

6.4. Spacing.Blank lines should be inserted as follows:

5 blank lines between DIVISIONS3 blank lines between SECTIONS2 blank lines between FDs1 blank line between 01 levels

IT TRAINING 12

Page 13: COBOL

COBOL Programming Last Printed: 08/04/23

7. PROCEDURE DIVISION

The instructions within the PROCEDURE DIVISION must follow the logic of the program i.e. they must be obeyed in the correct order to give the desired outcome. The words that specify the actions are called COBOL verbs. A statement containing a COBOL verb starts in column 12. Each verb must be on a separate line. We will start by looking at some COBOL verbs and then see how these can be linked together to form a simple program.

The procedure division is split up into sections. Each section can be further sub divided by the use of paragraphs. Each section should have a name, starting in column 8, in the form:

Snn-meaningfulname SECTION.

The first section within the procedure division of a COBOL program at NU should be:

S10-CONTROL SECTION.

Following section names should increment the section number by 10, i.e. the next section will start with S20-

A section should always start with a series of comments describing what that section does then the first paragraph marker in the form:

Pnn-10.

Paragraph markers should start in column 8. The nn part reflects the section number. The section ends with a final paragraph marker in the form:

Pnn-EXIT. EXIT.

The last line ('EXIT') beginning in column 12.

7.1. ACCEPT Purpose: to get a small volume of data into a program, for example a parameter date.

Format.

ACCEPT dataname

Dataname must be either an alphanumeric (i.e. PIC X(n)) or a numeric (i.e. PIC 9(n)) field and can be any length. The system will read in as many characters as the number of bytes in the dataname. Dataname can be a group field. This format of the ACCEPT statement has to have a SYSIN DD statement in the JCL.

Example.

ACCEPT W10-PROGRAMMER-NAME.

IT TRAINING 13

Page 14: COBOL

COBOL Programming Last Printed: 08/04/23

7.2. ACCEPT.... FROM....

Purpose: This form of ACCEPT is used to extract values from COBOL reserved words - DATE, DAY or TIME. DATE and DAY are today's date (in different formats) and TIME is the current time.

Format 1.

ACCEPT dataname FROM DATE.

Dataname should be 6 byte numeric field. DATE is in the form YYMMDD.

Example.

ACCEPT W10-DATE FROM DATE.

Where W10-DATE is defined in Working Storage as:

03 W10-DATE PIC 9(6).

or…

03 W10-DATE. 05 W10-YEAR PIC 99. 05 W10-MONTH PIC 99. 05 W10-DAY PIC 99.

if the individual components of the date need to be accessed. Here 6 bytes of data will be input to the program.

Format 2.

ACCEPT dataname FROM DAY.

Dataname should be a 5 byte numeric field. DAY is the Julian date format in the form YYDDD.

The Julian date consists of the year and days into that year (e.g. 13.2.96 is 96044 and 31.12.96 is 96366)

Format 3.

ACCEPT dataname FROM TIME.

Dataname should be an 8 byte numeric field. TIME is 2 digits for hour, 2 digits for minutes, 2 digits for seconds and 2 digits for hundredths of second i.e. in the form HHMMSSCC.

IT TRAINING 14

Page 15: COBOL

COBOL Programming Last Printed: 08/04/23

7.3. DISPLAY.

Purpose: To output small amounts of information. The information is written to the SYSOUT DD statement in the JCL.

Format.

DISPLAY dataname.DISPLAY literal 1 literal 2.DISPLAY literal 1 dataname.

Example.

DISPLAY 'DATE ASSUMED' W20-DATE.

NB.There is no limit on the number of characters, but should be restricted to less than 80 bytes. The data should be numeric or alphanumeric for best results. DISPLAY can also be used for debugging.

7.4. GOBACK.

Purpose: to stop the program execution. The GOBACK statement specifies the logical end of a program.

Format.

GOBACK.starting in column 12

There should be only one GOBACK in a program because any statements logically following the GOBACK are not executed.

The GOBACK is always located at the of the S00-CONTROL-SECTION (NU Standard):

S00-CONTROL SECTION. ******************************************************* * * * * * CONTROLS THE PROGRAM * * * * * ******************************************************* P00-10. COBOL statements. P00-EXIT. GOBACK.

IT TRAINING 15

Page 16: COBOL

COBOL Programming Last Printed: 08/04/23

8. FURTHER DATA DIVISION .

This division contains descriptions of all data fields referenced in the program. There can be three sections in the DATA DIVISION:

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 developed and processed by the program.

Linkage Section.Describes data made available by another program. It 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.

FILE SECTION starting in column 8

8.1. FILE DEFINITION.

A file definition is needed for each file used in the program. The file definition (or FD) for each file is in the following format.

FD filenamestarting in column 8

Filename must tie back to a SELECT....ASSIGN statement. Sequential files need the following statements:

BLOCK 0starting in column 12

The block clause specifies the number of logical records contained within a physical record. This is determined by the SMS (System Managed Storage) at runtime.

RECORDING MODE F or Vstarting in column 12

This tells the program that the records in this file are all the same length (F for fixed), or vary in length (V for variable).

Example File Definition.

FD TR-MAIN-FILE BLOCK 0 RECORDING MODE F.

IT TRAINING 16

Page 17: COBOL

COBOL Programming Last Printed: 08/04/23

8.2. RECORD DESCRIPTION.

Following the FD statement there is a description of the record(s) found in that file. As the program can only deal with one record at a time it need only be described once for each type of record contained on the file. If there is more than one type of record on a file there must be a record description for each type. Files containing more than one type of record are described later in this course. For the moment we will assume a file only contains one type of record.

Record Names.

Format.

pp-<meaningful-name>-REC

Where pp is the project code and must be the same as for the associated file.Meaningful-name must be the same as for the associated file name.

Example.

TR-MAIN-REC

A suffix is optional and is only required when there is more than one record definition associated with the file.

pp-<meaningful-name>-REC-suffix

Example.

TR-ACCOUNT-REC-1

Each line (or multiple lines) of data is known as a logical record and is subdivided into smaller areas of information known as fields.

Within a record, information is held in these fields. They have to be described in the order they are within the record. Fields can be one of two types; group or elementary. Group fields can be broken down into further (group and elementary) fields whereas elementary fields can not.

Example.

A file contains details of hours worked by employees. Each record on the file holds the following information:

Name, consisting of first name, second name and surname. Employee number Date, consisting of day, month and year, Hours worked.

In COBOL we represent this structure by level numbers. The topmost level or record name is level 01 and each successive level downwards is 03, 05, 07 etc. In the above example Name, Employee number, Date and Hours worked would be 03 level whilst first name, second name, surname, day, month and year would be 05 levels.

IT TRAINING 17

Page 18: COBOL

COBOL Programming Last Printed: 08/04/23

This could be written as in FIGURE 1. The indentation follows the NU Programming Standards:

01 starts in column 8. 03 starts in column 12. 05 starts in column 14. 07 starts in column 16 etc.

Level numbers are in the range 01 to 49 (we only use odd). There is an 88 level, which has a special meaning and will be described later in this course.

The names attached to the level numbers are data names. We also have to apply the NU Programming Standards. These state that the project letter prefix of filename followed by a hyphen should prefix any field name.

Data names start in column 21. The exception is when the level number is greater than 09, in which case the most appropriate column should be used.

Following the dataname formation rules and the NU programming standards FIGURE 2 is the correct layout.

IT TRAINING 18

Page 19: COBOL

COBOL Programming Last Printed: 08/04/23

9. FURTHER PROCEDURE DIVISION .

The instructions within the PROCEDURE DIVISION must follow the logic of the program i.e. they must be obeyed in the correct order to give the desired outcome. The words which specify the actions are called COBOL verbs. A statement containing a COBOL verb starts in column 12. Each verb must be on a separate line. We will start by looking at some COBOL verbs and then see how these can be linked together to form a simple program.

9.1. File Handling Verbs - OPEN.

Purpose: to open a file. Like a book a file must be opened before it can be read or written to. The successful execution of an OPEN statement determines the availability of the file and results in that file being in open mode. A file is available if it is physically present and is recognised by the input-output control system.

The successful execution of the OPEN statement makes the associated record area available to the program; it does not obtain or release the first data record.

Format.

OPEN INPUT filename 1.

OPEN OUTPUT filename 2.

INPUT is necessary for a file that is to be read. OUTPUT is for a file that is to be written to. There may be more than one file opened for input and/or output.

Filename is that in the FD statement.

Example.

OPEN INPUT TR-ACCOUNT-FILE.

OPEN OUTPUT TR-PRINT-FILE.

9.2. READ.

Purpose: to read a record from a file. A program can only deal with one record at a time. Records are held in blocks for ease of handling and efficiency. The first read statement for a file causes the physical transmission of the first block of records from the file to a buffer, and the first record in the block is made available for processing. This means that one record at a time can be accessed via the 01 record area of the file. Each subsequent read for that file causes each subsequent record to become available until all records in the block have been processed. The next read will transfer the next block of data and thus the process will be repeated until the end of the file. The handling of the blocks of data, does not need any programmer action.

Format.

READ filename AT END imperative statement.

Filename is that named in the FD statement for this file.

IT TRAINING 19

Page 20: COBOL

COBOL Programming Last Printed: 08/04/23

AT END asks is it the end of file. The imperative statement will be obeyed if it is the end of file. End of file means the label after the last record on the file has been found this indicates that there is no data left. Imperative statement is an unconditional statement.

Example.

READ TR-ACCOUNT-FILE AT END MOVE 1 TO W90-END-OF-FILE. (MOVE will be explained later).

9.3. WRITE.

Purpose: to write a record to a file. The record is created in the record area of the output file. That is, in the fields described under the 01 entry of that file's FD. Conversely to the read, a record is written to a buffer one at a time, then when the buffer is full the data is transferred to the actual disk or tape. Once again the handling of the buffer is done automatically and is quite transparent to the programmer.

Format.

WRITE recordname.

Where recordname is the name of an 01 level in a file that has been opened for OUTPUT.

Example.

WRITE TR-OUTPUT-REC.

9.4. CLOSE.

Purpose: to close a file after all processing for that file has been completed.

A CLOSE statement may be executed only for a file in an open mode. After successful execution of a CLOSE statement:

The record area associated with the file-name is no longer available. An OPEN statement for the file must be executed before any other input/output

statement.

Unsuccessful execution of a CLOSE statement leaves availability of the record data undefined.

Format.

CLOSE filename 1. CLOSE filename 2.

Filename must be described in a FD entry.

Example.

CLOSE TR-ACCOUNT-FILE. CLOSE TR-PRINT-FILE.

IT TRAINING 20

Page 21: COBOL

COBOL Programming Last Printed: 08/04/23

10. Data Handling Verbs.

10.1. MOVE.

Purpose: The MOVE statement transfers data from one area of storage to one or more other areas in the DATA DIVISION. The data in the sending field remains the same but that in the receiving field is overwritten. As COBOL is primarily a data handling language this is one of the most used verbs.

Format.

MOVE dataname1 TO dataname 2. MOVE literal 1 TO dataname 3

dataname 4.

The data names must be described in one of the sections in the DATA DIVISION.

A literal can be either: a numeric literal, size 1 to 18 digits a non-numeric literal, size 1 to 120 characters. A non-numeric literal must be enclosed in

double quotes (i.e. 'literal').

Example.

MOVE TR-DATE TO W20-INPUT-DATE. MOVE 200 TO W30-RATE. MOVE 'INVALID' TO W20-MESSAGE TR-WARNING.

IT TRAINING 21

Page 22: COBOL

COBOL Programming Last Printed: 08/04/23

10.2. MOVE - Other Considerations.

The manner in which data is moved is governed by the picture of the receiving field (i.e. dataname 2).

If the receiving field is alphanumeric:

The data is left justified If the receiving field is smaller than the sending field the data is truncated. If the receiving field is larger than the sending field the receiving field is filled with

trailing spaces.

If the receiving field is numeric:

The data is right justified If the receiving field is smaller than the sending field the most significant digit(s) are

lost. If the receiving field is longer than the sending field the receiving field is filled with

leading zeros.

A numeric field can be moved to a numeric or alphanumeric field.

An alphanumeric field can be moved to an alphanumeric field but can only be moved to a numeric field only if it contains digits.

Example.

Sending Field Data Receiving field Data

PIC 9(3) 123 PIC 9(3) 123PIC 9(4) 1234 PIC 99 34PIC 9(3) 123 PIC 9(4) 0123PIC X(4) ABCD PIC X(3) ABCPIC X(3) ABC PIC X(3) ABC

IT TRAINING 22

Page 23: COBOL

COBOL Programming Last Printed: 08/04/23

11. PERFORM .

Purpose: the PROCEDURE DIVISION is made up of sections, each of which given a name. Sections are used when passing control to a different piece of code. All programs now written at Norwich Union are structured and make use of sections. This is the out-of-line perform but is normally referred to just as a perform. The PERFORM statement transfers control explicitly to one or more procedures and implicitly returns control to the next executable statement after execution of the specified procedure(s) is completed.

11.1. Sections.

Section Names.

Snn-meaningful name SECTION.

nn is always a multiple of 10.

Example.

S10-INITIALISE SECTION. S30-ERROR-CONTROL SECTION. S80-HEADING SECTION. S900-READ SECTION.

Each SECTION begins with a comment that briefly describes the action of that section and an initial paragraph number, e.g.

Pnn-10.

Pnn-EXIT.Starting in column 8

EXIT.Starting in column 12

Pnn-EXIT is used for clarity and readability.

NB. Spacing between sections is three blank lines.

Sections are arranged in ascending order within the Procedure Division. There can be paragraphs within sections. Do not perform paragraphs, only sections.

Sections are actioned by use of the PERFORM verb and must only perform higher numbered sections.

When a program starts processing, the first statement obeyed is the first one in the PROCEDURE DIVISION, this is also the first statement within the first section of the program. Control is then passed to other sections by use of the PERFORM statement.

Format.PERFORM section name.

Example.

PERFORM S90-READ.

IT TRAINING 23

Page 24: COBOL

COBOL Programming Last Printed: 08/04/23

NB.The system obeys the PERFORM verb by going to the section named, obeying the instructions in that section, control then returns to the statement following the PERFORM. The system recognises the end of a section either by the word SECTION in the next instruction or the end of the program. Therefore always check the word SECTION is present in the section name.

Example.

Consider the following code to print headings when the end of the page is reached:

IF W70-LINE-COUNT > 60 PERFORM S80-HEADING END-IF. MOVE TR-DESC-CODE TO W70-DESC-CODE.

S80-HEADING SECTION.

P80-10. ADD 1 TO W80-PAGE. MOVE W80-PAGE TO P-REP2-H1-PAGE. WRITE TR-PRINT-REC FROM P-REP2-H1 AFTER PAGE. MOVE 2 TO W70-LINE-COUNT. P80-EXIT. EXIT.

IT TRAINING 24

Page 25: COBOL

COBOL Programming Last Printed: 08/04/23

11.2. PERFORM with UNTIL phrase.

Sometimes we need to repeat a piece of code until a certain condition arises. In the UNTIL phrase format, the procedure(s) referred to are performed until the condition specified by the UNTIL phrase is true. Control is then passed to the next executable statement following the PERFORM statement.

Format.

PERFORM section name UNTIL condition.

Examples.

We are reading a sequential file containing records. We wish to process all the records. The following could be coded:

S20-PROCESS SECTION. ****************************************************** * * * PRINTS RECORD DETAILS * * * ****************************************************** P20-10. ADD 1 TO W20-RECORDS-READ. IF TR-ACCOUNT-NO = W10-ACCOUNT-NO PERFORM S40-DUPLICATE RECORD END-IF. PERFORM S90-READ. P20-EXIT. EXIT.

We would then perform this section until the required condition(s) is met.

PERFORM S20-PROCESS UNTIL W90-ENDFILE = 1.

We may have to consider other conditions. In a different example we may be processing accounts and may include the following statement.

PERFORM S70-ACCOUNT UNTIL TR-ACCOUNT-NO NOT = W10-ACCOUNT-NO OR W90-ENDFILE = 1.

NB.Whenever a PERFORM...UNTIL statement is first obeyed the conditions are tested first. So if the condition is satisfied the section will not be performed at all (i.e. if W90-ENDFILE does contain 1 then S20-PROCESS will not be performed).

It is a Norwich Union standard to have an INITIALISE SECTION at the beginning of each program, after the CONTROL SECTION, and a TERMINATE SECTION at the end.

IT TRAINING 25

Page 26: COBOL

COBOL Programming Last Printed: 08/04/23

A simple program may, therefore, have the following CONTROL SECTION.

S00-CONTROL SECTION. ************************************************ * * * CONTROLS THE PROGRAM * * * ************************************************ P00-10. PERFORM S10-INITIALISE. PERFORM S90-READ. PERFORM S20-PROCESS UNTIL W90-ENDFILE = 1. PERFORM S30-TERMINATE. P00-EXIT. GOBACK.

The INITIALISE SECTION is normally used to carry out instructions before the main processing takes place, such as:

Opening any files Zeroise any necessary fields, such as W90-ENDFILE.

The TERMINATE SECTION is used to carry out instructions after the main processing has taken place, such as:

Printing a terminal report. Closing any files.

11.3. PERFORM with TIMES phrase.

The procedure referred to in the TIMES phrase PERFORM statement is executed the number of times specified by the value in identifier (W30-NUMBER) or integer (4). Control then passes to the next executable statement following the PERFORM statement.

Example.

PERFORM S40-COUNT W30-NUMBER TIMES. PERFORM S20-ACCUMULATE 4 TIMES.

IT TRAINING 26

Page 27: COBOL

COBOL Programming Last Printed: 08/04/23

12. Decimal Point .

Purpose: we use a V to denote a decimal point in a field. The V does not occupy a character position, it is an implied decimal point.

Example.

A 5 byte zoned decimal with 2 decimal places is described thus:- PIC 9(3)V99

A 7 byte zoned decimal field with 5 decimal places PIC 99V9(5)

Remember that V shows the position of a decimal point, so a 4 byte field with no decimal places is really PIC 9(4)V but when the decimal point is at the end of the field it is not shown. There can only be one decimal point in a picture.

12.1. MOVE and Decimal Points.

If there is a decimal point in a field a MOVE will line up the receiving field on the decimal point.

Example.

Sending field Contents Receiving field ContentsPIC 9(3)V99 123.45 PIC 9(2)V99 23.45PIC 9(3)V99 123.45 PIC 9(3)V9 123.4PIC 9(3)V99 123.45 PIC 9(4) 0123

IT TRAINING 27

Page 28: COBOL

COBOL Programming Last Printed: 08/04/23

13. Signed Fields .

Purpose: if a field is signed this is shown by an S as the first character of the picture. It does not occupy position in a field. There can only be one S in a picture.

Example 1.

03 W20-AMOUNT PIC S9(3).

This field can hold any number is the range +999 to -999.

MOVE -35 to W20-AMOUNT.

After the move statement has been obeyed the contents of W20-AMOUNT will be:

bin 1111 0000 1111 0011 1101 0101hex F 0 F 3 D 5

Example 2.

MOVE 147 to W20-AMOUNT

After move statement has been obeyed the contents of W20-AMOUNT will be:

bin 1111 0001 1111 0100 1100 0111hex F 1 F 4 C 7

NB. When zoned decimal is signed the top bits of the rightmost byte will contain a sign

either hex C or D. Zero in a signed field is always positive. A signed field with an unsigned value gives a compiler warning.

IT TRAINING 28

Page 29: COBOL

COBOL Programming Last Printed: 08/04/23

13.1. IF.

Purpose: the IF statement evaluates a condition and provides for alternative actions in the program, depending on the evaluation.

Format.

IF condition imperative statement

END-IF.

Example.

MOVE TR-AMOUNT TO W60-AMOUNT. MOVE TR-VAT-AMOUNT TO W60-VAT-AMOUNT. IF TR-DEB-CRED-IND = 'D' MULTIPLY -1 BY W60-AMOUNT MULTIPLY -1 BY W60-VAT-AMOUNT END-IF.

The condition can be negated by the inclusion of a NOT.

Example. IF TR-DEB-CRED-IND NOT = 'C' MULTIPLY -1 BY W60-AMOUNT MULTIPLY -1 BY W60-VAT-AMOUNT END-IF.

Statements following IF should be indented 6 spaces. The explicit scope terminator END-IF should be used. Only code nested IF statements if the resulting code is more easily understood than it

would be without the nested IF statements. A maximum of 3 levels of nested IF are permitted. No in-line performs may be coded within an IF statement. All statements under an IF statement must be highly associated.

IT TRAINING 29

Page 30: COBOL

COBOL Programming Last Printed: 08/04/23

13.2. GO TO.

Purpose: a GO TO statement is a sequence control statement and enables you to branch backwards or forwards in a program. Norwich Union Standards only allow the use of a forward GO TO.

The GO TO statement transfers control to the first statement in the paragraph or section named after the GO TO. This verb may be used where it helps to simplify coding, but the following rules should be observed.

Keep the use of GO TOs to a minimum Only use forward GO TOs. These must remain within a section. Do not overlap GO TOs.

Format.

GO TO paragraph name

where paragraph name is a label in the same section. The rules for paragraph names are:

Must be unique In the form Pnn-mm. Where nn is section number and mm is a multiple of 10, starting at

10. Paragraph names are arranged in ascending order within a section. Start in column 8.

Example. GO TO P20-30.

IT TRAINING 30

Page 31: COBOL

COBOL Programming Last Printed: 08/04/23

13.3. PARM.

Purpose: To pass a small amount of data, maximum 100 characters, to a program. PARM is used in conjunction with EXEC JCL statement (explained in the JCL course).

NB.This method is preferable to ACCEPT. Parameters are passed directly to a program. An ACCEPT statement is not needed.

Format.

A LINKAGE SECTION is required; this comes after the WORKING-STORAGE SECTION. The data is automatically transferred from the JCL to the LINKAGE SECTION. The system puts the number of characters passed in the first 2 bytes of the section. If no characters are passed, this field is set to zero. Thus the first field should always be a 2 byte binary field. The data is then put in byte 3 onwards, these will be alphanumeric or zoned decimal, and can consist of several fields or groups. The Linkage Section has to be linked with the Procedure Division by coding PROCEDURE DIVISION USING ... The field named on this is the 01 field in the LINKAGE SECTION.

Example.

LINKAGE SECTION. 01 L-DETAILS. 03 L-LENGTH PIC S9(4) BINARY. 03 L-DATE PIC 9(6). .... .... PROCEDURE DIVISION USING L-DETAILS.

See Intermediate JCL book for examples of JCL to use in conjunction with PARM & LINKAGE SECTION.

IT TRAINING 31

Page 32: COBOL

COBOL Programming Last Printed: 08/04/23

14. Explicit Scope Terminators .

An explicit scope terminator marks the end of certain Procedure Division statements. Their main function is to increase the legibility of the source code.Explicit scope terminators must be used with the following verbs:

EVALUATE IF PERFORM (in-line only)

Example.

IF W30-ORDER-1 = 'BURGER' MOVE W30-BIG-MAC TO W30-BURGER MOVE 2 TO W30-MEAL-INDICATOR END-IF.

NB. Explicit scope terminators may be used to enhance the clarity of the program with the following verbs:

ADD, REWRITE, CALL, SEARCH, COMPUTE, START, DIVIDE, STRING, MULTIPLY, SUBTRACT, READ, UNSTRING, RETURN, WRITE.They are of the most use when the statement following the verb is quite large.

IT TRAINING 32

Page 33: COBOL

COBOL Programming Last Printed: 08/04/23

15. INITIALIZE .

Purpose: at the beginning of a program the contents of working storage fields are unpredictable. It is quite common to initialise fields at the beginning of a program (i.e. in the S10-INITIALIZE SECTION).

Format.

INITIALIZE dataname 1 (dataname 2 ...)

Example.

Field Description After INITIALIZEPIC 9(5) ZEROPIC S9(3) PACKED-DECIMAL ZEROPIC S9(4) BINARY ZEROPIC X(5) SPACES

One of the advantages of the INITIALIZE statement is that you can reset the values of subordinate items by initialising only the group item. This facility may be extremely useful for initialising tables.

By using INITIALIZE on a group field, alphanumeric elementary fields will be set to spaces and numeric to zero.

Example.

01 W10-DETAILS. 03 W10-ACCOUNT-NO PIC 9(8). 03 W10-NAME PIC X(28). 03 W10-ADDRESS PIC X(32).

After executing the following code:

INITIALIZE W10-DETAILS.

W10-ACCOUNT-NO will have the value zero, W10-NAME and W10-ADDRESS will be space filled.

IT TRAINING 33

Page 34: COBOL

COBOL Programming Last Printed: 08/04/23

16. CONDITION-NAMES (88 LEVEL ).

Using a condition-name is another way of setting up a relationship test. To use a condition-name the data field (which must be an elementary item) that is to be tested has extra entries following it. These extra entries have a level number of 88. Each 88 level has a data name, which is called a condition-name, followed by a VALUE clause. VALUE is coded in column 41.

Format:

88 condition-name VALUE literal 1 (THRU literal 2) literal 4 (THRU literal 5) ...............

Example.

TR-BRANCH is held as a number in the range 1 to 470.A main branch is when TR-BRANCH is equal to 1,2,3,4,5,11,12,13,14,15,45.

This can be described in the FILE SECTION as

03 TR-BRANCH PIC S9(3) PACKED-DECIMAL. 88 MAIN-BRANCH VALUE 1 THRU 5 11 THRU 15 45.

Then the tests:

IF MAIN-BRANCH .............is equivalent IF TR-BRANCH < 6 OR > 10 and < 16 OR = 45 ............

By choosing a meaningful condition-name, the coding in 1. is easier to follow.88 levels can be used in the FILE SECTION or the WORKING-STORAGE SECTION. 88 levels can be used with an OCCURS field, they are described in the same way.

Example.

03 W30-VALUE PIC 99 OCCURS 24. 88 VALID-VALUE VALUE 2 5 7 13.

When referenced the condition-name must be subscripted by a subscript or index (explained later).

Example.

IF VALID-VALUE(W30-SUB) ............

Condition-names can be used with alphanumeric fields, the literal must be in quotes.

IT TRAINING 34

Page 35: COBOL

COBOL Programming Last Printed: 08/04/23

Example.

03 W20-MONTH PIC X(4). 88 REQUIRED-MONTH VALUE 'JAN' 'JUNE' 'JULY'. 03 W10-IDENTIFIER PIC X. 88 VALID-IDENTIFIER VALUE 'A' THRU 'J'.

A simple example would be the end of file marker. The following statement might be written.

PERFORM S20-ACCOUNTS UNTIL W90-END-OF-FILE.

Where W90-END-OF-FILE is an 88 level - attached to an end of file indicator

01 W90-WORKFIELDS. 03 W90-ENDFILE PIC 9. 88 W90-END-OF-FILE VALUE 1.

and the read section is

READ TR-MAIN-FILE AT END MOVE 1 TO W90-ENDFILE.

17. SET TO TRUE .

This command is used for setting condition flags.

Format.

SET condition name 1 (condition name 2) TO TRUE.

Example.

WORKING-STORAGE SECTION. .... 03 W900-ENDFILE PIC 9. 88 W900-END-OF-FILE VALUE 1.

.... PROCEDURE DIVISION. .... PERFORM S900-READ UNTIL W900-END-OF-FILE. .... S900-READ SECTION. P900-10 READ TR-MAIN-FILE AT END SET W900-END-OF-FILE TO TRUE. P900-EXIT. EXIT. This command is particularly useful when a field is being used to test several conditions, and so may have many possible values.

IT TRAINING 35

Page 36: COBOL

COBOL Programming Last Printed: 08/04/23

Example.

01 TR-INPUT-RECORD. 03 TR-TRANSACTION-CODE PIC X(9). .... 01 TR-OUTPUT-RECORD. 03 TR-TYPE PIC X. 88 TR-REC-ACTIVE VALUE 'A'. 88 TR-REC-SUSPENDED VALUE 'S'. 88 TR-REC-DELETED VALUE 'D'. 03 TR-KEY PIC X(5). .... PROCEDURE DIVISION. .... IF TR-TRANSACTION-CODE = 'ADDED ' SET TR-RECORD-ACTIVE TO TRUE END-IF. IF T-TRANSACTION-CODE = 'SUSPENDED' SET TR-RECORD-SUSPENDED TO TRUE END-IF. IF T-TRANSACTION-CODE = 'DELETED ' SET TR-RECORD-DELETED TO TRUE END-IF.

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.

Example.

01 TR-OUTPUT-RECORD. 03 TR-RECORD-TYPE PIC X. 88 TR-TYPE VALUE 1 THRU 10. . . SET TR-TYPE TO TRUE.

After this code has been executed TR-RECORD-TYPE will contain 1.

IT TRAINING 36

Page 37: COBOL

COBOL Programming Last Printed: 08/04/23

18. In-Line PERFORM .

The in-line PERFORM statement allows statements to be executed whilst enclosed within the PERFORM and END-PERFORM statements, instead of being in a separate section. However code within an in-line PERFORM must be kept simple, no nested IF statements, out-of-line PERFORMS or GO TOs are allowed under NU standards (The only exception to this rule is when performing an initialise section).

Example 1.

MOVE ZERO TO W30-COMM-SUB. PERFORM 5 TIMES MOVE 'VOID' TO W30-COMMENT(W30-COMM-SUB) ADD 1 TO W30-COMM-SUB END-PERFORM.

Example 2.

PERFORM VARYING W20-TABLE-SUB FROM 1 BY W20-INCREMENT UNTIL W20-TABLE-SUB > 30 OR W20-TABLE-CODE(W20-TABLE-SUB) = 200 ADD 1 TO W20-SALARY-TOTAL(W20-TABLE-SUB) END-PERFORM.

Example 3.

PERFORM UNTIL W20-SUB1 > 20 OR W20-MEANING-LIFE(W20-SUB1 W20-SUB2) = 42 PERFORM UNTIL W20-SUB2 > 30 OR W20-MEANING-LIFE(W20-SUB1 W20-SUB2) = 42 ADD 1 TO W20-SUB2 END-PERFORM IF W20-SUB2 > 30 MOVE 1 TO W20-SUB2 ADD 1 TO W20-SUB1 END-IF END-PERFORM.

END-PERFORM delimits the scope of the in-line PERFORM statement. Execution of an in-line PERFORM is completed after the last statement contained within it has been executed.

Statements other than imperatives statements within an in-line PERFORM must be coded with their scope terminators; e.g. END-IF as shown in the example above.

IT TRAINING 37

Page 38: COBOL

COBOL Programming Last Printed: 08/04/23

19. Figurative Constants - 1.

For certain values COBOL has a FIGURATIVE CONSTANT.

19.1. ZERO.

ZERO, ZEROES or ZEROS which are self explanatory and all mean the same.

Example.

MOVE ZERO TO W40-TOTAL. MOVE ZERO TO W90-ENDFILE.

If W40-TOTAL had the picture PIC 9(4), after the move W40-TOTAL will contain hex F0F0F0F0. If the contents of W40-TOTAL were printed it would be 0000.

ZERO, ZEROES or ZEROS can be used with any field types.

19.2. SPACE or SPACES.

Example.

MOVE SPACES TO W40-MESSAGE. MOVE SPACES TO TR-PRINT-REC.

If W40-MESSAGE had the picture PIC X(10). After the MOVE W40-MESSAGE will contain hex 40404040404040404040. If the contents of W40-MESSAGE were printed it would be (i.e. ten spaces).

SPACES or SPACES can only be moved to an alphanumeric field.

IT TRAINING 38

Page 39: COBOL

COBOL Programming Last Printed: 08/04/23

20. VALUE .

Purpose: to give a value at the start of the program to a field in WORKING-STORAGE. Its use is normally used to set up fields that will retain the value for all the time the program is executing. The VALUE clause follows the picture.

Example.

03 W20-PAGE PIC X(4) VALUE 'PAGE'.

03 W20-PAGE PIC X(15) VALUE 'PAGE NUMBER IS:'.

VALUE should be coded in column 55. If BINARY or PACKED-DECIMAL are being used or if the literal is too long to fit on the same line, value item should be coded in the most suitable place.

NB. The figurative constants ZERO, SPACES can be used with VALUE.

Assigning an initial value to a field follows the same rules as a move.

If the field is alphanumeric and

if it is longer than the VALUE it will be filled with trailing spaces. if it is shorter, it will give a compiler warning and will be truncated.

If the field is numeric and

if it is longer than the VALUE it will be filled with leading zeros. If it is shorter, the most significant figure(s) will be lost.

IT TRAINING 39

Page 40: COBOL

COBOL Programming Last Printed: 08/04/23

21. READ ... INTO .

Purpose: To put a copy of a record into an area in the WORKING-STORAGE, LINKAGE SECTION or another previously opened file. The record is also available via its record description.

Format.

READ filename INTO dataname 1 AT END imperative statement.

This statement is equivalent to:

READ filename AT END imperative statement MOVE record-name TO dataname 1.

Example. READ TR-MAIN-FILE INTO W10-RECORD AT END MOVE 1 TO W90-ENDFILE.

This statement is equivalent to:

READ TR-MAIN-FILE AT END MOVE 1 TO W90-ENDFILE. MOVE TR-MAIN-REC TO W10-RECORD.

22. WRITE ... FROM .

Purpose: to write a record to an output file, when the record has been constructed or is in another area than the record description of that output file.

Format.

WRITE record-name FROM dataname 1.

Like the READ INTO the dataname can be in WORKING-STORAGE, LINKAGE SECTION or another previously opened file. The contents of dataname are moved to the record name, then the record is written.

Example.

WRITE TR-MAIN-REC FROM W20-RECORD. WRITE TR-PRINT-REC FROM P-REP1-H1.

IT TRAINING 40

Page 41: COBOL

COBOL Programming Last Printed: 08/04/23

23. PRINTING

A lot of COBOL batch programs produce printed output. Standard computer paper at the NU is 132 print positions wide and 66 lines deep (we only print on 62). The maximum width is 150 print positions. There are several other sizes and types of stationery, including pre-printed stationery and 2,3 and 4 ply (i.e. paper with carbon). We will only consider standard stationery in our examples.

As with writing a sequential file to disk or tape the record (in this case a line of print) is assembled and then written.

The FD for a print file is normally:

FD TR-PRINT-FILE BLOCK 0 RECORDING F.

01 TR-PRINT-REC PIC X(132).

The print lines are set up in working storage, usually one line per 01 level. Consideration has to be given to spacing between fields on a line. This is done by use of the phrase:

03 FILLER PIC X(n) VALUE SPACES.

where n is the number of blank characters.

All data to be printed must be in the alphanumeric or zoned decimal form, i.e. stored as one character per byte. You can not print the contents of packed decimal or binary fields directly. Headings are set up by the VALUE clause, e.g.

03 FILLER PIC X(12) VALUE 'PAGE NUMBER'

Vertical spacing also has to be considered. The computer has to be told if we wish to write on every line, leave gaps, or write at the top of the page. This is done via an extension of the WRITE statement.

Format.

WRITE recordname AFTER integer.WRITE recordname AFTER PAGE.WRITE recordname AFTER dataname.

Integer must be a positive whole number, and this is the number of lines 'thrown' before the record is written. If AFTER n is omitted, A value of one is assumed.

Example 1. WRITE TR-PRINT-REC AFTER 2.

This code would leave one blank line before the record was written.

Example 2. WRITE TR-PRINT-REC AFTER PAGE.

This will write the line at the top of a new page (useful for page headings).

IT TRAINING 41

Page 42: COBOL

COBOL Programming Last Printed: 08/04/23

Example 3.

WRITE TR-PRINT-REC AFTER W20-PAGE-THROW.

W20-PAGE-THROW should contain a positive whole number. This is similar to Example 1.

The computer interprets the paper throw needed and writes a character at the front of the print record. This character is a standard ANSI control character. The printer then understands the control character. The printer record is therefore 133 bytes long 132 + 1 byte control character.

When printing it is the programmer's responsibility, via the logic in his code, to write the correct number of lines per page and to write headings (if required) at the top of each new page.

IT TRAINING 42

Page 43: COBOL

COBOL Programming Last Printed: 08/04/23

24. Naming Standards for Print Fields .

Datanames which describe print lines will indicate the report they belong to, and where possible, the line in the report, and will take the form:

P-xxx-ann where xxx is report name abbreviation (variable length)

a is H for Heading L for Line F for footer

nn is the line number Example.

01 P-REP1-H1. 03 FILLER PIC X(120) VALUE SPACES. 03 FILLER PIC X(4) VALUE 'PAGE'. 03 P-REP1-H1-PAGE PIC 9(4).

The above code describes a header print line at the top of a page (H1). This is the first page of a report called REP (REP1).

If the following code was executed:

MOVE W10-PAGE-NUMBER TO P-REP1-H1-PAGE. WRITE TR-PRINT-REC FROM P-REP1-H1 AFTER PAGE.

The result would be the word PAGE followed by the contents of W10-PAGE-NUMBER printed in the top right corner of a new page.

The line numbers and size of the fields are usually given on a print layout sheet in the program specification document.

25. Editing fields .

When fields are printed, especially numeric fields, we frequently wish to print extra detail (e.g. £, + - decimal point etc.) or we do not want to print (i.e. suppress) details (e.g. leading zeros). To do this editing characters are used.

Editing characters can only be used with alphanumeric and zoned decimal fields. There are two types of editing characters, insertion and replacement. An insertion editing character is additional information whilst replacement, as its name suggests, replaces digit(s) with another character.

Arithmetic functions can not be performed on edited fields but an edited field can follow GIVING in arithmetic statements or can be the receiving field in a COMPUTE statement (explained later).

IT TRAINING 43

Page 44: COBOL

COBOL Programming Last Printed: 08/04/23

25.1. Z (Suppression).

Purpose: the Z editing character replaces leading zero(s) with spaces.

If we printed the contents of a six byte numeric field containing 123 it would be printed as 000123. Normally we do not want to print three leading zeroes. To achieve this we could use the following edited field.

Example.

P-REP1-H2-AMOUNT PIC Z(5)9

Up to 5 leading zeros will be replaced by spaces but if the field is zero a single zero will be printed.

Further examples.

Data Receiving field Contents(zero) PIC Z(4) _ _ _ _8730 PIC Z(4) 8 7 3 00087 PIC Z(4) _ _ 8 70087 PIC Z(3)9 _ _ 8 7(zero) PIC Z(3)9 _ _ _ 00036 PIC Z9(3) _ 0 3 60025 PIC ZZ99 _ _ 2 5

Where _ signifies a blank space.

25.2. * Cheque Protect (Replacement).

Purpose: the cheque protect character * replaces leading zeros with *'s. This is to stop people changing figures on cheques etc.

Example.

P-REP-H2-AMOUNT PIC *(5)9

If 30 was moved to P-REP-H2-AMOUNT it would be printed as ****30.

25.3. £ Fixed (Insertion).

If only one £ sign appears in a PIC clause it is treated as being an insertion character, and will be printed in that position.

Example.

Data Receiving field Contents103 PIC £9(4) £010323 PIC £Z(4)9 £__23

IT TRAINING 44

Page 45: COBOL

COBOL Programming Last Printed: 08/04/23

25.4. £ Floating (Replacement).

If more than one £ sign appears in a PIC it is interpreted as floating. It will suppress leading zeros as dictated by the picture and will position a £ in place of the rightmost zero suppressed.

Example.

Data Receiving field Contents0000134 PIC £££9(4) £0134(zero) PIC £(3) ____8 PIC £(5) ___£8123 PIC ££99 £123

NB.The number of £ signs plus the number of 9's in a picture must be one more than the maximum number of digits in a field.i.e. PIC 9(6) containing 123456 moved to a PIC £(6) would print £23456.

25.5. Plus and Minus Signs (Insertion).

When using a plus or a minus sign the following applies:

A minus sign in a picture will be printed if the item is negative and a space will appear if the amount is positive, zero or unsigned.

A plus sign will be printed if the item is positive, unsigned or zero and a minus sign will be printed if the item is negative.

25.6. + or - Fixed (Insertion).

NB.Only one + or - will be interpreted as fixed. Like the £ sign it will be printed where it appears in a picture.

Example.

Data Receiving field Contents+33 PIC -99 _33-33 PIC 99- 33--33 PIC -99 -33(zero) PIC -99 _00(zero) PIC +99 +00-22 PIC +99 -22+20 PIC 99+ 20+

IT TRAINING 45

Page 46: COBOL

COBOL Programming Last Printed: 08/04/23

25.7. + and - Floating (Replacement).

NB.More than one + or - sign in a picture will be interpreted as replacement. These will appear at the beginning of the picture only. Once again like £ sign the number of + or - must be one more than the number of digits to be suppressed.

Example.

Data Receiving field Contents123 PIC --99 123-12 PIC -(3)99 -12(zero) PIC -(4)12 PIC ++99 +12-6 PIC ++9 -6(zero) PIC +(4)123 PIC ++99 +123

25.8. Credit or Debit Indicators (Insertion).

Purpose: to print CR or DB when the field in whose PIC they are, is negative.

Example.

03 P-REP-L2-AMOUNT PIC Z(6)9CR.

If P-REP-L2-AMOUNT contains -12, 12CR will be printed.

03 P-REP-L2-AMOUNT PIC Z(6)DB.

If P-REP-L2-AMOUNT contains -45, 45DB will be printed.

NB.In both cases if the field moved to P-REP-L2-AMOUNT is positive, zero or unsigned, spaces are printed in place of CR or DB.

25.9. Blank Spaces (Insertion).

Purpose: to insert a space. Can be used with alphanumeric and zoned decimal fields.

Example.

03 P-REP-L2-DATE PIC XXBXXBXX

If '160784' was moved to P-REP-L2-DATE the printed result would be:

16 07 84

IT TRAINING 46

Page 47: COBOL

COBOL Programming Last Printed: 08/04/23

25.10. Commas (Insertion).

Purpose: to insert a comma in a numeric field.

Example.

03 P-REP-L2-AMOUNT PIC 9,999,999.

Data Receiving field Contents8388679 P-REP-L2-AMOUNT 8,388,6794567 P-REP-L2-AMOUNT 0,004,567(zero) P-REP-L2-AMOUNT 0,000,000

Combining suppression and insertion characters:

03 P-REP-L3-AMOUNT PIC Z,Z(3),Z(3).

Data Receiving field Contents8388679 P-REP-L3-AMOUNT 8,388,6794567 P-REP-L3-AMOUNT 4,567(zero) P-REP-L3-AMOUNT

NB.Suppression will override insertion. This rule applies to all editing characters.

25.11. Slash (Insertion).

Purpose: to insert a / into a field.

Example.

03 P-REP-L3-DATE PIC XX/XX/XX.

i.e. 130272 Would be printed as 13/02/72

NB.The sending field must be an elementary field, it will not work if the sending field is a group field.

IT TRAINING 47

Page 48: COBOL

COBOL Programming Last Printed: 08/04/23

25.12. Full Stop or Decimal Point (Insertion).

Purpose: to print a decimal point. A full stop will be aligned to correspond to the decimal point in the sending field. Recall in a non-edited field V indicates the position of the decimal point in a data item.

Example.

Data Receiving field Contents12.34 PIC 9(3).99 012.3412.34 PIC 9(3).9 012.312.34 PIC Z(5)9.99 12.34 .34 PIC Z(5)9.99 .3412 PIC Z(5)9.99 12.00 .02 PIC Z(6).ZZ .02(zero) PIC Z(6).ZZZ _._ .02 PIC *(5).** *****.02(zero) PIC *(5).** *****.**

NB.Only one full stop is allowed in a picture. V and . can not both appear in the same picture.There is no suppression after the decimal point.

If you wish to print a field held as pence, as pounds and pence use divide by 100 GIVING an edited field.

Example.

03 TR-PREMIUM PIC S9(7) PACKED-DECIMAL.

03 P-REP-L2-AMOUNT PIC Z(4)9.99.

DIVIDE TR-PREMIUM BY 100 GIVING P-REP-L2-AMOUNT.

25.13. BLANK WHEN ZERO.

Purpose: to fill with space(s) when an amount is zero. Can only be used with zoned decimal fields, and can not be used with the cheque protect character.

Example.

03 P-REP-L2-AMOUNT PIC Z(5)9.99 BLANK WHEN ZERO.

Small amounts will be printed as 0.04 while zero will be printed as spaces instead of 0.00.

NB.This has very limited use.

IT TRAINING 48

Page 49: COBOL

COBOL Programming Last Printed: 08/04/23

26. Figurative Constants 2 .

We have seen Figurative Constants that are COBOL terms and describe commonly needed data values (e.g. SPACE and ZERO). There are three more:

26.1. HIGH-VALUE or HIGH-VALUES.

Both spellings have the same meaning. This represents the highest possible value in a byte (i.e. each bit set to 1) - seen in hex FF. HIGH-VALUE(S) can only be used with alphanumeric fields (includes group fields).

26.2. LOW-VALUE or LOW-VALUES.

Both spellings have the same meaning. Represents the lowest possible value in a byte i.e. each bit set to zero. (HEX 00). Can only be used with alphanumeric fields (includes group fields).

26.3. ALL.

Represents one or more occurrences of a string of characters composing a literal and must be non-numeric and can only be used with alphanumeric fields.

Example.

03 FILLER PIC X(30) VALUE ALL '*'. is the same as: 03 FILLER PIC X(30) VALUE '******************************'.

03 FILLER PIC X(33) VALUE ALL '(*)'. is the same as: 03 FILLER PIC X(33) VALUE '(*)(*)(*)(*)(*)(*)(*)(*)(*)(*)(*)'.

MOVE ALL '*' TO W20-VARIABLE. is the same as: MOVE '********************' TO W20-VARIABLE. where: 03 W20-VARIABLE PIC X(20).

IT TRAINING 49

Page 50: COBOL

COBOL Programming Last Printed: 08/04/23

27. COPY .

Purpose: to copy into your program pieces of code. This is usually used in the Data Division but may be in any part of a COBOL program. The advantage is code that is to be used in a lot of programs needs only to be written (and stored) once. Record descriptions are usually copied. This is so all programs that access the same file type use the same field names, this leads to easier understanding and maintenance and also saves programmer time and effort.

The COPY statement instructs the compiler to copy the text name into your program at compilation time. The text is stored in a partitioned dataset. The text name being membername.

Format.

COPY text name

Example.

01 TR-MAIN-REC. COPY MAINFILE.

After the compilation:

01 TR-MAIN-REC. COPY MAINFILE. 03 TR-ACCOUNT .....

Copied record descriptions normally start at the 03 level, this is so record names can be decided as appropriate per program.

IT TRAINING 50

Page 51: COBOL

COBOL Programming Last Printed: 08/04/23

28. Arithmetic Verbs .

Purpose: arithmetic verbs can not be performed on alphanumeric fields, they can only be used with numeric fields. Packed decimal and binary are preferable to zoned decimal.

The following fields will be used in examples

03 TR-PREMIUM PIC S9(7) PACKED-DECIMAL. 03 W10-TOTAL PIC S9(7) PACKED-DECIMAL. 03 W20-GRAND-TOT PIC S9(7) PACKED-DECIMAL.

28.1. ADD.

The ADD statement sums two or more numeric operands and stores the result.

Format 1.

ADD dataname1 TO dataname 2ADD literal1 dataname1 TO dataname 2

The answer is put in the dataname following the TO, thus this can not be a literal. All identifiers or literals preceding the key word TO are added together, and this sum is added to and stored in dataname 2.

Example 1.

ADD TR-PREMIUM TO W10-TOTAL. ADD 8 TO W10-TOTAL.

More than two fields can be used:-

Example 2.

ADD 8 TR-PREMIUM TO W10-TOTAL

ADD 8 TR-PREMIUM TO W10-TOTAL W20-GRAND-TOT.

ADD TR-PREMIUM TO W10-TOTAL W20-GRAND-TOT.

Format 2.

ADD dataname1 dataname 2 dataname 3 literal 1 literal 2 literal 3 GIVING dataname 4 dataname 5.

Adds up the literals and contents of fields before the GIVING and puts the answer in the dataname(s) following the GIVING, overwriting whatever is there (similar to a MOVE).

IT TRAINING 51

Page 52: COBOL

COBOL Programming Last Printed: 08/04/23

28.2. ROUNDED.

Purpose: is to round the answer if the answer field can not contain all the decimal places.

After decimal point alignment, the number of decimal places in the fraction of the result of an arithmetic operation is compared with the number of decimal places provided for the fraction of the resultant identifier.

When the size of the fractional result exceeds the number of places provided for its storage, truncation occurs unless ROUNDED is specified. When ROUNDED is specified, the least significant digit of the resultant identifier is increased by 1 whenever the most significant digit of the excess is greater than or equal to 5 (i.e. greater than or equal to .5 rounded up, less than .5 rounded down).

Example.

03 W10-AMOUNT PIC S9(5)V99 PACKED-DECIMAL. 03 W10-PREMIUM PIC S9(6)V9(3) PACKED-DECIMAL. 03 W10-GRAND-TOT PIC S9(7)V99 PACKED-DECIMAL.

If W10-AMOUNT contained 33.74 and W10-PREMIUM contained 41.389, the result of:

ADD W10-PREMIUM W10-AMOUNT GIVING W10-GRANT-TOT

would be 75.12 (i.e. the result of simply adding 33.74 to 41.389 is 75.129).

By using ROUNDED:

ADD W10-PREMIUM W10-AMOUNT GIVING W10-GRAND-TOT ROUNDED

The contents of W10-GRAND-TOT would be 75.13.

IT TRAINING 52

Page 53: COBOL

COBOL Programming Last Printed: 08/04/23

28.3. ON SIZE ERROR.

Purpose: if the result of an ADD statement is too big for the resultant field that field will be truncated i.e. leading digit(s) will be lost.If necessary this truncation can be identified by using ON SIZE ERROR.

Example.

If TR-PREMIUM contained 7785476 and W10-TOTAL contained 4477889 and the following statement was executed:

ADD TR-PREMIUM TO W10-TOTAL.

The contents of W10-TOTAL would be 2263365 as the most significant digit, a one, would be lost.

By using the following code this problem would be flagged:

ADD TR-PREMIUM TO W10-TOTAL ON SIZE ERROR imperative statement.

If the field is too small the imperative statement would be obeyed (e.g. PERFORM S70-ERROR) and the contents of W10-TOTAL would be as they were before the ADD statement was executed.

NB.Both ROUNDED and ON SIZE ERROR can be used for the same dataname.ROUNDED and ON SIZE ERROR can be applied in the same way to SUBTRACT, MULTIPLY and DIVIDE statements, and will therefore not be explained again.

IT TRAINING 53

Page 54: COBOL

COBOL Programming Last Printed: 08/04/23

28.4. SUBTRACT.

The SUBTRACT statement subtracts one numeric item, or the sum of two or more numeric items, from one or more numeric items, and stores the result.

The fields described earlier are used in the following examples.

Format 1.

SUBTRACT dataname1 FROM dataname 2SUBTRACT literal 1 FROM dataname 2

Example 1.

SUBTRACT TR-PREMIUM FROM W20-GRAND-TOT. SUBTRACT 25 FROM W20-GRAND-TOT.

Format 2.

SUBTRACT dataname1 dataname 2 FROM dataname 3 dataname 4.SUBTRACT literal 1 literal 2 FROM dataname 3.

The fields and literals before the FROM are added together and subtracted from the dataname(s) following the FROM.

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

Example 2.

SUBTRACT TR-PREMIUM FROM W20-GRAND-TOT W10-AMOUNT.

Format 3.

SUBTRACT dataname 1 literal 1 FROM dataname 2 literal 2GIVING dataname 3.

Example 3.

SUBTRACT TR-PREMIUM FROM W10-TOTAL GIVING W20-GRAND-TOT.

All datanames or literals preceding the key word FROM are added together and this sum is subtracted from dataname 2 or literal 2. The result of the subtraction is stored as the new value of each data item referenced by dataname 3.

IT TRAINING 54

Page 55: COBOL

COBOL Programming Last Printed: 08/04/23

28.5. MULTIPLY.

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

Format 1.

MULTIPLY dataname1 BY dataname 2MULTIPLY literal1 BY dataname 2

In Format 1, the value of dataname 1 or literal 1 is multiplied by the value of dataname 2; the product is then placed in dataname 2.

Example.

MULTIPLY 10 BY W10-TOTAL. MULTIPLY TR-PREMIUM BY W10-TOTAL.

Format 2.

MULTIPLY dataname 1 BY dataname 2 GIVING dataname 3.MULTIPLY literal1 BY literal 2 GIVING dataname 3.

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

Example.

MULTIPLY TR-PREMIUM BY 10 GIVING W10-TOTAL.

IT TRAINING 55

Page 56: COBOL

COBOL Programming Last Printed: 08/04/23

28.6. DIVIDE.

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

Format 1.

DIVIDE dataname 1 INTO dataname 2.DIVIDE literal 1 INTO dataname 2.

The value of dataname 1 or literal 1 is divided into the value of dataname 2; the quotient then is placed in dataname 2.

Example 1.

DIVIDE 10 INTO W10-TOTAL.

Format 2.

DIVIDE dataname1 BY dataname 2 GIVING dataname 3.DIVIDE literal 1 INTO literal 2 GIVING dataname 3.

The value of dataname 1 or literal 1 is divided into/by the value of dataname 2 or literal 2. The value of the quotient is stored in each data item referenced by dataname 3.

Example 2.

DIVIDE TR-PREMIUM BY 100 GIVING W20-RATE. DIVIDE 100 INTO TR-PREMIUM GIVING W20-RATE.

Given that the contents of TR-PREMIUM are the same for both statements the contents of W20-RATE will be the same after execution of both statements.

Format 3.

DIVIDE dataname 1 BY dataname 2 GIVING dataname 3REMAINDER dataname 4.

DIVIDE literal 1 INTO literal 2 GIVING dataname 3 REMAINDER dataname 4.

The value of dataname 1 or literal 1 is divided into/by dataname 2 or literal 2. The value of the quotient is stored in dataname 3, and the value of the remainder is stored in dataname 4.

IT TRAINING 56

Page 57: COBOL

COBOL Programming Last Printed: 08/04/23

29. Conditions.

29.1. IF ... ELSE.

Purpose: without the ELSE, the IF statement causes the imperative statements, up to the END-IF statement following the condition to be actioned if the condition is true. When ELSE is incorporated, the statements between the condition and ELSE are actioned if the condition is true. Those following the ELSE and up to the full stop are actioned if the condition is false.

Format.

IF conditionimperative statement(s)

ELSE imperative statement(s)

END-IF.

Example.

IF TR-DEB-CRED-IND = 'D' MULTIPLY TR-PREMIUM BY -1 GIVING W20-AMOUNT ELSE MOVE TR-PREMIUM TO W20-AMOUNT END-IF.

NB. Only one full stop. The ELSE is on a line by itself. The imperative statements should be lined up. There should not be too many imperative statements.

29.2. IF ... AND.

When conditions are joined by AND both conditions have to be true for the statement following to be actioned.

Example.

IF TR-RISK = 44 AND TR-CLASS = 52 MOVE 'BURGLARY' TO W20-TYPE END-IF.

IT TRAINING 57

Page 58: COBOL

COBOL Programming Last Printed: 08/04/23

29.3. IF ... OR.

When conditions are joined by OR only one condition needs to be true for the following statement(s) to be actioned.

Example.

IF TR-RISK = 30 OR TR-RISK = 40 MOVE 'HOUSEHOLD' TO W30-RISK END-IF.

In both conditions the AND/OR is written in column 19 with the second condition following it on the same line. The imperative statement(s) start in column 26 on subsequent lines (i.e. indented by six spaces).

29.4. IF....NOT.

NOT's can be incorporated in compound IF conditions.

Example.

IF TR-CLASS NOT = 30 AND TR-POL-DEPT = W20-POL-DEPT MOVE TR-POL-NO TO W20-POLICY END-IF.

Using NOT and OR in the same IF statement is not good practice, see example below.

Example.

IF TR-CLASS NOT = 30 OR TR-CLASS NOT = 31 MOVE TR-POL-NO TO W20-POLICY END-IF.

If TR-CLASS is 31 the first condition is satisfied (i.e. the condition is true) and the statement following the IF will be obeyed. If TR-CLASS is 30 the second condition is satisfied and the statement(s) following the IF will be obeyed, i.e. this condition will always be true and the code is equivalent to:

MOVE TR-POL-NO TO W20-POLICY.

IT TRAINING 58

Page 59: COBOL

COBOL Programming Last Printed: 08/04/23

29.5. IF - Testing Field Contents.

Purpose: to test a numeric field, dataname must be a numeric field. Positive means greater than zero, negative means less than zero. If a field is unsigned it will be treated as positive.

Format.

IF dataname NEGATIVE POSITIVE ZERO

imperative statement END-IF.

Purpose: to test a field to see if it is numeric without causing the program to abend, if the data does not conform to its picture. Can be used with PIC X, 9 or PACKED-DECIMAL. Format.

IF dataname NUMERIC imperative statement

END-IF.

NB.A PIC X field will be treated as numeric if it contains digits (i.e.0-9).

Purpose: To see if a field contains only A to Z or space. Can only be used with PIC X fields.

Format.

IF dataname ALPHABETIC imperative statement

END-IF.

NB.All of these conditions can be negated by included the NOT phrase.

IT TRAINING 59

Page 60: COBOL

COBOL Programming Last Printed: 08/04/23

30. COMPUTE.

Purpose: The COMPUTE statement combines together the ADD, MULTIPLY, DIVIDE and SUBTRACT verbs. Special symbols are used to represent these verbs. Thus these operands can be combined in one statement.

Format.

COMPUTE dataname 1 = arithmetic expression.

The arithmetic expression is evaluated and the answer is put in the dataname(s) following the COMPUTE. This can be ROUNDED. ON SIZE ERROR can also be used, both work in the same manner as with the arithmetic verbs.

Symbols. + ADD - SUBTRACT* MULTIPLY / DIVIDE** EXPONENTIATION

Examples.

COMPUTE W10-TOTAL = (TR-PREMIUM + TR-BONUS) / TR-RATE.

COMPUTE W40-RESULT = (W20-INT**2 + W10-AMOUNT) * 4 - W20-DEDUCT.

COMPUTE W40-RESULT ROUNDED = (TR-PREMIUM * 7.41) + W70-BONUS.

The expression is evaluated following the normal parenthesis for arithmetic expressions:

1. Expressions within brackets2. Unary operator i.e. multiply by +1 or -13. Exponentiation4. Multiplication and Division5. Addition and Subtraction

30.1. IF and Arithmetic Expressions.

Arithmetic expressions containing the symbols used in COMPUTE statements can be used in IF statements. Do not make expressions complicated.

Example.

IF W10-PREMIUM > W40-COMMISSION + 20.4 PERFORM S20-CHECK-COMMISSION END-IF.

IF W10-PREMIUM / W20-RATE NOT > TR-PREMIUM X .75 PERFORM S30-CHECK-PREMIUM END-IF.

IT TRAINING 60

Page 61: COBOL

COBOL Programming Last Printed: 08/04/23

31. EVALUATE .

Purpose: The EVALUATE verb is very useful for coding 'case statements'. It provides a clearer, simpler, alternative, to a series of repeated IF statements, or nested IF statements. Also GO TO commands become unnecessary.

Example.

WORKING-STORAGE SECTION. 01 W10-WORKFIELDS. 03 W10-AGE PIC 9(3). 03 W10-SEX PIC X. 03 W10-DETAILS PIC X(20).

.... PROCEDURE DIVISION. .... EVALUATE W10-AGE ALSO W10-SEX WHEN 0 THROUGH 12 ALSO 'F' MOVE 'FEMALE CHILD' TO W10-DETAILS WHEN 0 THROUGH 12 ALSO 'M' MOVE 'MALE CHILD' TO W10-DETAILS WHEN 13 THROUGH 19 ALSO 'F' MOVE 'FEMALE TEENAGER' TO W10-DETAILS WHEN 13 THROUGH 19 ALSO 'M' MOVE 'MALE TEENAGER' TO W10-DETAILS WHEN 20 ALSO 'F' MOVE 'FEMALE 20 YRS' TO W10-DETAILS WHEN 20 ALSO 'M' MOVE 'MALE 20 YRS' TO W10-DETAILS WHEN 21 THROUGH 99 ALSO 'F' MOVE 'FEMALE ADULT' TO W10-DETAILS WHEN 21 THROUGH 99 ALSO 'M' MOVE 'MALE ADULT' TO W10-DETAILS WHEN OTHER MOVE 'VERY OLD PERSON' TO W10-DETAILS END-EVALUATE.

In the EVALUATE statement, expressions to be tested are called selection-subjects. In the example above, W50-AGE and W50-SEX are the selection-subjects. The reserved word ALSO separates the selection subjects. The answer selected is called a selection-object. When evaluated each pair of selection-subjects and selection-objects must belong to the same class (numeric, character, CONDITION TRUE or FALSE or ANY).

In the example, W50-AGE is a numeric field, so the selection object is also numeric (e.g. 13), and W50-SEX is an alphanumeric field, so the selection object is also an alphanumeric (e.g. 'F'). If WHEN OTHER is coded, the statement following it will be executed if none of the preceding conditions have been true.

You can specify up to 255 evaluate subjects and objects in an EVALUATE statement. There is no limit to the number of WHEN clauses that can be specified in an EVALUATE statement, but one page is a practical limit to observe.

The WHEN phrase will be indented by 3 spaces. Statements following a when will be indented by 6 spaces.

The first WHEN condition is examined; if this condition is satisfied, the processing actions associated with this phrase are selected.

IT TRAINING 61

Page 62: COBOL

COBOL Programming Last Printed: 08/04/23

The execution of the EVALUATE statement ends when:

The statements associated with the selected WHEN phrase are executed The statements associated with the WHEN OTHER phrase are executed No WHEN conditions are satisfied

Because the WHEN phrases are tested in the order in which they are coded, you should order these phrases with optimum performance in mind, i.e. code the WHEN phrase containing selection-objects most likely to be satisfied first, the other WHEN phrases coded in descending order of probability of satisfaction. The WHEN OTHER phrase must be coded last.

There will be no in-line PERFORM or nested IF statements within EVALUATE statements.

IT TRAINING 62

Page 63: COBOL

COBOL Programming Last Printed: 08/04/23

32. Numeric fields .

32.1. PACKED-DECIMAL.

Recall from data representation that a packed decimal field is one where the number is stored as two digits to a byte. Apart from the rightmost byte which contains the least significant digit and the sign in the last 4 bits of this byte.

A three byte field containing +12345 will be held thus:

binary: 0001 0010 0011 0100 0101 1100hex: 1 2 3 4 5 C

Format.

PIC S9(n) PACKED-DECIMAL.

NB. PACKED-DECIMAL in column 55 indicates the field is packed decimal. n is the number of digits in the field. n can be in the range 1 to 18. n should always be odd to utilise all the space as a packed decimal is an exact number of

bytes. The exception to 4 above is the maximum size of packed decimal field which is PIC

S9(18) PACKED-DECIMAL (ANSI standard). Packed decimal fields should always be signed. In older programs expect to see COMP-3 rather than PACKED-DECIMAL as this was

used in OS/VS COBOL

32.1.1. Decimal point in a packed decimal field.

V is used to denote a decimal point as in a zoned decimal field

Example.

PIC S9(5)V99 PACKED-DECIMAL.

This will contain a maximum of 7 digits and has 2 decimal places.

32.1.2. Length of a packed decimal field.

The length of a packed decimal field is (n+1)/2 bytes, where n is the total number of digits.

Example.

PIC S9(9) PACKED-DECIMAL is a 5 byte field (9+1)/2 = 5

PIC S9(5)V99 PACKED-DECIMAL is a 4 byte field (7+1)/2 = 4

IT TRAINING 63

Page 64: COBOL

COBOL Programming Last Printed: 08/04/23

32.2. BINARY.

Format.

PIC S9(n) BINARY

n is either 4, 9 or 18 and represents the total number of digits the field should hold. BINARY in column 55 indicates the field is binary. Binary fields should always be signed.

32.2.1. Binary Fields and Length.

A PIC S9(4) BINARY will hold a maximum of 9999 and will occupy 2 bytes. A PIC S9(9) BINARY will hold a maximum of 999,999,999 and will occupy 4 bytes. A PIC S9(18) BINARY will hold a maximum of 18 9's and will occupy 8 bytes. Binary fields in COBOL can only be one of these 3 lengths, if n is not 4, 9 or 18 the

number is rounded up to give a field 2, 4 or 8 bytes long. Binary fields larger than PIC S9(9) BINARY are inefficient, (a special routine has to

be invoked to use them) and only should be used when necessary.

NB.It is possible to store a number greater than 9999 in a 2 byte and a number greater than 999,999,999 in a 4 byte field, but this should not be done. If the number is bigger use the next size field. Problems can occur when comparing a PIC S9(9) BINARY and a PIC S9(18) BINARY where the PIC S9(9) BINARY contains a number greater than 999,999,999.In older programs expect to see COMP rather than binary as this was used in OS/VS COBOL.

32.2.2. Decimal point in a binary field.

Like zoned decimal and packed decimal fields a decimal point in a binary field is represented by a V.

Example.

PIC S9(5)V9(4) BINARY.

This is a 4 byte binary field (9 digit) and has 4 decimal places.

IT TRAINING 64

Page 65: COBOL

COBOL Programming Last Printed: 08/04/23

32.3. Choice of numeric fields.

32.3.1. Zoned decimal.

Used to define numeric fields where one number is held in one byte. Typically used for print fields or fields on screens.The computer has to convert zoned decimal fields to use in arithmetic operations.

32.3.2. Packed decimal.

Used for all arithmetic fields except subscripts, as they do not have to be converted for arithmetic, can be easily understood in hex prints. They must always be defined as an odd number of numeric digits and be signed.

32.3.3. Binary.

Used for arithmetic fields and subscripting (explained later in this course), but inefficient if larger than 9 digits or 4 bytes.

IT TRAINING 65

Page 66: COBOL

COBOL Programming Last Printed: 08/04/23

33. File Handling .

33.1. Implicit RedefinitionRedefinition allows you to use different data description entries to describe the same computer storage area.

NB.Fixed length records only.

A file can have any number of record descriptions. Each record description is described by an 01 level. Each record will have its own fields but at least one field will be common to all types of record. This field will indicate which record type the record is, and it will be in the same position in all records, normally at the beginning.

When the records are fixed length the record descriptions apply to the same length input area and if any fields are in the same position in one or more records they need only be named once.

Example.

Record 1 consists of:Type 1 byte zoned decimalName 20 byte alphanumericAddress 40 byte alphanumericBank code 9 byte zoned decimal

Record 2 consists of:Type 1 byte zoned decimalSalary 6 byte zoned decimalJob 10 byte alphanumericTax 4 byte zoned decimalDescription 40 byte alphanumericDeduction code 9 byte zoned decimal

In this example type is the 'key' field and since it is in the same position (i.e. the first byte) in both record descriptions it need only be named once.

A file definition could be:

FD TR-STAFF-FILE BLOCK 0 RECORDING F.

01 TR-STAFF-REC1. 03 TR-TYPE1 PIC 9. 03 TR-NAME PIC X(20). 03 TR-ADDRESS PIC X(40). 03 TR-BANK-CODE PIC 9(9). 01 TR-STAFF-REC2. 03 TR-TYPE2 PIC 9. 03 TR-SALARY PIC 9(6). 03 TR-JOB PIC X(10). 03 TR-TAX PIC 9(4). 03 TR-DESC PIC X(40). 03 TR-DED-CODE PIC 9(9).

IT TRAINING 66

Page 67: COBOL

COBOL Programming Last Printed: 08/04/23

Remember record descriptions tell the computer a field's position relative to the start of the record and the field type.

Multiple record descriptions are really telling the computer to interpret the data in a particular way. Thus in our example when TR-NAME is accessed the computer will take bytes 2-21 of the record area and treat it as alphanumeric. Whilst if TR-SALARY is referenced bytes 2-7 are accessed and are treated as zoned decimal.

So you can see why it is necessary to decide which record you have prior to processing, i.e. if record type 1 was the last record read with a name of WATSON, and TR-SALARY was referenced, the contents of bytes 2-7 would be WATSON followed by one trailing space, not a valid salary amount!

As both TR-TYPE fields are the same length and refer to the same byte, it is common practice to only name one field and have FILLER for the second. It would be possible to use a FILLER for the second of the code fields (TR-DED-CODE) as this field is in the same position and is the same length as TR-BANK-CODE, although this could lead to maintenance problems.

Thus a revised record descriptions could be:

01 TR-STAFF-REC1. 03 TR-TYPE PIC 9. 03 TR-NAME PIC X(20). 03 TR-ADDRESS PIC X(40). 03 TR-CODE PIC 9(9). 01 TR-STAFF-REC2. 03 FILLER PIC X. 03 TR-SALARY PIC 9(6). 03 TR-JOB PIC X(10). 03 TR-TAX PIC 9(4). 03 TR-DESC PIC X(40). 03 FILLER PIC X(9).

IT TRAINING 67

Page 68: COBOL

COBOL Programming Last Printed: 08/04/23

34. Variable Length Records .

In previous topics we have been using files containing fixed length records. In practice some files contain records which vary in length. This may be because the file contains several different record descriptions, which are different lengths or it could be one record description which varies in length (see OCCURS DEPENDING later in this course).

Variable length records have a 4 byte field in front of the first data field which contains the length of the record. This is called the record descriptor word or RDW. The system uses this field to decide how many bytes of the record can be made available to your program. This field is created by the system not by your program when a record is written. It can not be accessed by your program and does not have to be described in the DATA DIVISION.

Files containing variable length records, have RECORDING V in the FD.

Example. FD TR-CLIENT-FILE BLOCK 0 RECORDING V. .... 01 TR-CLIENT-REC-1. 03 TR-NUMBER PIC S9(5) PACKED-DECIMAL. 03 TR-TYPE PIC 9. 03 TR-FIRST-NAME PIC X(32). 03 TR-SECOND-NAME PIC X(32). 01 TR-CLIENT-REC-2. 03 FILLER PIC X(4). 03 TR-ADDRESS-1 PIC X(32). 03 TR-ADDRESS-2 PIC X(32). 03 TR-ADDRESS-3 PIC X(32). 03 TR-POST-CODE PIC X(8).

FILLER is used in the second description as TR-NUMBER and TR-TYPE are common to both descriptions.

TR-CLIENT-REC-1 is 68 bytes long and TR-CLIENT-REC-2 is 108 bytes.

TR-TYPE has to be accessed to decide which record type has been read. If a record type 1 had just been read and TR-POSTCODE was accessed, the contents would be indeterminate, you would be trying to access bytes 100-108 when the record read was only 68 bytes long.

When using READ ... INTO with variable records the area following the INTO must be large enough to hold the maximum record length, otherwise records may be truncated.

When writing variable length records to as file, the correct record name must be in the WRITE statement, so a record of the correct length will be written. Given the above file description, if TR-CLIENT-REC-2 had been constructed but then the statement:

WRITE TR-CLIENT-REC-1.

was executed later in the program logic a record 68 bytes long would be written not 108 bytes.

Remember the system will automatically put the Record Descriptor Word on the front of the record when it is written.

IT TRAINING 68

Page 69: COBOL

COBOL Programming Last Printed: 08/04/23

35. REDEFINES .

We have already seen that we have implicit redefinition at 01 levels i.e. record level in the FILE SECTION, this is because records within a given file are automatically redefined. In such 01 level entries, the REDEFINES clause must not be specified.

If we wish to redefine an area of storage outside the FILE SECTION we use the REDEFINES clause. The REDEFINES clause allows you to use different data description entries to describe the same computer storage area.

Format:

level no dataname 1 REDEFINES dataname 2

Thus the area of store allocated to dataname 1 will be the same as that allocated to dataname 2. The level numbers of the datanames must be the same and consecutive at that level, dataname 2 must appear first. Dataname 1 can be a FILLER field.

Redefinition begins at dataname 1 and ends when a level number less than or equal to that of data-name-1 is encountered. No entry having a level number numerically lower than those of dataname 1 and dataname 2 may occur between these entries.

Example:

A field that is 6 bytes long is alphanumeric if an indicator field has the value 2 and numeric if the indicator field has the value 3.

03 TR-ALPHA-BRANCH PIC X(6). 03 TR-NUMERIC-BRANCH REDEFINES TR-ALPHA-BRANCH PIC 9(6).

The data description entry for dataname 2, the redefined item, can contain a REDEFINES clause.

REDEFINES is coded in column 41. If a picture is coded for the dataname then it should be coded in column 41 of the next line.

Multiple redefinitions must all use the data-name of the original entry that defined this storage area.

Example:

03 TR-MOTOR. 05 TR-CAR-NO PIC X(7). 05 TR-AREA PIC S9(7) PACKED-DECIMAL. 03 TR-FIRE REDEFINES TR-MOTOR. 05 TR-CLASS PIC X(4). 05 TR-SUM-INSURED PIC S9(13) PACKED-DECIMAL. 03 TR-LIVESTOCK REDEFINES TR-MOTOR. 05 TR-ANIMAL-CODE PIC S9(5) PACKED-DECIMAL. 05 FILLER PIC X(8).

Each level can be sub divided, if one level is a group the next can be a group or elementary item. Dataname 1 and dataname 2 should be the same length, unless they are 01 levels, then the lengths may differ. In the above example TR-LIVESTOCK has an 8 byte FILLER to make this so.

IT TRAINING 69

Page 70: COBOL

COBOL Programming Last Printed: 08/04/23

This facility is used extensively for files containing records concerning different classes of insurance. The details peculiar to each class are held in the last bytes of the record, these bytes have a different description for each type of insurance.

NB.The data description entry for the redefined item cannot contain an OCCURS clause with or without the DEPENDING ON option. However, the redefined item may be subordinate to an item whose data description entry contains an OCCURS clause. In this case, the reference to the redefined item in the REDEFINES clause must not be subscripted. Neither the original definition nor the redefinition can include a variable occurrence data item. Neither the redefined item nor the redefining item, or any items subordinate to them, can contain an OCCURS DEPENDING ON clause. The redefining entry (identified by dataname 1), and any subordinate entries, must not contain any VALUE clauses.

35.1. Further Examples.

The REDEFINES clause may be specified for an item within the scope of an area being redefined (that is, an item subordinate to a redefined item).

03 W10-REGULAR-EMP. 05 W10-LOCATION PIC X(8). 05 W10-GRADE PIC X(4). 05 W10-SEMI-MONTH-PAY PIC 9(4)V99. 05 W10-WEEKLY-PAY REDEFINES W10-SEMI-MONTH-PAY PIC 999V999.

03 W10-TEMP-EMPLOYEE REDEFINES W10-REGULAR-EMP. 05 W10-LOCATION PIC X(8). 05 W10-FILLER PIC X(6). 05 W10-HOURLY-PAY PIC 99V99.

The REDEFINES clause may also be specified for an item subordinate to a redefining item.

* 03 W20-REGULAR-EMP. 05 W20-LOCATION PIC X(8). 05 W20-GRADE PIC X(4). 05 W20-SEMI-MONTH-PAY PIC 999V999.* 03 W20-TEMP-EMPLOYEE REDEFINES W20-REGULAR-EMP. 05 W20-LOCATION PIC X(8). 05 FILLER PIC X(6). 05 W20-HOURLY-PAY PIC 99V99. 05 W20-CODE-H REDEFINES W20-HOURLY-PAY PIC 9(4).

IT TRAINING 70

Page 71: COBOL

COBOL Programming Last Printed: 08/04/23

36. OCCURS , SUBSCRIPTS and TABLES .

We have seen that data is described in the data division and that each elementary field is given a picture.

If we wished to describe 4 date fields we might code this:

01 W20-WORKFIELDS. 03 W20-DATE1 PIC X(8). 03 W20-DATE2 PIC X(8). 03 W20-DATE3 PIC X(8). 03 W20-DATE4 PIC X(8).

W20-WORKFIELDS is 32 bytes long. Each elementary field has a different name and each has a picture.

There is an alternative way to write this using the OCCURS statement.

One of the Data Division clauses used for table handling is the OCCURS clause. The OCCURS clause specifies tables whose elements can be referred to by indexing or subscripting. It eliminates the need for separate entries for repeated data items.

Format.

level no dataname picture OCCURS n

Example.

01 W20-WORKFIELDS. 03 W20-DATE PIC X(8) OCCURS 4.

W20-WORKFIELDS is still 32 bytes long and the 4 occurrences of W20-DATE are held next to each other in store. OCCURS is coded in column 41.

This is a one dimensional table.

To refer to a dataname in COBOL it must be unique. Therefore we have to distinguish between the 4 occurrences of W20-DATE. To do this we use a subscript. The subscript is put in brackets following the dataname.

Format.

dataname (subscript)

Subscript can be either a numeric literal between 1 and the number of OCCURS, or a dataname containing a whole number in that range.

To reference an occurrence of W20-DATE we could code

W20-DATE(3) or W20-DATE(W20-SUB)

IT TRAINING 71

Page 72: COBOL

COBOL Programming Last Printed: 08/04/23

NB. OCCURS cannot be used at a 01 level. Cannot have a VALUE clause with OCCURS. A subscript should be preferably 2 byte binary field. A subscript cannot itself be subscripted.

This is the simplest form of OCCURS. The field that occurs can itself be subdivided. There can be up to 3 levels of OCCURS (also called a three dimensional table). Normally we only use 2 levels.

Example.

01 TR-ITEMS. 03 TR-GROUP OCCURS 3. 05 TR-PART PIC 99. 05 TR-NAME PIC X(10).

This could be expressed diagrammatically thus:

TR-ITEMSTR-GROUP(1) TR-GROUP(2) TR-GROUP(3)

TR-PART(1) TR-NAME(1) TR-PART(2) TR-NAME(2) TR-PART(3) TR-NAME(3)

Example.

Two levels of OCCURS:

03 W20-MONTH OCCURS 12. 05 W20-WEEK PIC X(7) OCCURS 4.

To reference the third week of the seventh month can have either.

W20-WEEK (7 3) or W20-WEEK (W20-MTH-SUB W20-WK-SUB)

where W20-MTH-SUB would contain 7 and W20-WK-SUB would contain 3.

NB. The subscript of the highest level comes first i.e. of W20-MONTH in the above example. The subscripts are separated by a space.

We can combine OCCURS and REDEFINES to hold tables of information. For example branches are numbered, but invariably the name of the branch needs to be printed not the number. One solution is to have successive IF statements or an EVALUATE.

IT TRAINING 72

Page 73: COBOL

COBOL Programming Last Printed: 08/04/23

Example.

EitherIF TR-BRANCH = 1

MOVE 'NORWICH' TO W20-BRANCH ELSE IF TR-BRANCH = 2 MOVE 'IPSWICH' TO W20-BRANCH ELSE

MOVE 'EDINBURGH' TO W20-BRANCHEND-IF

END-IF.or

EVALUATE TR-BRANCHWHEN 1

MOVE 'NORWICH' TO W20-BRANCH WHEN 2 MOVE 'IPSWICH' TO W20-BRANCH WHEN OTHER MOVE 'EDINBURGH' TO W20-BRANCH END-EVALUATE.

Instead we can code as the following working storage:-

03 W20-BRANCH-LIST.05 FILLER PIC X(9) VALUE ‘NORWICH’.05 FILLER PIC X(9) VALUE ‘IPSWICH’.05 FILLER PIC X(9) VALUE ‘EDINBURGH’.

03 W20-BRANCH-ARRAY REDEFINES W20-BRANCH-LIST. 05 W20-BRANCH-NAME PIC X(9) OCCURS 3.

Then one move statement is needed

MOVE W20-BRANCH-NAME(TR-BRANCH) TO W20-BRANCH.

where TR-BRANCH contains a number in the range one to three.NB.

The field must be as long as the longest name. The shorter names will have trailing spaces.

Instead of FILLER. we could have W20-BR1, W20-BR2 etc. Names are sometimes better as it can be easier if the name and its occurrence number are linked. However FILLER is often the preferred method, as the VALUE defines the link.

36.1. Further Considerations.

An alternative and normally more efficient way of handling tables is by INDEXING, explained later in this course.

IT TRAINING 73

Page 74: COBOL

COBOL Programming Last Printed: 08/04/23

37. OCCURS DEPENDING ON .

One way to have variable length records is to have a separate 01 entry for each possible length of record. Another way is to use the OCCURS DEPENDING ON clause, this allows a single 01 level entry to represent a range of record lengths. This may appear in a unique record description or in one or several of a set of 01 levels in the same file. The OCCURS DEPENDING ON clause can be used in record descriptions and in the Working Storage section.

Format.

level dataname 1 OCCURS integer 1 TO integer 2 (TIMES)DEPENDING ON dataname 2

NB. Integer 1 gives the minimum number of occurrences. Integer 2 gives the maximum number of occurrences. Dataname 1 is the subject of the OCCURS DEPENDING ON clause. Dataname 2 is the object of the clause. Dataname 2 will usually be in the fixed part of the

same record description (it can not be in the variable portion) sometimes it will be in a WORKING-STORAGE field.

If dataname 2 is a working storage field it should be a binary field.

Consider a file containing motor records. Each motor record can insure up to 4 cars. In this file 60% of the records have details of one car, 20% of the records have details of two cars, 15% have three cars and 5% of records insure four cars.

If the record was a constant length then each record would need space for four cars and if the file contained half a million records a lot of space would be unused and therefore wasted. Thus if each record only contained the bytes it used this problem would be overcome. There could be a separate 01 for record description for each length but it is better to use the OCCURS DEPENDING ON clause.

Example.

03 TR-CAR-COUNT PIC S9 BINARY. 03 TR-CAR-DETAILS OCCURS 0 TO 4 DEPENDING ON TR-CAR-COUNT. 05 TR-MAKE PIC X(20). 05 TR-CAR-REG PIC X(7).

The length of the subject item (i.e. TR-CAR-DETAILS) is fixed. It is the number of the occurrences that varies (from zero to four in this example). The object of the OCCURS DEPENDING ON (i.e. TR-CAR-COUNT) must contain a positive whole number. The contents of this field will determine how long the record is (i.e. TR-CAR-COUNT contains the number of occurrences of TR-CAR-DETAILS).

Any statement which uses a piece of data containing an OCCURS DEPENDING ON clause will take note of the value in the object and act upon that variably sized piece of data. In the above example if TR-COUNT contains 3 there will be 81 bytes of data available.

NB.You should not attempt to access items whose occurrence number exceeds the value of the object. When the value of the object is reduced, the contents of the items whose occurrence number exceeds the new value are unpredictable. In the above example if TR-CAR-COUNT is 3 you should not try to access TR-CAR-DETAILS(4).

IT TRAINING 74

Page 75: COBOL

COBOL Programming Last Printed: 08/04/23

37.1. Length Calculation.

The length is calculated when a record is read and when the object of the OCCURS DEPENDING ON is changed as a result of a MOVE (or arithmetic function) to it or a move to a group that contains it. Thus a move to TR-CAR-COUNT will cause the length to be recalculated but a move to TR-CAR-DETAILS(4) will not.

It is important to understand when the system takes note of changes in length.

Example.

A program contains:

FD TR-MAIN-FILE BLOCK 0 RECORDING MODE V. .... 01 TR-MAIN-REC. 03 TR-COUNT PIC S9(3) PACKED-DECIMAL. 03 TR-DETAILS. 05 TR-ITEM PIC X OCCURS ZERO TO 10 DEPENDING ON TR-COUNT. .... WORKING-STORAGE SECTION. .... 01 W10-GROUP. 03 W10-COUNT PIC S9(4) BINARY. 03 W10-DETAILS. 05 W10-ITEM PIC X OCCURS ZERO TO 5.

The code is:

MOVE 5 TO W10-COUNT. MOVE 'ABCDE' TO W10-DETAILS. MOVE 5 TO TR-COUNT.

NB. length of TR-MAIN-REC is now 7 bytes. the first of the five occurrences of W10-ITEM contains 'A', the second 'B', etc.

MOVE 12345 TO TR-DETAILS. MOVE 2 TO TR-COUNT.

NB.length of TR-MAIN-REC is recalculated as 4 bytes and occurrences 3, 4 and 5 should not accessed.

MOVE W10-GROUP TO TR-MAIN-REC. MOVE 5 TO TR-COUNT.

IT TRAINING 75

Page 76: COBOL

COBOL Programming Last Printed: 08/04/23

NB. moves AB to the first two occurrences of TR-ITEM as the length of TR-MAIN-REC is

only 4 bytes. as 5 has been moved to TR-COUNT (this is the object of the OCCURS DEPENDING

ON) the length of TR-MAIN-REC is now recalculated to 7 bytes.

DISPLAY TR-DETAILS.

would display AB345

In order to ensure the system knows the correct length before any move always move to the object of the OCCURS DEPENDING ON first, thus establishing the length. Then move the record or group, e.g.

MOVE W10-COUNT TO TR-COUNT. MOVE W10-GROUP TO TR-MAIN-REC.

37.2. Further Considerations. Never attempt to change the length of an input record in the FD (i.e. in the input

buffer). Before a record is written always set the object of the OCCURS in the output FD to its

correct value. It is possible to have more than one OCCURS DEPENDING ON clause in the same

record description. These need to be accessed very carefully and should be avoided if possible.

Example.

01 W10-GROUP. 03 W10-COUNT1 PIC S9(4) BINARY. 03 W10-COUNT2 PIC S9(4) BINARY. 03 W10-LINE1 OCCURS ZERO TO 12 DEPENDING ON W10-COUNT1. 05 W10-ITEMS1 PIC X(15). 03 W10-LINE2 OCCURS ZERO TO 10 DEPENDING ON W10-COUNT2. 05 W10-ITEMS2 PIC X(20).

Before W10-LINE1 can be changed W10-LINE2 has to be moved. W10-LINE1 can the be amended and W10-LINE2 moved back.

IT TRAINING 76

Page 77: COBOL

COBOL Programming Last Printed: 08/04/23

38. APPLY WRITE ONLY .

NB.APPLY WRITE-ONLY is applicable only to variable length records.

Normally as data is transferred to a record description and records are written, a buffer the size of the maximum block size is gradually filled. After each WRITE the amount of space left in the buffer is checked. If this space is too small to contain the largest record specified in the FD the block is truncated and transferred to secondary storage e.g. disk or tape and a new block begun. This may mean wasted space and hence more input/output activity. Thus if the maximum record length is 4000 bytes and the average record is 1000 bytes, 3000 bytes could be wasted at the end of each block.

APPLY WRITE-ONLY can be used to minimise wasted space. Using APPLY WRITE-ONLY records are built up away from the output record area (e.g. in WORKING-STORAGE) and output using 'WRITE....FROM'. At write time APPLY WRITE-ONLY causes the system to check to see if the current record length will fit in the buffer instead of using the maximum record length. If there is not sufficient space the block is truncated and transferred to secondary storage and a new block started, otherwise data is transferred to the output buffer.

The clause is contained in a paragraph called I-O-CONTROL in the CONFIGURATION SECTION starting in column 8. This paragraph follows the SELECT .... ASSIGN statement(s).

Format.

I-O-CONTROL. APPLY WRITE-ONLY filename.

starting in column 12

NB. The file must be opened for output. The WRITE statement for this filename must be in the form: WRITE recordname FROM

identifier None of the datanames defined under the output FD can be referenced in the

PROCEDURE DIVISION.

If this file contains a DEPENDING ON clause, the object of this DEPENDING ON clause must be outside the record area. You will recall that before a record containing an OCCURS DEPENDING ON clause is written, it is necessary to move that correct value to the object of the OCCURS DEPENDING ON clause. If the object is part of the record description we would contravene rule 3 above. Therefore if the object of the OCCURS DEPENDING clause is a WORKING STORAGE field, when the value of that field is amended the length of the output record will be correctly calculated.

IT TRAINING 77

Page 78: COBOL

COBOL Programming Last Printed: 08/04/23

39. PERFORM VARYING .

By updating a subscript it is possible to access items held in a table, that is, subordinate to an OCCURS statement. One method is to add or subtract a value from a subscript, then test to ascertain whether the requisite number of records have been processed.

Example.

MOVE 1 TO W50-SUB. P40-20. MOVE ZERO TO W50-TOTAL(W50-SUB). ADD 1 TO W50-SUB. IF W50-SUB < 11 GO TO P40-20 END-IF.

This would process 10 occurrences of S50-TOTALS, but includes a backward GO TO statement. Instead we could have coded the following:

PERFORM S60-ZEROISE VARYING W40-SUB FROM 1 BY 1 UNTIL W40-SUB > 10. .... S60-ZEROISE SECTION. .... MOVE ZERO TO W40-TOTAL(W40-SUB). P60-EXIT. EXIT.

NOTE – when using PERFORM – VARYING – the subscript to be varied is incremented BEFORE the UNTIL condition is tested. This can cause problems where a ZERO iteration may be encountered – the subscript will always be incremented to the first value.

IT TRAINING 78

Page 79: COBOL

COBOL Programming Last Printed: 08/04/23

40. STRING .

Purpose: the STRING statement strings together the partial or complete contents of two or more data items or literals into one single data item. One STRING statement can be written instead of a series of MOVE statements.

Format.

STRING dataname 1DELIMITED BY dataname 2

INTO dataname 3.

STRING literal 1DELIMITED BY literal 2

INTO dataname 3.

STRING identifier 1DELIMITED BY SIZE

INTO dataname 3.

Example 1.

03 P-REP1-H5-DATE PIC X(8). .... 03 W20-ACCEPTED-DATE. 05 W20-YEAR PIC 99. 05 W20-MTH PIC 99. 05 W20-DAY PIC 99. .... PROCEDURE DIVISION. .... STRING W20-DAY '/' W20-MTH '/' W20-YEAR DELIMITED BY SIZE INTO P-REP1-H5-DATE.

This code 'converts' a date in the format YYMMDD to a format of DD/MM/YY.

Example 2.

STRING W40-FIELD1 W40-FIELD2 W40-FIELD3 DELIMITED BY '*' INTO W80-RESULT.

This would take the contents of W40-FIELD1 up to an * in this field and copy them to W80-RESULT (if no * present the complete field would be moved.) This is then repeated with W40-FIELD2 and W40-FIELD3. If the receiving field is filled before all the data is transferred the operation stops. If the receiving field is only partially filled trailing spaces are not added. If a dataname is used in the delimited statement, it contains the delimiting character(s). The fields used in a STRING statement should be zoned decimal or alphanumeric.

IT TRAINING 79

Page 80: COBOL

COBOL Programming Last Printed: 08/04/23

40.1. Further Considerations.

A pointer can be used to control the placement of data in the receiving field. A string overflow statement can be added to determine when the receiving field is full.

Example.

STRING W20-DAY '/' W20-MTH '/' W20-YEAR DELIMITED BY SIZE INTO TR-DATE-OUT OVERFLOW PERFORM S30-OVERFLOW END-STRING.

41. UNSTRING .

Purpose: the UNSTRING statement causes contiguous data in a sending field to be separated and placed into multiple receiving fields. One UNSTRING statement can be written instead of a series of MOVE statements.

Format.

UNSTRING dataname1 DELIMITED BY dataname2INTO dataname3

UNSTRING dataname1 DELIMITED BY literal 1 INTO dataname3

Example.

03 W40-INPUT PIC X(30). 03 W40-ACCOUNT PIC X(6). 03 W40-NAME PIC X(20). 03 W40-INITIALS PIC X(4).

If W40-INPUT contains 1235A*BROWN*JKS, the following instruction:

UNSTRING W40-INPUT DELIMITED BY '*' INTO W40-ACCOUNT W40-NAME W40-INITIALS would result in:

W40-ACCOUNT containing 1235A W40-NAME containing BROWN W40-INITIALS containing JKS

41.1. Further Considerations.

It is possible to count the number of characters transferred into a field. Using the POINTER phrase different starting points can be used. It is possible to specify that several continuous occurrences of a delimiter can be treated

as one. The TALLYING option will count the number of 'target' fields.

IT TRAINING 80

Page 81: COBOL

COBOL Programming Last Printed: 08/04/23

42. NORWICH UNION DATES .

Dates are very important in the Insurance business. For example, we have to store the following:

Dates of birth Date of policy or renewal Date of endorsement (alteration) Date of payment Date of accident

What we need is a formula for storing dates which is convenient for calculations. We very often have to calculate the difference between two dates.

Norwich Union Date Format.

NU dates, commonly referred to as ‘SNUF’ dates (Standard Norwich Union Format), are stored as the number of months since December 1849 (e.g. Jan 1850 is month 1, January 1998 is month 1777). These dates are stored in two 2-byte binary fields, the first holding months, the second the day of the month.

These dates are easily managed as there are several routines to convert 'normal' (i.e. DDMMYY) dates to NU dates and vice versa. Routines are documented in the dataset NUCWS.CENTSOFT.SUB#PROG or by using S.CENT option in TSO.

Example.

The routine RDDTOUTA will convert a Norwich Union date to a normal DDMMYY format

CALL 'RDDTOUTA' USING TR-DATE W30-DATE W30-ERROR.

TR-DATE is the name of a field (can be a group or elementary) containing the Norwich Union date.

W30-DATE is the name of the field to contain the normal date. W30-ERROR is an error message field set to zero if no error is found, if an error is

discovered identifier 3 is set to 1 and the contents of identifier 2 are indeterminate.

The statement following the CALL should test the error message field and take the appropriate action if the contents are not zero.

As the identifiers are accessed by both programs their lengths must be the same and their types compatible. The details of field lengths and types expected by project wide subroutines are contained in NU SOFTWARE.

IT TRAINING 81

Page 82: COBOL

COBOL Programming Last Printed: 08/04/23

43. GO TO....DEPENDING .

Purpose: to use the contents of dataname to determine which paragraph is to be executed. This is not a recommended way of controlling the logical flow through the code.

Format.

GO TO paragraph name 1 paragraph name 2 ..... DEPENDING ON dataname

Example.

The following:- IF W20-TYPE = 1 GO TO P20-10 END-IF. IF W20-TYPE = 2 GO TO P20-40 END-IF. IF W20-TYPE = 3 GO TO P20-60 END-IF.

Could be replaced by:

GO TO P20-10 P20-40 P20-60 DEPENDING ON W20-TYPE.

NB.The dataname must be a numeric field.If the value of dataname is less than 1 or greater than the number of paragraphs listed control passes to the instruction following the GO TO.Paragraph names can be repeated.

IT TRAINING 82

Page 83: COBOL

COBOL Programming Last Printed: 08/04/23

44. COBOL Subroutines .

A COBOL subroutine is a complete program in itself, that is, the four divisions have to be present.

44.1. CALL.

A CALL statement enables you to borrow pieces of compiled logic, normally called a subroutine (or sub program). Subroutines allow common code to be accessed by many programs. Subroutines need not be written in COBOL and can be written in another language (e.g. ASSEMBLER) if that is more appropriate to the task being carried out.

Control is passed from the main program to the subroutine by the CALL statement. Usually data items in the calling program need to be accessed by the subroutine. This is done via the USING option of the CALL statement which makes data items in the calling program available to the subroutine.

Format.

CALL 'Subroutine name' CALL 'Subroutine name' USING identifier 1

identifier 2

Subroutine name is a maximum of eight alphanumeric characters, the first must be alphabetic. The identifier(s) may be a field anywhere in the DATA DIVISION. Fields passed to the subroutine as input only, must not be changed by the called subroutine.

Control is passed to the subroutine (sometimes referred to as the called program) and data is passed to the subroutine via the CALL statement as previously described. The name of the subroutine is the PROGRAM-ID of the subroutine. The data fields are not copied into the subroutine, the subroutine has access to specified fields in the calling program's area. The passed fields are specified to the called program on the PROCEDURE DIVISION statement.

Status checks will be carried out immediately following a CALL, where possible.

IT TRAINING 83

Page 84: COBOL

COBOL Programming Last Printed: 08/04/23

Format.

PROCEDURE DIVISION USING identifier 1 identifier 2 .........

These identifiers are described, each at an 01 level, in the LINKAGE SECTION of the subroutine. The LINKAGE SECTION follows the WORKING-STORAGE SECTION. As the identifiers on the CALL and the PROCEDURE DIVISION are corresponded on position, not name, the identifiers must appear in the same order on both statements but not necessarily in this order in the LINKAGE SECTION. The identifiers must contain the same number of characters, although their pictures need not be the same. The names of the identifiers can differ between the calling program and the subroutine. The value statement cannot be used in the LINKAGE SECTION (other than for 88 levels) as data is overwritten each time the routine is called.

The execution of a called program always starts at the first statement of the PROCEDURE DIVISION. The first time a called program is entered its state is that of a fresh copy of the program. Each subsequent time a called program is entered its state is as it was upon the last exit from that program. Control is returned to the calling program by a GOBACK statement in the subroutine.

After the CALL statement has been executed control passes to the statement following the CALL.

44.1.1. Further Consideration.

Subroutines need not handle files, if they do normally all the file handling is done by the subroutine. If the file is opened and closed within the subroutine care must be taken that the file is not opened and closed every time the subroutine is called.

44.2. Link Editing.

A load module of a calling and called programs can be produced in two ways.

The program and subroutines can be compiled and object modules produced in the normal way. Linkage editor commands are then created in a LEL library with a member name of the program. These commands specify the object modules to be included to form the load module. The calling program is then link edited, but the LEL library is specified not the object library.

The subroutines can be held in load module form. If COBOL they are compiled in the normal way, then link edited with an extra option NCAL. A subroutine being linked by itself must be linked with NCAL, so that external references (i.e. CALLS) will not be resolved, because external references should only be resolved when we link edit the main program. The calling program is then link edited in the normal way, with the normal options.

The advantage of the second method is that the special commands in the linkage editor library are not required.

IT TRAINING 84

Page 85: COBOL

COBOL Programming Last Printed: 08/04/23

45. INSPECT .

Purpose: To count characters in a dataname and/or replace them. Can only be used with alphanumeric or zoned decimal fields.

Example 1.

INSPECT W20-FIELD TALLYING W20-TOTAL FOR LEADING ZEROS.

Example 2.

INSPECT W20-FIELD REPLACING LEADING SPACES BY '*'.

46. REFERENCE MODIFICATION

Purpose – to reference a portion of a data item. Can only be used with alphanumeric or zoned decimal fields. Note – not NU standard but occasionally useful.

Syntax - W00-DATA-ITEM (START BYTE POSITION : NUMBER OF BYTES)

Example 1

01 W10-WORKFIELDS. 03 W10-DATA-STRING PIC X(30) VALUE ‘A0025JONES NR126JU’.

MOVE W10-DATA-STRING(6:10) TO P-REP1-L1-SURNAME.

Would move the characters JONES (with the 5 trailing spaces) to the print line field. Much better to break down the string in Working Storage with group fields – easier to access.

Example 2

01 W10-WORKFIELDS. 03 W10-SYS-DATE PIC 9(6).

01 P-REP1-H1. 03 FILLER PIC X(6) VALUE ‘DATE : ‘. 03 P-REP1-H1-DAY PIC 99. 03 FILLER PIC X VALUE ‘/’. 03 P-REP1-H1-MONTH PIC 99. 03 FILLER PIC X VALUE ‘/’. 03 P-REP1-H1-CENT PIC 99 VALUE 20. 03 P-REP1-H1-YEAR PIC 99.

P10-XX. ACCEPT W10-SYS-DATE FROM DATE. MOVE W10-SYS-DATE(1:2) TO P-REP1-H1-YEAR. MOVE W10-SYS-DATE(3:2) TO P-REP1-H1-MONTH. MOVE W10-SYS-DATE(5:2) TO P-REP1-H1-DAY.

IT TRAINING 85

Page 86: COBOL

COBOL Programming Last Printed: 08/04/23

47. INDEXED .

We have already seen how to access occurring fields and tables. Indexing is a more efficient way of accessing these fields.

Example.Using subscripting:

03 W10-TOTAL PIC S9(3) PACKED-DECIMAL OCCURS 10. 03 W10-SUB PIC S9(4) BINARY.

MOVE W10-TOTAL(W10-SUB) TO W10-PREMIUM.

Using indexing we would have:-

03 W10-TOTAL PIC S9(3) PACKED-DECIMAL OCCURS 10 INDEXED BY X-TOTAL. .... MOVE W10-TOTAL(X-TOTAL) TO W10-PREMIUM.

47.1. Further Considerations.

X-TOTAL is not defined anywhere else in the DATA DIVISION, it will be set up automatically.

If a field is indexed you can still access it by a subscript. The index (i.e. X-TOTAL) contains a displacement value i.e. a value which points to

an item in a field relative to the start of the table.

Example.

To access the fourth occurrence of the above table the index would contain:

(occurrence - 1) X length in bytes

(4 - 1) X 2 = 6

Can use relative indexing;

MOVE W10-TOTAL(X-TOTAL + 2) TO ......

where 2 is the number of occurrences. This statement does not affect the value in X-TOTAL.

It is possible to have up to 3 levels of occurs with indexing at all levels.

Example. 03 W10-BRANCH OCCURS 60 INDEXED BY X-BRANCH. 05 W10-CLASS OCCURS 20 INDEXED BY X-CLASS. 07 W10-PREMIUM PIC S9(5) PACKED-DECIMAL. .... MOVE W10-PREMIUM(X-BRANCH X-CLASS) TO .....

IT TRAINING 86

Page 87: COBOL

COBOL Programming Last Printed: 08/04/23

Cannot have INDEXED BY at a 01 level, (you cannot have OCCURS at 01 level).

Cannot mix INDEXES and subscripts in the same reference.

Can have more than 1 index per occurs (see later).

Indexes are named X-meaningful name.

If tables are identical e.g. same level, same number of occurrences and the occurrences are the same length, an index belonging to one table can be used to access the other.

48. Modifying Indexes .

An index can only be modified by the following verbs;

SET PERFORM SEARCH

NB. Not by the MOVE verb.

48.1. SET.

Purpose: to move a value to an index. The SET statement establishes reference points for table handling operations by doing one of the following:

Placing values associated with table elements into indexes associated with index-names

Incrementing or decrementing an occurrence number Setting the status of an external switch to ON or OFF Moving data to condition names to make conditions true Setting pointer data items.

Index-names are related to a given table through the INDEXED BY phrase of the OCCURS clause; they are not further defined in the program.

When the sending and receiving fields in a SET statement share part of their storage (that is, the operands overlap), the result of the execution of such a SET statement is undefined.

Format.

SET index 1 TO dataname 2 SET dataname 1 TO index 2 SET dataname 1 TO integer

NB. index 1, dataname 1 are the receiving fields and must name either index data items or

elementary numeric integer items. index 2 is a sending field. The value before the SET statement is executed must

correspond to the occurrence number of its associated table. dataname 2 is a sending field. It must name either an index data item or an elementary

numeric integer item. integer 1 is a sending field a and must be a positive integer.

IT TRAINING 87

Page 88: COBOL

COBOL Programming Last Printed: 08/04/23

Example.

SET X-TABLE TO 1. SET X-TABLE TO X-TOT-TABLE. SET X-TABLE TO W20-COUNT.

In all cases the value is converted to a displacement value.

As arithmetic functions cannot be performed on an index, the following versions of the SET verb can be used.

SET index 1 index 2 UP BY datanameSET index 1 DOWN BY integer

Example.

SET X-TOT-TABLE UP BY 1. SET X-TOT-TABLE DOWN BY W20-COUNT.

48.2. SEARCH.

Purpose: to search a table for an element that satisfies the specified condition, and adjusts the associated index to indicate that element. When the item is found or the whole table has been searched, the SEARCH stops and control passes to the next statement. There are two versions of the SEARCH verb.

A serial search, the table is searched one entry at a time until the condition is satisfied or the end of table is reached.

A binary search, the number of entries in a table are continually divided by two until the required condition is satisfied or the search has been completed.

The following working storage is used for the serial and binary search examples:

03 W50-CAR-MAKE-TABLE. 05 W50-BMW PIC X(18) VALUE 'BMW ,GOOD '. 05 W50-FORD PIC X(18) VALUE 'FORD ,POOR '. 05 W50-VAUXHALL PIC X(18) VALUE 'VAUXHALL ,GOOD '. 03 FILLER REDEFINES W50-CAR-MAKE-TABLE. 05 W50-CAR-MAKE-ENTRY OCCURS 3 ASCENDING KEY IS W50-CAR-MAKE INDEXED BY W50-CAR-MAKE-TABLE-INDEX. 07 W50-CAR-MAKE PIC X(10). 07 FILLER PIC X. 07 W50-CAR-MAKE-QUAL PIC X(7).

NB. ASCENDING KEY IS clause is only required if a Binary chop (SEARCH ALL) is to be performed on the table.

IT TRAINING 88

Page 89: COBOL

COBOL Programming Last Printed: 08/04/23

48.3. Serial Search.

Format.

SEARCH dataname1 VARYING index name WHEN condition imperative statement

END-SEARCH.

SEARCH dataname1 AT END imperative statement END-SEARCH.

The serial search statement executes a search beginning at the current index setting. When the search begins, if the value of the index name associated with dataname1 is not greater than the highest possible occurrence number, the following actions take place:

 1. The condition(s) in the WHEN phrase are evaluated in the order in which they are written.2. If none of the conditions are satisfied, the index name for dataname 1 is increased to

correspond to the next table element, and step 1 is repeated.3. If upon evaluation, one of the WHEN conditions is satisfied, the search is terminated

immediately, and the imperative statement associated with that condition is executed. The index name points to the table element that satisfied the condition.

4. If the end of the table is reached (that is, the incremented index name value is greater than the highest possible occurrence number) without the WHEN condition being satisfied, the search is terminated, as described in the next paragraph.

If, when the search begins, the value of the index-name associated with dataname 1 is greater than the highest possible occurrence number, the search immediately ends, and, if specified, the AT END imperative statement is executed. If the AT END phrase is omitted, control passes to the next statement after the SEARCH statement.

Example.

SET W50-CAR-MAKE-TABLE-INDEX TO 1. SEARCH W50-CAR-MAKE-ENTRY AT END MOVE '?' TO W100-CAR-MAKE-QUALITY WHEN W50-CAR-MAKE(W50-CAR-MAKE-TABLE-INDEX) = W70-CAR-MAKE MOVE W50-CAR-MAKE-QUALITY(W50-CAR-MAKE-TABLE-INDEX) TO W100-CAR-MAKE-QUALITY END-SEARCH.

IT TRAINING 89

Page 90: COBOL

COBOL Programming Last Printed: 08/04/23

48.4. Binary Search.Format.

SEARCH ALL dataname 1 AT END imperative statementWHEN condition

END-SEARCH.

The SEARCH ALL statement executes a binary search. The search index need not be initialised by SET statements, because its setting is varied during the search operation so that its value is at no time less than the value of the first table element, nor ever greater than the value of the last table element. The index used is always that associated with the first index-name specified in the OCCURS clause.

The results of a SEARCH ALL operation are predictable only when:

The data in the table is ordered in ASCENDING/DESCENDING KEY, i.e. in the format:

............. OCCURS integer TIMES (ASCENDING/DESCENDING) KEY is dataname1 INDEXED BY index name1 index name2

The contents of the ASCENDING/DESCENDING keys specified in the WHEN clause provide a unique table reference.

Dataname 1 can be a data item subordinate to a data item that contains an OCCURS clause; that is, it can be a part of a two to seven-dimensional table. In this case, the data description entry must specify an INDEXED BY phrase for each dimension of the table. It must refer to all occurrences within the table element; that is, it must not be subscripted or reference-modified.Cannot be a floating-point data item. It cannot be a pointer data item. The Data Division description of dataname 1 must contain an OCCURS clause with the INDEXED BY option.

AT END, the condition that exists when the search operation terminates without satisfying the condition specified in any of the associated WHEN phrases.

Example.

SEARCH ALL W50-CAR-MAKE-ENTRY AT END MOVE '?' TO W100-CAR-MAKE-QUALITY WHEN W50-CAR-MAKE(W50-CAR-MAKE-TABLE-INDEX) = W70-CAR-MAKE MOVE W50-CAR-MAKE-QUALITY(W50-CAR-MAKE-TABLE-INDEX) TO W100-CAR-MAKE-QUALITY END-SEARCH.

IT TRAINING 90

Page 91: COBOL

COBOL Programming Last Printed: 08/04/23

Example 2.

03 W20-BRANCHES OCCURS 150 ASCENDING KEY IS W20-BRANCH INDEXED BY X-BRANCH. 05 W20-BRANCH PIC S9(5) PACKED-DECIMAL. 05 W20-BRANCH-TOTAL PIC S9(4) BINARY. .... SEARCH ALL W20-BRANCHES AT END GO TO P20-30 WHEN W20-BRANCH (X-BRANCH) = TR-BRANCH ADD W20-BRANCH-TOTAL (X-BRANCH) TO W20-AMT END-SEARCH.

NB. In the above example the table must be in W20-BRANCH order. Condition could be an 88 level name. An 88 level could only have a single value. The index does not have to be initialised before the SEARCH ALL statement. Only one WHEN is allowed but the conditions can be joined by an AND. The index used is always the first named index. If the search is unsuccessful the AT END statement, if present is obeyed, otherwise

control passes to the next statement. In this case the final value of the index is unpredictable.

If the search is successful the index contains the value that satisfied the WHEN condition.

If a relation-condition is specified it must be in the following format:

dataname 1 (EQUAL TO) (dataname2 ) ( = ) (literal) (arithmetic expression)

dataname1 must be a key field. dataname2 must not be a key field or a field indexed by the same index used in

the SEARCH. If the key consists of more than one field, all preceding key datanames must be

specified.

IT TRAINING 91

Page 92: COBOL

COBOL Programming Last Printed: 08/04/23

48.5. Comparison Between Subscripting and Indexing.

1. Subscript.

MOVE 1 TO W20-SUB. PERFORM UNTIL W20-SUB > 10 IF W20-BRANCH (W20-SUB) = TR-BRANCH MOVE W20-BRANCH-NAME (W20-SUB) TO P-REP1-L7-NAME END-IF ADD 1 TO W20-SUB END-PERFORM. IF W20-SUB > 10 MOVE 'INVALID BRANCH' TO P-REP1-L7-NAME END-IF.

2. Indexing.

P20-20. MOVE SPACES TO P-REP1-L7-NAME. SET X-BR-IND TO 1. SEARCH W20-NAMES WHEN W20-BRANCH (X-BR-IND) = TR-BRANCH MOVE W20-BRANCH-NAME (X-BR-IND) TO P-REP1-L7-NAME END-SEARCH. IF P-REP1-L7-NAME = SPACES MOVE 'INVALID BRANCH' TO P-REP1-L7-NAME END-IF. P20-30.

Or:

SET X-BR-IND TO 1. SEARCH W20-NAMES AT END MOVE 'INVALID' TO W30-MESSAGE WHEN W20-BRANCH (X-BR-IND) = TR-BRANCH MOVE W20-BRANCH-NAME (X-BR-IND) TO P-REP1-L7-NAME END-SEARCH.

3 Indexing with an Array Subscript.

01 W-ARRAY-WORKFIELDS. 03 W-ARRAY-SUB PIC 9(3) PACKED-DECIMAL. 03 W-ARRAY OCCURS (0 TO ) 50. 05 W-ARRAY-KEY PIC X(4). 05 W-ARRAY-ITEM PIC X(35).

PXX-00. MOVE 1 TO W-ARRAY-SUB. SEARCH W-ARRAY VARYING W-ARRAY-SUB AT END MOVE 'NOT THERE' TO P-REP1-DECODE WHEN W-ARRAY-KEY(W-ARRAY-SUB) = TR-KEY MOVE W-ARRAY-ITEM(W-ARRAY-SUB) TO P-REP1-DECODE END-SEARCH.

IT TRAINING 92

Page 93: COBOL

COBOL Programming Last Printed: 08/04/23

4 Indexing varying Array Index.

01 W-ARRAY-WORKFIELDS. 03 W-ARRAY OCCURS (0 TO) 50 INDEXED BY W-ARRAY-INDEX. 05 W-ARRAY-KEY PIC X(4). 05 W-ARRAY-ITEM PIC X(35).

PXX-00. SET W-ARRAY-INDEX TO 1. SEARCH W-ARRAY VARYING W-ARRAY-INDEX AT END MOVE 'NOT THERE' TO P-REP1-DECODE WHEN W-ARRAY-KEY(W-ARRAY-INDEX) = TR-KEY MOVE W-ARRAY-ITEM(W-ARRAY-INDEX) TO P-REP1-DECODE END-SEARCH.

5 Indexing varying Array Index.

01 W-ARRAY-WORKFIELDS. 03 W-ARRAY OCCURS (0 TO) 50 ASCENDING KEY IS W-ARRAY-KEY INDEXED BY W-ARRAY-INDEX. 05 W-ARRAY-KEY PIC X(4). 05 W-ARRAY-ITEM PIC X(35).

PXX-00. SEARCH ALL W-ARRAY AT END MOVE 'NOT THERE' TO P-REP1-DECODE WHEN W-ARRAY-KEY(W-ARRAY-INDEX) = TR-KEY MOVE W-ARRAY-ITEM(W-ARRAY-INDEX) TO P-REP1-DECODE END-SEARCH.

IT TRAINING 93

Page 94: COBOL

COBOL Programming Last Printed: 08/04/23

48.6. Further Considerations.

1. Searching a two dimensional table:

03 W20-LINE1 OCCURS 10 INDEXED BY X-LINE1. 05 W20-LINE2 PIC S9(4) BINARY OCCURS 5 INDEXED BY X-LINE2. .... PERFORM S30-SEARCH VARYING X-LINE1 FROM 1 BY 1 UNTIL W30-FOUND OR X-LINE1 > 10.

S30-SEARCH SECTION. P30-10. SET X-LINE2 TO 1. SEARCH W20-LINE2 WHEN W20-LINE2 (X-LINE1 X-LINE2) = 7 MOVE 1 TO W30-FOUND-IND. P30-EXIT. EXIT.

2. More than one index and the VARYING option of SEARCH. An OCCURS item can have more than one index. If the varying option is not used, the first named index is used for the SEARCH.

Example.

03 W10-TOTAL PIC S9(3) PACKED-DECIMAL OCCURS 10 INDEXED BY X-1-TOTAL X-2-TOTAL X-3-TOTAL.

IT TRAINING 94

Page 95: COBOL

COBOL Programming Last Printed: 08/04/23

49. INDEX

+

+ and - Floating (Replacement) · 46+ or - Fixed (Insertion) · 45

£

£ Floating (Replacement) · 45£ Fixed (Insertion) · 44

8

88 LEVEL · 34

A

ACCEPT · 13ACCEPT.... FROM.... · 14ADD · 51ALL · 49ALPHABETIC · 59APPLY WRITE ONLY · 77Arithmetic Verbs · 51

B

BINARY · 64Binary Search · 90Blank Spaces (Insertion) · 46BLANK WHEN ZERO · 48

C

Cheque Protect (Replacement) · 44Choice of numeric fields · 65CLOSE · 20column 8 · 18COLUMN POSITIONS · 11Columns · 6Commas (Insertion) · 47COMPUTE · 60CONDITION-NAMES (88 LEVEL). · 34CONTROL SECTION · 26COPY · 50Credit or Debit Indicators (Insertion) · 46

D

DATA DIVISION · 1, 7, 10, 16, 21, 68, 83, 86dataname · 6Dates · 81DDnames · 9Decimal Point · 27

DISPLAY · 15DIVIDE · 56divisions · 7

E

Editing fields · 43elementary fields · 17END-IF · 32END-PERFORM · 37ENVIRONMENT DIVISION · 1, 7, 9EVALUATE · 61EXIT · 23Explicit Scope Terminators · 32

F

FD · 16Figurative Constants · 38Figurative Constants 2 · 49file definition · 16File Handling · 66FILLER · 12Full Stop or Decimal Point (Insertion) · 48

G

GIVING · 51GO TO · 30GO TO....DEPENDING · 82GOBACK · 15Group fields · 17

H

HIGH-VALUES · 49

I

IDENTIFICATION DIVISION · 1, 7, 8identifier · 6IF · 29IF - Testing Field Contents · 59IF ... AND · 57IF ... ELSE · 57IF ... OR · 58IF and Arithmetic Expressions · 60IF....NOT · 58Implicit Redefinition · 66INDEXED · 86INITIALIZE · 33In-Line PERFORM · 37INPUT-OUTPUT SECTION · 9INSPECT · 85

IT TRAINING 95

Page 96: COBOL

COBOL Programming Last Printed: 08/04/23

L

level numbers · 17Level numbers · 10, 18Link Editing · 84LOW-VALUES · 49

M

Modifying Indexes · 87MOVE · 21MOVE - Other Considerations · 22MOVE and Decimal Points · 27MULTIPLY · 55

N

Naming Standards for Print Fields · 43NEGATIVE · 59NORWICH UNION DATES · 81Numeric fields · 63numeric literal · 6

O

OCCURS · 71OCCURS and REDEFINES · 72OCCURS DEPENDING ON · 74OCCURS, SUBSCRIPTS and TABLES · 71ON SIZE ERROR · 53OPEN · 19

P

PACKED-DECIMAL · 63PARM · 31PERFORM · 23PERFORM VARYING · 78PERFORM with TIMES phrase · 26PERFORM with UNTIL phrase · 25Picture (PIC) · Plus and Minus Signs (Insertion) · 45POSITIVE · 59print lines · 41PRINTING · 41PROCEDURE DIVISION · 1, 7, 13, 19, 23, 31,

35, 36, 61, 77, 79, 83, 84PROGRAM-ID · 8

R

READ · 19READ ... INTO · 40RECORD DESCRIPTION · 17REDEFINES · 69REFERENCE MODIFICATION · 85ROUNDED · 52

S

S.CENT · 81SEARCH · 88SELECT .. ASSIGN · 9sentence · 6SET · 87SET TO TRUE · 35Signed Fields · 28Slash (Insertion) · 47SNUF’ dates · 81SPACE or SPACES · 38Spacing · 12STRING · 79string overflow · 80Subroutines · 83Subscripting and Indexing · 92SUBSCRIPTS · 71SUBTRACT · 54

U

UNSTRING · 80

V

VALUE · 12, 39Variable Length Records · 68

W

Working-Storage · 11WRITE · 20WRITE ... FROM · 40

Z

Z (Suppression) · 44ZERO · 38

IT TRAINING 96

Page 97: COBOL

COBOL Programming Last Printed: 08/04/23

IT TRAINING 97