Basic COBOL Statements

79
® IBM Software Group © 2006 IBM Corporation Enterprise COBOL Education Using Rational Developer for Enterprise COBOL Education Using Rational Developer for System Z System Z Module 3 – Basic COBOL Statements Module 3 – Basic COBOL Statements Jon Sayles, IBM Software Group, Rational EcoSystems Team

Transcript of Basic COBOL Statements

Page 1: Basic COBOL Statements

®

IBM Software Group

© 2006 IBM Corporation

Enterprise COBOL Education Using Rational Developer for System ZEnterprise COBOL Education Using Rational Developer for System Z

Module 3 – Basic COBOL StatementsModule 3 – Basic COBOL Statements

Jon Sayles, IBM Software Group, Rational EcoSystems Team

Page 2: Basic COBOL Statements

2

IBM Trademarks and Copyrights

© Copyright IBM Corporation 2007,2008, 2009. All rights reserved.

The information contained in these materials is provided for informational purposes only, and is provided AS IS without warranty of any kind, express or implied. IBM shall not be responsible for any damages arising out of the use of, or otherwise related to, these materials. Nothing contained in these materials is intended to, nor shall have the effect of, creating any warranties or representations from IBM or its suppliers or licensors, or altering the terms and conditions of the applicable license agreement governing the use of IBM software. References in these materials to IBM products, programs, or services do not imply that they will be available in all countries in which IBM operates.

This information is based on current IBM product plans and strategy, which are subject to change by IBM without notice. Product release dates and/or capabilities referenced in these materials may change at any time at IBM’s sole discretion based on market opportunities or other factors, and are not intended to be a commitment to future product or feature availability in any way.

IBM, the IBM logo, the on-demand business logo, Rational, the Rational logo, and other IBM Rational products and services are trademarks or registered trademarks of the International Business Machines Corporation, in the United States, other countries or both. Other company, product, or service names may be trademarks or service marks of others.

Page 3: Basic COBOL Statements

3

Course Contributing Authors

Thanks to the following individuals, for assisting with this course: David Myers/IBM Ka Yin Lam/IBM Don Higgins/Automated Software Tools Corporation Steve Wilcenski/Sabre Systems, Inc. Mike Wrzinski/Sentry Insurance

Page 4: Basic COBOL Statements

4

Course Description Course Name: COBOL Foundation Training - with RDz

Course Description: Learn the COBOL language, RDz and learn z/OS terms, concepts and development skills in this course.

Pre-requisites: Some experience in a 3rd or 4th Generation Language is expected. SQL is also recommended.

Course Length: 10 days

Topics (Agenda) Getting Started - installing and configuring RDz - and the course materials, and using Eclipse to edit COBOL COBOL General Language Rules Basic COBOL StatementsBasic COBOL Statements Advanced record and table handling Debugging Programs - Note: Deep dive on using RDz for common COBOL programming errors (001, 0C4, 0C7, infinite loops, fall-thru, etc.) Input/Output and Report Writing Patterns COBOL Subprograms and the Linkage Section Structured Programming Concepts, professional COBOL development practices and Coding Patterns Advanced Character Manipulation, COBOL Intrinsic Functions, Date and Time coding patterns, and Language Environment calls OS/390 Concepts and JCL - Compile/Link & Run Procs on the mainframe Indexed file Coding Patterns Sort/Merge, Sequential File Match/Merge and Master File Update Coding Patterns Accessing DB2 Data and DB2 Stored Procedures COBOL in the Real World:

– CICS - lecture only– IMS (DL/I and TM) - ditto– Batch processing - ditto– Java calling COBOL– COBOL and XML Statements– SOA and COBOL - creating and calling Web Services– Web 2.0 using Rich UI

Page 5: Basic COBOL Statements

5

Course Details

Audience This course is designed for application developers who have programmed in

some language before, and who wish to learn COBOL.

Prerequisites This course assumes that the student has the basic knowledge of IS

technologies, data processing, software and have programmed for at least two or more years in a language such as: Java, VB, RPG, PL/1, Pascal, or some 4th Generation Language or tool.

Knowledge of SQL (Structured Query Language) for database access is assumed as well.

Basic PC and mouse-driven development skills is also assumed. Finally, it is assumed that you have been following along in this course, and

have successfully completed the learning modules in sequence. Or have the equivalent COBOL background obtained through some other form of

COBOL study or on-the-job work.

Page 6: Basic COBOL Statements

6

Unit

Assignment Statements and Internal Data Assignment Statements and Internal Data RepresentationRepresentation

Math Operations

Conditional Logic

Transfer of control

COBOL Looping Constructs

Sequential File Processing Patterns

Java and .NET Equivalents

Topics:Topics:

COBOL General Language COBOL General Language RulesRules

Page 7: Basic COBOL Statements

7

Topic objectives

After completing this topic, you should be able to:Describe the COBOL MOVE and assignment operationList the three types of COBOL assignment statements – and what causes the

COBOL compiler to choose one type over the otherDefine the rules for:

Alphanumeric moves Numeric moves Group or structure moves

List a few optional MOVE clauses, and describe what they do, including: MOVE CORRESPONDING

Code MOVE statements that are syntactically correctDescribe the underlying COBOL storage representation for:

Alphanumeric data Numeric data

List the common COBOL Figurative ConstantsDescribe what the COBOL INITIALIZE statement does

Page 8: Basic COBOL Statements

8

COBOL Picture Clauses and Internal Data Representation

COBOL Data types are PICPIC clause dependent, and come in several broad categories: Character Data:

Fixed Length: PIC X(nn) – or PIC A(nn) PIC X(nn) – or PIC A(nn) … Note, A "Alphabetic data" Stored as EBCDIC bytes – examples: AA Hex: C1C1, BB Hex: C2C2, 99 Hex: F9F9, etc

http://theamericanprogrammer.com/code7302/ebcdic.txt

Numeric Data: DisplayDisplay numeric (aka Zoned Decimal): PIC 9(5), PIC S9(5)V99PIC 9(5), PIC S9(5)V99

Stored as EBCDIC bytes, with "assumed" decimal place – one byte per digit – Hex values: F0 F0 F9 F9

With VV in declaration – COBOL takes care of decimal alignment in math/MOVEMOVE operations With SS (sign) in declaration, the last byte of internal storage holds the sign (C or D):

– CC - is positive number:– PIC S9(5)V99 - value: 321.19 F0 F0 F3 F2 F1 F1 C9

– DD - is negative number– PIC S9(5)V99 - value: 321.19 F0 F0 F3 F2 F1 F1 D9

Binary (COMP) numeric – used to improve run-time COBOL arithmetic instruction performance: Small binary: PIC S9(4) COMPPIC S9(4) COMP – stored in two bytes, pure binary (base 16) data Medium binary: PIC S9(9) COMPPIC S9(9) COMP – stored in four bytes Large binary: PIC S9(18) COMPPIC S9(18) COMP – stored in eight bytes With or without Signs, and assumed decimal places:

Ex.– PIC S9(4) COMP Value 123. PIC S9(4) COMP Value 123. Stored as: 01230123– PIC S9(4) COMP Value -123. PIC S9(4) COMP Value -123. Stored as twos complement of 123: FF85 123: FF85

Packed decimal (COMP-3) numeric – frequently used to reduce the size of a file: Two digits per/byte. Sign bit – in last "nibble" (bottom 1/2 of last byte). "Slack bytes" (other high-order/leading

zeroes) may need to be added to the internal storage to account for evenly divisible PIC clause + sign nibbleEx.

– PIC S9(5)V99 COMP-3 Value 123.99. PIC S9(5)V99 COMP-3 Value 123.99. Stored as: 00 12 39 9C 00 12 39 9C– PIC S9(5)V99 COMP-3 Value -123.99. PIC S9(5)V99 COMP-3 Value -123.99. Stored as: 00 12 39 9D 00 12 39 9D

Important – See Slide NotesImportant – See Slide Notes

EBCDIC InternalData Representation

Page 9: Basic COBOL Statements

9

COBOL Picture Clause Editing and External (Output) Field Values

There are a number of other PICPIC clauses used for output result data on reports and green-screen I/O. They are simple to understand, and very convenient. Note that the numeric PICPIC clauses force decimal-point alignment. The alphanumeric PICPIC clauses all align the data left.

Z Suppress leading zeroes – insert floating blanks PIC ZZ,ZZZ,Z99.99PIC ZZ,ZZZ,Z99.99

B Alphanumeric "mask" – Positionally insert a blank into alphanumeric data PIC XBXBXBPIC XBXBXB

0 Numeric "mask" - Positionally insert a zero into a numeric field. PIC 990990PIC 990990

/ Data mask - Insert a slash into alphanumeric data – typically used for dates PIC XX/XX/XXPIC XX/XX/XX

, Insert a comma into numeric data PIC Z,ZZZ,Z99.99PIC Z,ZZZ,Z99.99

. Insert a decimal point, into numeric data Z,ZZZ,Z99.99Z,ZZZ,Z99.99

+ Insert a plus sign – IF the value in the variable is > 0PIC Z,ZZZ,Z99.99+PIC Z,ZZZ,Z99.99+

- Insert a negative sign – IF the value in the variable is < 0PIC Z,ZZZ,Z99.99-PIC Z,ZZZ,Z99.99-

CR Insert a "CR" literal – IF the value in the variable is < 0PIC Z,ZZZ,Z99.99CRPIC Z,ZZZ,Z99.99CR

DB Insert a "DB" literal – IF the value in the variable is < 0PIC Z,ZZZ,Z99.99DBPIC Z,ZZZ,Z99.99DB

* Insert asterisks instead of leading zeros for numeric valuesPIC ********9999PIC ********9999

$ Dollar-sign suppressions - Insert a floating, left-justified $ sign for numeric valuesPIC $$,$$$,$99.99PIC $$,$$$,$99.99

Page 10: Basic COBOL Statements

10

ILE Reference Manual – Picture Clause Editing Examples – 1 of 2

The ILE reference manual has an excellent sample guide to Picture Clause editing http://publib.boulder.ibm.com/infocenter/iadthelp/v7r0/index.jsp?topic=/com.ibm.etools.iseries.langref.doc/c0925395267.htm

Page 11: Basic COBOL Statements

11

ILE Reference Manual – Picture Clause Editing Examples – 2 of 2

The ILE reference manual has an excellent sample guide to Picture Clause editing http://publib.boulder.ibm.com/infocenter/iadthelp/v7r0/index.jsp?topic=/com.ibm.etools.iseries.langref.doc/c0925395267.htm

Page 12: Basic COBOL Statements

12

COBOL Storage Representation – Reference Chart

Picture ClausePicture Clause MeaningMeaning ValueValue Internal ValueInternal Value

Internal Storage Internal Storage (EBCDIC bytes)(EBCDIC bytes)

PIC X(10) Fixed alpha-numeric data 'ABC' ABCbbbbbbb (seven trailing blanks)

CCC444444412300000000

PIC 9(5) Display numeric (Zoned Decimal) numbers -321 00321 - Note - without S (sign) value get "absolute value"

FFFFF00321

PIC S9(5) Zoned decimal - with sign -321 00321 - Value is negative in math operations

FFFFD00321

PIC S9(5)V99 Zoned decimal with implied decimal place 321.5 00321V50 FFFFFFC0032150

PIC S9(4) COMP Small binary number - 2 byte - note, negative binary #s stored as two's complement

321 0321 0411

PIC S9(5) ==> S9(9) COMP Binary number - 4 bytes 321 00000321 00040011

PIC S9(9) ==> S9(18) COMP Large Binary number 321 000000000000000321 0000000400000011

PIC 9(4) COMP-3 Packed decimal number 321 0321 03102F

PIC S9(5)V99 COMP-3 Packed decimal number 321.99 00321.99 0319029C

PIC S9(5)V99 COMP-3 Packed decimal number -321.99 00321.99 – Value is negative in math operations

0319029D

External PIC clauses Value Output/Display Value NotesPIC Z(3) Zero-suppressed -2.99 2 No decimal places, no sign

PIC ZZ,ZZZ,ZZZ.99- Zero-suppressed, with commas and minus sign -321.99 321.99- Sign on right (can be on left). Zeroes suppressed

PIC $$,$$$,$99.99 Dollar-sign suppressed -321.99 $321.99 One resulting $, if need sign, must use dash (-)

PIC XBXBXB Blank insertion ABC AbBbCb Positional blank (b) inserted

PIC 990990 Zero insertion -321.99 030210 High-order inserted, numbers inserted @ PIC 9

PIC XX/XX/XX Slash insertion 012099 01/10/99 Date mask

PIC Z,ZZZ,Z99.99CR Zero-suppressed, with commas and Credit sign -321.99 321.99CR If number was positive, CR would not appear

PIC ****9999 Asterisk suppressed -333321.99 **321 Like Z and $ - asterisk suppresses leading zeros

PIC Z,ZZZ,Z99.99DB Zero-suppressed, with commas and Debit sign 321.99 321.99 If number was negative, DB would appear

Page 13: Basic COBOL Statements

13

88-Level Variables in the Data Division

88-level variables in COBOL programs are "conditionals, built in to the variable declarations"

They: Have no PICPIC clause Have one or more VALUESVALUES – specified as literals (see a few valid expressions below) Are used effectively to make COBOL IFIF conditional expressions readable/maintain-able

01 MONTH-IND PIC XXX.01 MONTH-IND PIC XXX. 88 SHORTEST-MONTH VALUE 'FEB'.88 SHORTEST-MONTH VALUE 'FEB'. 88 THIRTY-DAY-MONTH 88 THIRTY-DAY-MONTH

VALUES ARE 'JUN', 'SEP', 'APR', 'NOV'.VALUES ARE 'JUN', 'SEP', 'APR', 'NOV'. 88 THIRTY-ONE-DAY MONTH 88 THIRTY-ONE-DAY MONTH

VALUES ARE 'JAN' 'MAR' 'MAY' 'JUL' 'AUG' 'OCT' 'DEC'.VALUES ARE 'JAN' 'MAR' 'MAY' 'JUL' 'AUG' 'OCT' 'DEC'.…… IF THIRTY-DAY-MONTHIF THIRTY-DAY-MONTH

……

01 STUDENT-GRADE-RANGE PIC S9(3).01 STUDENT-GRADE-RANGE PIC S9(3). 88 A-OK 88 A-OK VALUE 90 THRU 100.VALUE 90 THRU 100. 88 NOT-BAD 88 NOT-BAD VALUE 80 THRU 89.VALUE 80 THRU 89. 88 PRETTY-GOOD VALUE 70 THRU 79.88 PRETTY-GOOD VALUE 70 THRU 79. 88 RUH-ROH 88 RUH-ROH VALUE 60 THRU 79.VALUE 60 THRU 79. 88 FAIL 88 FAIL VALUE 0 THRU 59.VALUE 0 THRU 59.

……IF NOT-BADIF NOT-BAD MOVE 'DOIN ALRIGHT' TO MSG-TEXTMOVE 'DOIN ALRIGHT' TO MSG-TEXT DISPLAY GRADE-MSGDISPLAY GRADE-MSG

Pluses:Pluses:• Make code more "English" read-ableMake code more "English" read-able• Allow you to centralize conditions in one place - Allow you to centralize conditions in one place - in the DATA DIVISIONin the DATA DIVISION

Minuses:Minuses:• Force you to refer to the DATA DIVISION for the Force you to refer to the DATA DIVISION for the actual values tested in the code in the PROCEDURE actual values tested in the code in the PROCEDURE DIVISIONDIVISION

Pluses:Pluses:• Make code more "English" read-ableMake code more "English" read-able• Allow you to centralize conditions in one place - Allow you to centralize conditions in one place - in the DATA DIVISIONin the DATA DIVISION

Minuses:Minuses:• Force you to refer to the DATA DIVISION for the Force you to refer to the DATA DIVISION for the actual values tested in the code in the PROCEDURE actual values tested in the code in the PROCEDURE DIVISIONDIVISION

Page 14: Basic COBOL Statements

14

Review – Imperative Statements – MOVEMOVE

FILE SECTION…01 OUT-REC PIC X(80).…WORKING-STORAGE SECTION. 77 INPUT-DATA PIC X(40).…PROCEDURE DIVISION.

…ACCEPT INPUT-DATA.MOVE INPUT-DATA TO OUT-REC.MOVE INPUT-DATA TO OUT-REC.

Syntax: MOVE <to-variable> TO <from-variable>. MOVE <to-variable> TO <from-variable>.

MOVE MOVE copiescopies the value in the to-variableto-variable to the from-variablefrom-variable (receiving field), over-writing the from-variablefrom-variable’s storage contents.

There are two types of MOVE operations:MOVE operations: Alphanumeric MOVEMOVE Numeric MOVEMOVE

The receiving field's datatype (PICPIC clause) dictates the type of MOVEMOVE operation It is important to understand how the contents of variable storage are affected by

MOVEMOVE. So, let's drill-down now, on PICPIC clauses and COBOL internal data storage representation

Page 15: Basic COBOL Statements

15

Alphanumeric MOVEMOVE Statements

Alphanumeric MOVEMOVE statements: Occur when the receiving field is considered Alphanumeric by the compiler

PIC XPIC X PIC APIC A The Alphanumeric formatted output PIC clauses:

– PIC with B, etc. Proceed from left-to-right – and copy byte-for-byte

When the sending and receiving fields are not the same size: Space (blank) fill to the right, if the receiving field is longer than the sending field Truncate if the receiving field is shorter than the sending field (typically you will get a W-level

diagnostic when you compile a program with a MOVEMOVE statement that truncates data) Except – can JUSTIFYJUSTIFY the receiving field data RIGHTRIGHT

FLD1 PIC X(4) VALUE 'ABCD'. FLD2 PIC X(10) JUSTIFY RIGHT.

… MOVE FLD1 TO FLD2.

– Results in FLD2 value of: bbbbbbABCDbbbbbbABCD If JUSTIFY RIGHTJUSTIFY RIGHT, and the receiving field is shorter than the sending field, truncation occurs in the right-most

characters If JUSTIFY RIGHTJUSTIFY RIGHT, and the receiving field is longer than the sending field, blanks are added to the left-most

positions Note: if, FLD1 PIC X(10) VALUE 'ABCD'FLD1 PIC X(10) VALUE 'ABCD' result of MOVEMOVE is: ABCDbbbbbbABCDbbbbbb.

– Why? Copy:

Internal storage values byte for byte For the # of bytes in the receiving field

Group data (structures) are considered Alphanumeric – in MOVEMOVE operations

Page 16: Basic COBOL Statements

16

Numeric MOVEMOVE Statements

Numeric MOVEMOVE statements: Occur when the receiving field's PICPIC clause is numeric

9 … 9 … anywhere in the PIC PIC clause Input field declaration:

– V, S Output (formatted numeric PICPIC clause in declaration)

– Z, $, 0, DB, CR, +, -, period (.), comma (,)

MOVEMOVE copies the algebraic value of the sending field to the receiving field as follows: Automatically aligns at the decimal place

Or assumed decimal place if no VV in PICPIC clause

Pad to the left with leading, and to the right with trailing zeroeszeroes, if the receiving field has more decimal digits to the left or the right of the (assumed) decimal positions

If sign (S) or numeric edited sign MOVEMOVE will value the receiving positively or negatively depending on the sending field's value. If no sign, the receiving field gets absolute value

Will numerically truncate – if receiving field has fewer decimal digits to the left of the decimal place, or less digits (decimal precision) to the right of the decimal place

What about mixed datatype MOVE statements? (next slide…)What about mixed datatype MOVE statements? (next slide…)

Page 17: Basic COBOL Statements

17

MOVE Statements When the Datatypes Are Not The Same Obviously you can move PIC XPIC X fields to other PIC XPIC X – and PIC 9PIC 9 fields to other PIC 9PIC 9

fields, but sometimes, due to business requirements you will have to code MOVEMOVE statements of unlike (mixed) datatypes.

Here are the general rules: Anything can be moved to an alphanumeric PIC X field Only other PIC 9 (input) fields can be moved to PIC 9 fields And only PIC 9 fields can be moved to numeric edited fields PIC 9 numeric edited fields can be moved to PIC 9 fields

Group moves are considered exactly the same as an alphanumeric PIC X field move by the compiler And all the rules you just learned about truncation, padding and decimal alignment also apply

This table may help clarify the rules for mixed data type MOVEMOVE

Sending Sending FieldsFields

Receiving FieldsReceiving Fields

PIC XPIC X PIC 9PIC 9

Numeric Numeric EditedEdited

PIC XPIC X YY NN NN

PIC 9PIC 9 Y Y Treated as an alphanumeric MOVE Treated as an alphanumeric MOVE

(digits may be lost, trailing blanks may be added, etc.)

YY YY

Numeric EditedNumeric Edited YY YY NN

Page 18: Basic COBOL Statements

18

AllowableMOVE Statements Please consult

this verbose (!) table to see the complete list of COBOL allowable MOVE statements – based on sending and receiving field PIC types.

Don't worry if there are terms you're not up to speed on just yet – we'll get you there.

Patience

Page 19: Basic COBOL Statements

19

Alphanumeric MOVEMOVE Statements - ExamplesSending FieldSending Field Receiving FieldReceiving Field Sending Field ValueSending Field Value Result in Receiving Result in Receiving

FieldFieldPIC X(5) PIC X(5) ABCDE ABCDE

PIC X(5) PIC X(3) ABCDE ABC

PIC X(5) PIC X(8) ABCDE ABCDEbbb

PIC 9(5) PIC X(8) 12345 12345bbb

PIC X(5) PIC 9(5) Not allowed by the compiler N/A

PIC S9(5)V99 COMP-3 PIC X(8) Not allowed by the compiler – as is non-integer numeric (see table of moves)

13574444 (hex)246C0000

PIC S9(4) COMP PIC X(4) 1234 13442400

PIC X(4) PIC X(10) JUSTIFY RIGHT. ABCD bbbbbbABCD

Numeric ValueNumeric ValuePIC 9(5)V99 PIC 9(3)V9 12345.67 345.67

PIC S9(7)V99 PIC 9(4) COMP 123456789.99 6789

PIC S9(5)V99 PIC S9(7)V999 COMP-3 -12345.67 0012345.670 (minus carried in sign bit)

PIC S9(9) COMP PIC 9(5)V99 1234567912 67912.00

PIC S9(5)V99 COMP-3 PIC 9 -12345.67 5

Group MovesGroup MovesCUSTOMER-NAME PIC X(18) SMITHbbbbbAALEXAND

CUSTOMER-RECORD PIC X(40) 1201SMITHbbbbbAALEXANDERbbbbbbbbbbbbbbbbbbbbbb

01 CUSTOMER-RECORD.01 CUSTOMER-RECORD. 05 ID-NUMBER PIC 9(2) VALUE 12.05 ID-NUMBER PIC 9(2) VALUE 12. 05 CUST-TYPE PIC 9(2) VALUE 01.05 CUST-TYPE PIC 9(2) VALUE 01. 05 CUSTOMER-NAME.05 CUSTOMER-NAME. 10 FIRST-NAME PIC X(10) VALUE 'SMITH'.10 FIRST-NAME PIC X(10) VALUE 'SMITH'. 10 MIDINIT PIC X(01) VALUE 'A'.10 MIDINIT PIC X(01) VALUE 'A'. 10 LAST-NAME PIC X(10) VALUE 'ALEXANDER'.10 LAST-NAME PIC X(10) VALUE 'ALEXANDER'.

Page 20: Basic COBOL Statements

20

MOVE With OF ModifierMOVE With OF Modifier

FILE SECTION. …

01 CUSTOMER-RECORD-IN.01 CUSTOMER-RECORD-IN.

05 ID-NUMBER PIC 9(2).05 ID-NUMBER PIC 9(2).

05 CUST-TYPE PIC 9(2).05 CUST-TYPE PIC 9(2).

05 CUSTOMER-NAME.05 CUSTOMER-NAME.

10 FIRST-NAME PIC X(10).10 FIRST-NAME PIC X(10).

10 MIDINIT PIC X(01).10 MIDINIT PIC X(01).

10 LAST-NAME PIC X(10).10 LAST-NAME PIC X(10).

01 CUSTOMER-RECORD-OUT.01 CUSTOMER-RECORD-OUT.

05 ID-NUMBER PIC 9(2).05 ID-NUMBER PIC 9(2).

05 CUST-TYPE PIC 9(2).05 CUST-TYPE PIC 9(2).

05 CUSTOMER-NAME.05 CUSTOMER-NAME.

10 FIRST-NAME PIC X(10).10 FIRST-NAME PIC X(10).

10 MIDINIT PIC X(01).10 MIDINIT PIC X(01).

10 LAST-NAME PIC X(10).10 LAST-NAME PIC X(10). … PROCEDURE DIVISION.

MOVE FIRST-NAME OF CUSTOMER-RECORD-IN TO FIRST-NAME OF CUSTOMER-RECORD-OUT.MOVE FIRST-NAME OF CUSTOMER-RECORD-IN TO FIRST-NAME OF CUSTOMER-RECORD-OUT.

Syntax: MOVE <from-variable> of <from-Group> to <to-variable>. MOVE <from-variable> of <from-Group> to <to-variable>.

The OF modifier allows you to:The OF modifier allows you to: Fully-qualify elementary field names – making large programs with 1,000's variables easier to maintainFully-qualify elementary field names – making large programs with 1,000's variables easier to maintain Compile programs with duplicate elementary field namesCompile programs with duplicate elementary field names

Page 21: Basic COBOL Statements

21

FILE SECTION. …

01 CUSTOMER-RECORD-IN.01 CUSTOMER-RECORD-IN.

05 ID-NUMBER PIC 9(2).05 ID-NUMBER PIC 9(2).

05 05 CUST-TYPECUST-TYPE PIC 9(2). PIC 9(2).

05 CUSTOMER-NAME.05 CUSTOMER-NAME.

10 10 FIRST-NAMEFIRST-NAME PIC X(10). PIC X(10).

10 MIDINIT PIC X(01).10 MIDINIT PIC X(01).

10 LAST-NAME PIC X(10).10 LAST-NAME PIC X(10).

01 CUSTOMER-RECORD-OUT.01 CUSTOMER-RECORD-OUT.

05 ID-NUMBER PIC 9(2).05 ID-NUMBER PIC 9(2).

05 05 CUSTTYPCUSTTYP PIC 9(2). PIC 9(2).

05 CUSTOMER-NAME.05 CUSTOMER-NAME.

10 10 FIRSTNAMEFIRSTNAME PIC X(10). PIC X(10).

10 MIDINIT PIC X(01).10 MIDINIT PIC X(01).

10 LAST-NAME PIC X(10).10 LAST-NAME PIC X(10). … PROCEDURE DIVISION.

MOVE CORRESPONDING CUSTOMER-RECORD-IN TO CUSTOMER-RECORD-OUT.MOVE CORRESPONDING CUSTOMER-RECORD-IN TO CUSTOMER-RECORD-OUT.

Syntax: MOVE CORRESPONDING <from-group-variable> to <to-group-variable>. MOVE CORRESPONDING <from-group-variable> to <to-group-variable>.

The The CORRESPONDINGCORRESPONDING modifier allows you to modifier allows you to MOVEMOVE group records: group records: When COBOL variable names match between the from and to groups, data is copiedWhen COBOL variable names match between the from and to groups, data is copied And only when COBOL variable names matchAnd only when COBOL variable names match

MOVE CORRESPONDINGMOVE CORRESPONDING

Field's data not movedField's data not moved

Field's data not movedField's data not moved

See NotesSee Notes

Page 22: Basic COBOL Statements

22

COBOL INITIALIZEINITIALIZE Statement

INITIALIZE values selected types of data fields. The default is: Numeric data to zeros alphanumeric data (PIC X or Group Data Items) to spaces.

You can also INITIALIZE fields, replacing classes of datatypes with specific values This is used less frequently, and is shown in the slide notesslide notes

Initializing a structure (INITIALIZE) You can reset the values of all subordinate data items in a group item by applying the

INITIALIZE statement to that group item.

Page 23: Basic COBOL Statements

23

COBOL Figurative ConstantsCOBOL Figurative Constants

FILE SECTION. …

01 CUSTOMER-RECORD-IN.01 CUSTOMER-RECORD-IN. …

77 COBOL-CHAR-FIELD77 COBOL-CHAR-FIELD PIC X(4).PIC X(4).

77 COBOL-NUM-FIELD77 COBOL-NUM-FIELD PIC X(4).PIC X(4).

77 COBOL-QT77 COBOL-QT PIC X(1) VALUE QUOTE.PIC X(1) VALUE QUOTE.

PROCEDURE DIVISION.

MOVE LOW-VALUES to CUSTOMER-RECORD-IN.MOVE LOW-VALUES to CUSTOMER-RECORD-IN.

MOVE HIGH-VALUES to COBOL-CHAR-FIELD.MOVE HIGH-VALUES to COBOL-CHAR-FIELD.

MOVE SPACES MOVE SPACES to COBOL-CHAR-FIELD. to COBOL-CHAR-FIELD.

MOVE ZEROS to COBOL-NUM-FIELD.MOVE ZEROS to COBOL-NUM-FIELD.

MOVE ALL '_' TO COBOL-CHAR-FIELD.MOVE ALL '_' TO COBOL-CHAR-FIELD.

Syntax: MOVE <figurative constant> to <Cobol variable>. MOVE <figurative constant> to <Cobol variable>.

There are a number of COBOL figurative constants available to fill the storage of alphanumeric fields (or in the case of ZEROS), either: With MOVEMOVE statements In VALUE clauses of field declarations

The figurative constants are reserved words, and there are a number of alternative spellings (see the COBOL language reference, or RDz Help system)

They are sometimes used by convention to signal some processing event: READ <fileName> AT END MOVE HIGH-VALUES TO <inputRecord>.READ <fileName> AT END MOVE HIGH-VALUES TO <inputRecord>.

Page 24: Basic COBOL Statements

24

Lab Assignment

From the course workshop documents, do the following labs:1. Data Representation and assignment (MOVE statement) Lab

2. Open ended workshop

Page 25: Basic COBOL Statements

25

Unit

Topics:Topics:

COBOL General Language COBOL General Language RulesRules

Assignment Statements and Internal Data Representation

Math OperationsMath Operations

Conditional Logic

Transfer of control

COBOL Looping Constructs

Sequential File Processing Patterns

Java and .NET Equivalents

Page 26: Basic COBOL Statements

26

COBOL Mathematical Operators

As you'd expect from a a business oriented languagebusiness oriented language, COBOL's math capabilities are simple, flexible, deep and robust. Simple operations:

ADDADD SUBTRACTSUBTRACT MULTIPLYMULTIPLY DIVIDEDIVIDE

…with a number of variations of operand/operator expressions and automatic decimal alignment across all numeric types

Algebraic statements: COMPUTECOMPUTE – uses arithmetic operators (next slide) to perform math operations

COBOL Intrinsic "Built-in" math Functions Here are a few of the math-oriented COBOL intrinsic functions:

ACOS ACOS ANNUITY ANNUITY ASIN ASIN ATAN ATAN CHAR CHAR COS COS FACTORIAL FACTORIAL LOG LOG

LOG10 LOG10 MAX MAX MEAN MEAN MEDIAN MEDIAN MIDRANGE MIDRANGE MIN MIN MOD MOD PRESENT-VALUE PRESENT-VALUE RANDOM RANDOM

RANDOM RANDOM RANGE RANGE REM REM REVERSE REVERSE SIN SIN SQRT SQRT STANDARD-DEVIATION STANDARD-DEVIATION SUM SUM TAN TAN VARIANCE VARIANCE

Page 27: Basic COBOL Statements

27

Fixed-Point Arithmetic Statements*** – ADDADD

WORKING-STORAGE SECTION. 01 WORK-FIELDS.

05 ITEM-1 PIC S9(3)V99 VALUE 85.52. 05 ITEM-1 PIC S9(3)V99 VALUE 85.52. 05 ITEM-2 PIC S9(3)V99 VALUE 2.34. 05 ITEM-2 PIC S9(3)V99 VALUE 2.34. 05 SUM PIC S9(5)V99 VALUE 0. 05 SUM PIC S9(5)V99 VALUE 0.

PROCEDURE DIVISION. …

ADD ITEM-1, ITEM-2 TO SUM ROUNDEDADD ITEM-1, ITEM-2 TO SUM ROUNDED ON SIZE ERROR MOVE 0 TO SUMON SIZE ERROR MOVE 0 TO SUM END-ADDEND-ADD

ADD ITEM-1 ITEM-2 GIVING SUM ROUNDEDADD ITEM-1 ITEM-2 GIVING SUM ROUNDED ON SIZE ERROR MOVE 0 TO SUMON SIZE ERROR MOVE 0 TO SUM DISPLAY '** ON SIZE ERROR **'DISPLAY '** ON SIZE ERROR **' END-ADDEND-ADD

Format 1Format 1 Adds the addend to the sumAdds the addend to the sum

Format 2Format 2 The values of all operands preceding the word GIVING are added together, and the The values of all operands preceding the word GIVING are added together, and the

sum is stored as the new value.sum is stored as the new value. None of the values in the operands preceding GIVING are changedNone of the values in the operands preceding GIVING are changed

Note: There is a Format 3 statement: ADD CORRESPONDINGADD CORRESPONDING

RoundedRounded Rounds to the decimal digits in the PIC Rounds to the decimal digits in the PIC

clause (See Slide Notes)clause (See Slide Notes)

ON SIZE ERRORON SIZE ERROR Allows you to handle arithmetic overflow Allows you to handle arithmetic overflow

conditions with imperative statements.conditions with imperative statements. Additional note: Additional note: You can substitute a

numeric literal for the variables in the ADDADD and TOTO (but not GIVINGGIVING) clauses in the statement

***See Notes***See Notes

Page 28: Basic COBOL Statements

28

Arithmetic Statements – ROUNDEDROUNDED and ON SIZE ERRORON SIZE ERROR

WORKING-STORAGE SECTION. 01 WORK-FIELDS.

05 ITEM-1 PIC S9(5)V99 VALUE 85.56. 05 ITEM-1 PIC S9(5)V99 VALUE 85.56. 05 RESULT PIC S9(6) VALUE 100.05 RESULT PIC S9(6) VALUE 100.

PROCEDURE DIVISION. …

ADD ITEM-1 TO RESULT. ADD ITEM-1 TO RESULT.

MOVE 100 TO RESULT.MOVE 100 TO RESULT.

ADD ITEM-1 TO RESULT ROUNDED. ADD ITEM-1 TO RESULT ROUNDED.

MOVE 140156.33 TO ITEM-1.MOVE 140156.33 TO ITEM-1. MOVE 900000 TO RESULT.MOVE 900000 TO RESULT. ADD ITEM-1 TO RESULT ROUNDED. ADD ITEM-1 TO RESULT ROUNDED.

MOVE 900000 TO RESULT.MOVE 900000 TO RESULT.

ADD ITEM-1 TO RESULTADD ITEM-1 TO RESULT ON SIZE ERROR MOVE 0 TO SUM ON SIZE ERROR MOVE 0 TO SUM DISPLAY '** ON SIZE ERROR **'.DISPLAY '** ON SIZE ERROR **'.

Value: 185 Value: 185

Value: 186Value: 186The ROUNDED phrase allows you to specify rounding up to the nearest low-order decimal digit of precision. This means that ROUNDEDROUNDED adds 1 to the absolute value of the low-order digit of the result variable IF IF the absolute value of the next least significant digit of the intermediateintermediate variable value is >= to 5.

Value: 040156 Value: 040156

Value: 000000Value: 000000

Page 29: Basic COBOL Statements

29

Arithmetic Statements – SUBTRACTSUBTRACT

WORKING-STORAGE SECTION. 01 WORK-FIELDS.

05 ITEM-1 PIC S9(3)V99 VALUE 85.52. 05 ITEM-1 PIC S9(3)V99 VALUE 85.52.

05 ITEM-2 PIC S9(3)V99 VALUE 2.34. 05 ITEM-2 PIC S9(3)V99 VALUE 2.34.

05 DIFFERENCE PIC S9(5)V99 VALUE 0. 05 DIFFERENCE PIC S9(5)V99 VALUE 0. PROCEDURE DIVISION.

SUBTRACT ITEM-1, ITEM-2 FROM DIFFERENCE ROUNDEDSUBTRACT ITEM-1, ITEM-2 FROM DIFFERENCE ROUNDED

ON SIZE ERROR MOVE 0 TO DIFFERENCEON SIZE ERROR MOVE 0 TO DIFFERENCE

END-SUBTRACTEND-SUBTRACT

SUBTRACT ITEM-1 FROM ITEM-2 GIVING DIFFERENCE ROUNDEDSUBTRACT ITEM-1 FROM ITEM-2 GIVING DIFFERENCE ROUNDED

ON SIZE ERROR MOVE 0 TO DIFFERENCEON SIZE ERROR MOVE 0 TO DIFFERENCE

DISPLAY '** ON SIZE ERROR **'DISPLAY '** ON SIZE ERROR **'

END-SUBTRACTEND-SUBTRACT

Format 1Format 1 Subtracts all minuends from the sumSubtracts all minuends from the sum

Format 2Format 2 The values of all operands preceding the word GIVING are added together, and the The values of all operands preceding the word GIVING are added together, and the

sum is subtracted from the difference (in the above)sum is subtracted from the difference (in the above) None of the values in the operands preceding GIVING are changedNone of the values in the operands preceding GIVING are changed

Note: There is a Format 3: SUBTRACT CORRESPONDINGSUBTRACT CORRESPONDING

RoundedRounded Rounds to the decimal digits in the PIC Rounds to the decimal digits in the PIC

clauseclause

ON SIZE ERRORON SIZE ERROR Allows you to handle arithmetic Allows you to handle arithmetic

overflow conditions with imperative overflow conditions with imperative statements.statements.

Additional note: Additional note: You can substitute a numeric literal for the variables in the SUBTRACTSUBTRACT and FROMFROM (but not GIVINGGIVING) clauses in the statement

Page 30: Basic COBOL Statements

30

Arithmetic Statements – MULTIPLYMULTIPLY

WORKING-STORAGE SECTION. 01 INPUT-FIELDS.

05 ITEM-1 05 ITEM-1 PIC S9(3)V99 VALUE 85.52. PIC S9(3)V99 VALUE 85.52.

05 ITEM-2 05 ITEM-2 PIC S9(3)V99 VALUE 2.34. PIC S9(3)V99 VALUE 2.34.

05 ITEM-3 05 ITEM-3 PIC S9(3)V99 VALUE 6.01. PIC S9(3)V99 VALUE 6.01.

05 RESULT 05 RESULT PIC S9(5)V99. PIC S9(5)V99. PROCEDURE DIVISION.

MULTIPLY ITEM-1 BY ITEM-3 ROUNDEDMULTIPLY ITEM-1 BY ITEM-3 ROUNDED

ON SIZE ERROR MOVE 0 TO DIFFERENCEON SIZE ERROR MOVE 0 TO DIFFERENCE

END-MULTIPLYEND-MULTIPLY

MULTIPLY ITEM-1 BY ITEM-2 GIVING RESULT ROUNDEDMULTIPLY ITEM-1 BY ITEM-2 GIVING RESULT ROUNDED

ON SIZE ERROR MOVE 0 TO DIFFERENCEON SIZE ERROR MOVE 0 TO DIFFERENCE

DISPLAY '** ON SIZE ERROR **'DISPLAY '** ON SIZE ERROR **'

END-MULTIPLYEND-MULTIPLY

Format 1Format 1 The values of the operand preceding the word BY is multiplied by the operand after The values of the operand preceding the word BY is multiplied by the operand after

the word BYthe word BY Format 2Format 2

The value of the operand after the word The value of the operand after the word GIVINGGIVING is replaced by the multiplication of is replaced by the multiplication of ITEM-1 BY ITEM-2ITEM-1 BY ITEM-2

None of the values in the operands preceding None of the values in the operands preceding GIVINGGIVING are changed are changed

Page 31: Basic COBOL Statements

31

Arithmetic Statements – DIVIDE DIVIDE – Common Usage and Formats

WORKING-STORAGE SECTION. 01 INPUT-FIELDS.

05 ITEM-1 05 ITEM-1 PIC S9(3)V99 VALUE 85.52. PIC S9(3)V99 VALUE 85.52.

05 ITEM-2 05 ITEM-2 PIC S9(3)V99 VALUE 2.34. PIC S9(3)V99 VALUE 2.34.

05 ITEM-3 05 ITEM-3 PIC S9(3)V99 VALUE 6.01. PIC S9(3)V99 VALUE 6.01.

05 RESULT 05 RESULT PIC S9(5)V99. PIC S9(5)V99. PROCEDURE DIVISION.

DIVIDE ITEM-1 INTO ITEM-3 ROUNDEDDIVIDE ITEM-1 INTO ITEM-3 ROUNDED

ON SIZE ERROR MOVE 0 TO DIFFERENCEON SIZE ERROR MOVE 0 TO DIFFERENCE

END-DIVIDEEND-DIVIDE

DIVIDE ITEM-1 INTO ITEM-2 GIVING RESULT ROUNDEDDIVIDE ITEM-1 INTO ITEM-2 GIVING RESULT ROUNDED

ON SIZE ERROR MOVE 0 TO DIFFERENCEON SIZE ERROR MOVE 0 TO DIFFERENCE

DISPLAY '** ON SIZE ERROR **'DISPLAY '** ON SIZE ERROR **'

END-DIVIDEEND-DIVIDE

DIVIDE ITEM-1 BY ITEM-3 ROUNDEDDIVIDE ITEM-1 BY ITEM-3 ROUNDED

REMAINDER ITEM-3REMAINDER ITEM-3

END-DIVIDEEND-DIVIDE

DIVIDE ITEM-1 INTO ITEM-2 GIVING RESULT ROUNDEDDIVIDE ITEM-1 INTO ITEM-2 GIVING RESULT ROUNDED

REMAINDER ITEM-3REMAINDER ITEM-3

END-DIVIDEEND-DIVIDE

Five separate Formats for Five separate Formats for DIVIDE DIVIDE (see Slide Notes)(see Slide Notes)

RoundedRounded Rounds to the decimal digits in the PIC Rounds to the decimal digits in the PIC

clauseclause

ON SIZE ERRORON SIZE ERROR Allows you to handle arithmetic overflow Allows you to handle arithmetic overflow

conditions with imperative statements.conditions with imperative statements.

Additional note: Additional note: You can substitute a numeric literal for the variables in the DIVIDE, BYDIVIDE, BY and INTOINTO, (but not GIVINGGIVING) clauses in the statement

Page 32: Basic COBOL Statements

32

Arithmetic Statements – COMPUTECOMPUTE

WORKING-STORAGE SECTION. …

01 INPUT-FIELDS.

05 ITEM-1 05 ITEM-1 PIC S9(3)V99 VALUE 85.52. PIC S9(3)V99 VALUE 85.52.

05 ITEM-2 05 ITEM-2 PIC S9(3)V99 VALUE 2.34. PIC S9(3)V99 VALUE 2.34.

05 ITEM-3 05 ITEM-3 PIC S9(3)V99 VALUE 6.01. PIC S9(3)V99 VALUE 6.01.

05 RESULT 05 RESULT PIC S9(5)V99. PIC S9(5)V99. PROCEDURE DIVISION.

COMPUTE RESULT ROUNDED = COMPUTE RESULT ROUNDED =

(ITEM-1 * ITEM-2 / ITEM-3).(ITEM-1 * ITEM-2 / ITEM-3).

The COMPUTECOMPUTE statement assigns the value of an arithmetic (think algebraic) expression to one or more data items.

It allows you to combine arithmetic operations without the restrictions on receiving data items that the rules for the ADD, SUBTRACT, MULTIPLY, ADD, SUBTRACT, MULTIPLY, and DIVIDEDIVIDE statements impose.

When you need to combine arithmetic operations, using the COMPUTE statement may be more efficient than writing a series of separate arithmetic statements.

You may use any of the arithmetic operators shown on the next slide inside a compute statement

Additionally, you can combine COMPUTECOMPUTE with COBOL intrinsic functions

Note:Note: Blanks (the white space) between elements Blanks (the white space) between elements of your equation are significant with of your equation are significant with COMPUTE. COMPUTE.

For exampleFor example:: Compute celsius rounded =Compute celsius rounded = (5/9) * (fahrenheit - 32).(5/9) * (fahrenheit - 32). --- will not work --- will not work

Compute celsius rounded =Compute celsius rounded = ( 5 / 9 ) * (fahrenheit - 32).( 5 / 9 ) * (fahrenheit - 32). --- will work --- will work

Page 33: Basic COBOL Statements

33

COMPUTECOMPUTE Arithmetic Operators

Use the above arithmetic operators to in your COMPUTECOMPUTE statements The operations proceed as follows:

Unary Operators Multiplication/Division/Exponentiation Addition/Subtraction

… from left to right within the COMPUTECOMPUTE – and following the order of parenthesis

Thus, it's always a good idea to force an explicit arithmetic order of precedence using parenthesis in COMPUTECOMPUTE statements These two statements are not algebraically equivalent:

COMPUTE RESULT ROUNDED = COMPUTE RESULT ROUNDED =

(ITEM-1 * ITEM-2 + ITEM-3).(ITEM-1 * ITEM-2 + ITEM-3).

COMPUTE RESULT ROUNDED = COMPUTE RESULT ROUNDED =

(ITEM-1 * (ITEM-2 + ITEM-3)).(ITEM-1 * (ITEM-2 + ITEM-3)).

Page 34: Basic COBOL Statements

34

Intermediate Results of Fixed Point MathIntermediate Results of Fixed Point Math

From the IBM Enterprise COBOL Programmer's Guide - Document Number: SC23-8529-00 The compiler handles arithmetic statements as a succession of operations performed according to

operator precedence, and sets up intermediate fields to contain the results of those operations. The compiler uses algorithms to determine the number of integer and decimal places to reserve. Intermediate results are possible in the following cases:

In an ADD or SUBTRACT statement that contains more than one operand immediately after the verb In a COMPUTE statement that specifies a series of arithmetic operations or multiple result fields In an arithmetic expression contained in a conditional statement or in a reference-modification specification In an ADD, SUBTRACT, MULTIPLY, or DIVIDE statement that uses the GIVING option and multiple result fields In a statement that uses an intrinsic function as an operand

The precision of intermediate results also depends on whether you compile using the default option ARITH(COMPAT) or using ARITH(EXTEND)

Net:Net: Because of the effect of the intermediate results on your arithmetic calculations can produce incorrect

results (mostly truncation errors) And because the above list is a lot to remember (and is actually only the entry point into the topic)! You can – and should follow these simple rules-of-thumb:

Be particularly careful to define your numeric datatypes to the precision necessary for your requirements When using literals in your calculations always add the necessary decimal digits of precision to them, in order to

force the compiler to create intermediate results to your level of requirements

Example:Example: Instead of: COMPUTE FIELD-1 ROUNDED = 100 * (32.78 / 1000).COMPUTE FIELD-1 ROUNDED = 100 * (32.78 / 1000).

Include decimal places in your literals:

COMPUTE FIELD-1 ROUNDED = 100.000 * (32.78 / 1000.000).COMPUTE FIELD-1 ROUNDED = 100.000 * (32.78 / 1000.000).

Page 35: Basic COBOL Statements

35

Lab Assignment

From the course workshop documents, do the following labs – create and debug COBOL program that calculates simple interest based on the following variables

amount PIC 9(7)V99.principal PIC 9(7)V99.interest PIC 9(2)V99.nbrYears PIC 9(4) COMP.

//Business logic – in pseudo-code.//Initialize values

amount = 0;principal = 10000.01;interest = .05;nbrYears = 10;

//Invoke simple interest calculation functioncalculateSimpleInterest();

end

function calculateSimpleInterest()amount = principal * (1 + (nbrYears * interest));

endend

Page 36: Basic COBOL Statements

36

Unit

Topics:Topics:

COBOL General Language COBOL General Language RulesRules

Assignment Statements and Internal Data Representation

Math Operations

Conditional LogicConditional Logic

Transfer of control

COBOL Looping Constructs

Sequential File Processing Patterns

Java and .NET Equivalents

Page 37: Basic COBOL Statements

37

COBOL Conditional Expressions

Two statement options:IF/ELSEIF/ELSEEVALUATEEVALUATE statement

Both useful – and have many language patterns and options (you'll see )

In general: Use IFIF for coding:

Simple expressions Conditional statements with tests against multiple fields Complex statements – with tests against multiple fields

Use EVALUATEEVALUATE for: Implementing "decision table" logic Coding statements with multiple tests against a single field

Let's take a close look at both statements

See Slide NotesSee Slide Notes

Page 38: Basic COBOL Statements

38

Conditional Statements – IF Statement OverviewConditional Statements – IF Statement Overview

IF statement has two operational modes: Alphanumeric compare:Alphanumeric compare:

On variables of type:– PIC XPIC X– PIC APIC A– Group data itemsGroup data items– Alphanumeric literal

EBCDIC (or ASCII) value "byte-for-byte" comparison

– Comparison proceeds from Left-to-Right

– Alphanumeric range ( < or > ) is based on the platform's collating sequence

Shorter fields are padded with spaces (HEX '40HEX '40') to length of longer variable

– Regardless of which side of the IF statement is shorter/longer

Numeric comparison:Numeric comparison: On variables of type PIC 9PIC 9 or a numeric literal Algebraic compareAlgebraic compare Decimal positions automatically aligned

Note that overall, the IF statement comparison values must be "data type compatible"

IFIFconditioncondition

THENTHENStatementStatement

BlockBlock

ELSEELSEStatementStatement

BlockBlock

END-IFEND-IF

Page 39: Basic COBOL Statements

39

IF Statement ExamplesIF POLICY-OVERDUE-DAYS > 90       ADD +100 TO AMT-DUEEND-IF_____________________________________________________________________

IF EMPLOYEE-SALARY-TYPE = "H"         PERFORM 400-PROCESS-HOURLY-PAYELSE       IF   EMPLOYEE-SALARY-TYPE = "S"             PERFORM 400-PROCESS-SALARIED-PAY       ELSE             MOVE "***" TO EMPLOYEE-SALARY-TYP

ADD +1 TO ERRORS-FOUND-KTR       END-IFEND-IF_____________________________________________________________________

IF HOURS-WORKED > 40            IF HOURLY-EMPLOYEE = "Y"                        IF NO-ERRORS-FOUND                                    PERFORM 900-CALCULATE-HOURLY-OT                        END-IF            END-IFEND-IF_____________________________________________________________________ IF HOURS-WORKED > 40 AND      HOURLY-EMPLOYEE = "Y" AND      NO-ERRORS-FOUND             PERFORM 900-CALCULATE-HOURLY-OTEND-IF

Simple IFIF - No ELSEELSE

IF/ELSEIF/ELSENote – matching END-IF END-IF for each

IF/ELSEIF/ELSE

"Nested" IF/ELSEIF/ELSE

Nested IF/ELSEIF/ELSE refactored as IFIF with ANDAND connectors

Note – only one END-IFEND-IF

Page 40: Basic COBOL Statements

40

COBOL Conditional Statements – IF Statement Overview

Condition may be simple or complex (> 1 simple condition) There are five simple conditions, which have a truth value of

either true or false: 1. Class condition:

ALPHABETIC, NUMERIC, ALPHABETIC-UPPERALPHABETIC, NUMERIC, ALPHABETIC-UPPER

2. Condition-name condition: 88-LEVEL Data Items88-LEVEL Data Items

3. Relation condition (value-based comparisons)4. Sign condition

POSITIVE, NEGATIVE, ZEROPOSITIVE, NEGATIVE, ZERO

5. Switch-status condition – used with SPECIAL NAMESSPECIAL NAMES (rare)

Use Content-Assist (Ctrl/SpacebarCtrl/Spacebar) to view options A complex conditioncomplex condition is formed by combining simple

conditions, combined conditions, and/or complex conditions with logical operators, or negating these conditions with logical negation: ANDAND OROR NOTNOT

If complex condition, comparisons proceed from Left-to-Right: But you can (and most of the time should) specify your own

comparison operation precedence by surrounding separate conditions with parenthesis to make the logic apparent To humans who read/maintain your code, as well as to the compiler See NotesSee Notes

Page 41: Basic COBOL Statements

41

IF/ELSE IF/ELSE – Examples – and See Slide Notes

FILE SECTION…01 OUT-REC PIC X(80).…WORKING-STORAGE SECTION. 77 ITEM-1 PIC X(12).77 ITEM-1 PIC X(12).7777 ITEM-2 PIC X(15). ITEM-2 PIC X(15).7777 ITEM-3 PIC 9(05). ITEM-3 PIC 9(05).

88 VALID-ITEM 88 VALID-ITEM VALUES ARE 11111, 22222.VALUES ARE 11111, 22222.…PROCEDURE DIVISION. IF ITEM-1 > "10" IF ITEM-1 > "10"

MOVE "X" TO ITEMB MOVE "X" TO ITEMB

ELSE ELSE

PERFORM PROC-APERFORM PROC-A

END-IFEND-IF

IF ITEM-1 > "10"IF ITEM-1 > "10"

IF ITEM-1 = ITEM-2IF ITEM-1 = ITEM-2

ADD 1 TO ITEM-3ADD 1 TO ITEM-3

MOVE ALL "X" TO OUT-RECMOVE ALL "X" TO OUT-REC

END-IFEND-IF

MOVE "X" TO ITEM-2MOVE "X" TO ITEM-2

END-IFEND-IF

IF ITEM-1 NUMERIC IF ITEM-1 NUMERIC

MOVE ITEM-1 TO ITEM-3MOVE ITEM-1 TO ITEM-3

END-IFEND-IF

IF VALID-ITEM IF VALID-ITEM

MOVE ITEM-2 TO ITEM-1MOVE ITEM-2 TO ITEM-1

ELSE ELSE

MOVE FUNCTION UPPER-CASE(ITEM-2) MOVE FUNCTION UPPER-CASE(ITEM-2)

TO ITEM-1TO ITEM-1

END-IFEND-IF

IF ( ITEM-3 IS POSITIVE ) AND IF ( ITEM-3 IS POSITIVE ) AND ( ITEM-1 NOT > ITEM-2 ) ( ITEM-1 NOT > ITEM-2 ) THEN THEN IF ITEM-3 = 22222 IF ITEM-3 = 22222

THEN DISPLAY "22222-RECORD" THEN DISPLAY "22222-RECORD"

ELSE DISPLAY "11111-RECORD" ELSE DISPLAY "11111-RECORD"

END-IF END-IF

ELSE DISPLAY "BAD RECORD" ELSE DISPLAY "BAD RECORD"

END-IF END-IF

IF NOT (ITEM-3 < 10 OR ITEM-3 > 500) IF NOT (ITEM-3 < 10 OR ITEM-3 > 500) AND ITEM-1 <= "Z" AND ITEM-1 <= "Z"

THEN DISPLAY "Done"THEN DISPLAY "Done"

END-IFEND-IF

SimpleSimpleRelationRelationConditionCondition

SimpleSimpleRelationRelationConditionCondition

ComplexComplexNested IFNested IFRelationRelationConditionCondition

ComplexComplexNested IFNested IFRelationRelationConditionCondition

ClassClassConditionCondition

ClassClassConditionCondition

Condition-NameCondition-NameConditionCondition

Condition-NameCondition-NameConditionCondition

ComplexComplexNested IFNested IFConditionConditionCombingCombingOR/ANDOR/AND

ComplexComplexNested IFNested IFConditionConditionCombingCombingOR/ANDOR/AND

ComplexComplexNested IFNested IFRelationRelationConditionCondition

ComplexComplexNested IFNested IFRelationRelationConditionCondition

Page 42: Basic COBOL Statements

42

Implied IF Condition Statements

When referring to the same field on both sides of a compound condition, you do not have to repeat the variable name

Example:IF EMPLOYEE-ID > 20 IF EMPLOYEE-ID > 20 AND EMPLOYEE-ID < 3000AND EMPLOYEE-ID < 3000

Can be coded as:

IF EMPLOYEE-ID > 2000 AND < 3000IF EMPLOYEE-ID > 2000 AND < 3000

There is no hard and fast rule (or even rule-of-thumb) on this coding idiom. Pluses:

Creates more compact easily code Can be more easily readable

Minuses Written semantics are not as exact and

explicit– Many modern languages do not permit this

Might be misunderstood if merely browsing or scanning code

IF ITEM-1 NUMERIC AND > 10000IF ITEM-1 NUMERIC AND > 10000

MOVE ITEM-1 TO ITEM-3MOVE ITEM-1 TO ITEM-3

END-IFEND-IF

IF ITEM-2 = "AABBCC" OR "AACCDD" IF ITEM-2 = "AABBCC" OR "AACCDD"

OR "AADDEE"OR "AADDEE"

MOVE ITEM-2 TO ITEM-1MOVE ITEM-2 TO ITEM-1

ELSE ELSE

MOVE FUNCTION UPPER-CASE(ITEM-2) MOVE FUNCTION UPPER-CASE(ITEM-2)

TO ITEM-1TO ITEM-1

END-IFEND-IF

IF NOT (ITEM-3 < 10 OR > 500) AND IF NOT (ITEM-3 < 10 OR > 500) AND ITEM-1 <= "Z" ITEM-1 <= "Z"

THEN DISPLAY "Done"THEN DISPLAY "Done"

END-IFEND-IF

Examples of implied IF statement conditions

Page 43: Basic COBOL Statements

43

Bypassing Conditional Logic (NEXT SENTENCENEXT SENTENCE and CONTINUECONTINUE)

There are two standard ways for you to skip over logic in a complex IF statement that you must avoid as per business requirements

Code (after the if condition) either: NEXT SENTENCENEXT SENTENCE – which branches to

the next sequential statement after an ending period…or…

CONTINUECONTINUE – which branches to the next sequential statement after an ending period – OR the IF statement's scope terminator.

An important distinction – to be sure Because NEXT SENTENCE is looking for

the next physical period in the source – and scope-terminators/indentation mean nothing whatsoever to it, you will probably want to use: CONTINUE – if you're coding style is to use scope-delimiters (a best practice).

Note also that, when you're coding new programs this is not as problematic as when you are maintaining existing COBOL applications

What if I want to bypass more than the current logic statement block?

See Slide NotesSlide Notes

IF ITEM-2 ALPHABETIC-UPPER IF ITEM-2 ALPHABETIC-UPPER

NEXT SENTENCENEXT SENTENCEELSE ELSE

MOVE FUNCTION UPPER-CASE(ITEM-2)TO ITEM-1MOVE FUNCTION UPPER-CASE(ITEM-2)TO ITEM-1

ADD +10 TO AMOUNT-SUB-TOTALADD +10 TO AMOUNT-SUB-TOTAL

END-IFEND-IF

ADD +1 TO REC-KTRADD +1 TO REC-KTR

ADD REC-TOTAL TO WS-TOTAL-CLAIMS-PYMNTSADD REC-TOTAL TO WS-TOTAL-CLAIMS-PYMNTS

WRITE OUTPUT-RECORD FROM WS-OUT-REC.WRITE OUTPUT-RECORD FROM WS-OUT-REC.

GOBACK. GOBACK.

IF ITEM-2 ALPHABETIC-UPPER IF ITEM-2 ALPHABETIC-UPPER

CONTINUECONTINUEELSE ELSE

MOVE FUNCTION UPPER-CASE(ITEM-2)TO ITEM-1MOVE FUNCTION UPPER-CASE(ITEM-2)TO ITEM-1

ADD +10 TO AMOUNT-SUB-TOTALADD +10 TO AMOUNT-SUB-TOTAL

END-IFEND-IF

ADD +1 TO REC-KTRADD +1 TO REC-KTR

ADD REC-TOTAL TO WS-TOTAL-CLAIMS-PYMNTSADD REC-TOTAL TO WS-TOTAL-CLAIMS-PYMNTS

WRITE OUTPUT-RECORD FROM WS-OUT-REC.WRITE OUTPUT-RECORD FROM WS-OUT-REC.

GOBACK. GOBACK.

Page 44: Basic COBOL Statements

44

Conditional Statements – Conditional Statements – EVALUATEEVALUATE Statement Statement EVALUATEEVALUATEStatementStatement

END-EVALUATEEND-EVALUATE

WHENWHENconditioncondition

WHENWHENOTHEROTHER

TRUETRUEStatementStatement

BlockBlock

WHENWHENconditioncondition

TRUETRUEStatementStatement

BlockBlock

TRUETRUEStatementStatement

BlockBlock……

The EVALUATEEVALUATE statement is COBOL's version of the (in other programming languages) "case" or "switch) statement.

EVALUATEEVALUATE provides a shorthand notation for a series of nested IFIF statements.

When your program has to test a single variable for more than two values, EVALUATEEVALUATE is probably a better choice than nest IFIF See next slide

EVALUATEEVALUATE parses a variable value WHEN is used as the condition expression

You can a single WHENWHEN condition You can use multiple WHENWHEN statements when

several conditions lead to the same processing action

You can use a WHENWHEN <value> THRUTHRU <value> phrase to easily code several conditions in a range of values

You can specify "TRUETRUE" or "FALSEFALSE" as the testing criteria – and can combine with "ALSOALSO"

Page 45: Basic COBOL Statements

45

EVALUATE versus Nested IF Statement Comparison

IF MARITAL-CODE = "M" THEN IF MARITAL-CODE = "M" THEN

ADD 2 TO PEOPLE-COUNT ADD 2 TO PEOPLE-COUNT

ELSE ELSE

IF MARITAL-CODE = "S" IF MARITAL-CODE = "S"

OR MARITAL-CODE = "D" OR MARITAL-CODE = "D"

OR MARITAL-CODE = "W" OR MARITAL-CODE = "W"

THEN ADD 1 TO PEOPLE-COUNT THEN ADD 1 TO PEOPLE-COUNT

END-IF END-IF

END-IF END-IF

EVALUATE MARITAL-CODE EVALUATE MARITAL-CODE

WHEN "M" ADD 2 TO PEOPLE-COUNT WHEN "M" ADD 2 TO PEOPLE-COUNT

WHEN "S" WHEN "S"

WHEN "D" WHEN "D"

WHEN "W" ADD 1 TO PEOPLE-COUNT WHEN "W" ADD 1 TO PEOPLE-COUNT

END-EVALUATE END-EVALUATE

Example 2Example 2

Example 1Example 1IF CARPOOL-SIZE = 1 THEN IF CARPOOL-SIZE = 1 THEN

MOVE "SINGLE" TO PRINT-CARPOOL-STATUS MOVE "SINGLE" TO PRINT-CARPOOL-STATUS

ELSE ELSE

IF CARPOOL-SIZE = 2 THEN IF CARPOOL-SIZE = 2 THEN

MOVE "COUPLE" TO PRINT-CARPOOL-STATUS MOVE "COUPLE" TO PRINT-CARPOOL-STATUS

ELSE ELSE

IF CARPOOL-SIZE >= 3 and IF CARPOOL-SIZE >= 3 and

CARPOOL-SIZE <= 6 THEN CARPOOL-SIZE <= 6 THEN

MOVE "SMALL GRP" TO PRINT-CARPOOL-STATUS MOVE "SMALL GRP" TO PRINT-CARPOOL-STATUS

ELSE ELSE

MOVE "BIG GRP" TO PRINT-CARPOOL-STATUS MOVE "BIG GRP" TO PRINT-CARPOOL-STATUS

END-IF END-IF

END-IF END-IF

END-IFEND-IF

EVALUATE CARPOOL-SIZE EVALUATE CARPOOL-SIZE

WHEN 1 WHEN 1

MOVE "SINGLE" TO PRINT-CARPOOL-STATUS MOVE "SINGLE" TO PRINT-CARPOOL-STATUS

WHEN 2 WHEN 2

MOVE "COUPLE" TO PRINT-CARPOOL-STATUS MOVE "COUPLE" TO PRINT-CARPOOL-STATUS

WHEN 3 THRU 6 WHEN 3 THRU 6

MOVE "SMALL GRP" TO PRINT-CARPOOL STATUS MOVE "SMALL GRP" TO PRINT-CARPOOL STATUS

WHEN OTHER WHEN OTHER

MOVE "BIG GRP" TO PRINT-CARPOOL STATUS MOVE "BIG GRP" TO PRINT-CARPOOL STATUS

END-EVALUATE END-EVALUATE

Page 46: Basic COBOL Statements

46

"True ALSO True""True ALSO True" means that both conditions in the WHEN clause must be true means that both conditions in the WHEN clause must be true to take the WHEN pathto take the WHEN path

Conditional Statements – EVALUATE EVALUATE – Complex ExamplesFILE SECTIONFILE SECTION……01 OUT-REC PIC X(80).01 OUT-REC PIC X(80).……Working-Storage Section. Working-Storage Section. 01 Age PIC 999. 01 Age PIC 999. 01 Sex PIC X. 01 Sex PIC X. 01 Description PIC X(15). 01 Description PIC X(15). 01 A PIC 999. 01 A PIC 999. 01 B PIC 9999. 01 B PIC 9999. 01 C PIC 9999. 01 C PIC 9999. 01 D PIC 9999. 01 D PIC 9999. 01 E PIC 99999. 01 E PIC 99999. 01 F PIC 999999. 01 F PIC 999999.

Evaluate True Also True Evaluate True Also True When Age < 13 Also Sex = "M" When Age < 13 Also Sex = "M" Move "Young Boy" To Description Move "Young Boy" To Description When Age < 13 Also Sex = "F" When Age < 13 Also Sex = "F" Move "Young Girl" To Description Move "Young Girl" To Description When Age > 12 And Age < 20 Also Sex = "M" When Age > 12 And Age < 20 Also Sex = "M" Move "Teenage Boy" To Description Move "Teenage Boy" To Description When Age > 12 And Age < 20 Also Sex = "F" When Age > 12 And Age < 20 Also Sex = "F" Move "Teenage Girl" To Description Move "Teenage Girl" To Description When Age > 19 Also Sex = "M" When Age > 19 Also Sex = "M" Move "Adult Man" To Description Move "Adult Man" To Description When Age > 19 Also Sex = "F" When Age > 19 Also Sex = "F" Move "Adult Woman" To Description Move "Adult Woman" To Description When Other When Other Move "Invalid Data" To Description Move "Invalid Data" To Description

End-Evaluate End-Evaluate

Evaluate True Also True Evaluate True Also True When A + B < 10 Also C = 10 When A + B < 10 Also C = 10

Move "Case 1" To Description Move "Case 1" To Description When A + B > 50 Also C = ( D + E ) / F When A + B > 50 Also C = ( D + E ) / F

Move "Case 2" To Description Move "Case 2" To Description When Other When Other

Move "Case Other" To Description Move "Case Other" To Description End-Evaluate End-Evaluate

Page 47: Basic COBOL Statements

47

Lab Assignment

From the course workshop documents, do the following labs:1. Conditionals Lab

Page 48: Basic COBOL Statements

48

Unit

Topics:Topics:

COBOL General Language COBOL General Language RulesRules

Assignment Statements and Internal Data Representation

Math Operations

Conditional Logic

Transfer of controlTransfer of control

COBOL Looping Constructs

Sequential File Processing Patterns

Java and .NET Equivalents

Page 49: Basic COBOL Statements

49

Topic objectives

By the end of this unit you should - Understand how the PERFORM can be used to transfer control to block

of code contained in a paragraph or section.. Know how to use the PERFORM..THRU and the GO TO and understand

the restrictions placed on using them. Understand the difference between in-line and out-of-line Performs

Page 50: Basic COBOL Statements

50

COBOL Transfer of Control Options

Three keywords used to transfer control in traditional COBOLPERFORMPERFORM

Branches to the first statement in a block of code– Inline

– Or, organized in a labeled paragraph or section somewhere else in the PROCEDURE PROCEDURE DIVISIONDIVISION

At the end of the performed code, control is automatically returned to the next sequential instruction following PERFORMPERFORM

PERFORMPERFORM is a statement with a number of useful options and extensions

GO TOGO TO Unconditional branch to a labeled paragraph or section All statements are executed at that point in time – forward in the program

CALLCALL Invoke another COBOL program Pass parameters with a USINGUSING statement We will discuss CALLCALL in a future section of this course

Of the above three options: PERFORM PERFORM and CALL CALL are best practices for "structured programming" GO TO GO TO is not a best practice, but we will present it, as you will see many

examples of GO TO GO TO in production COBOL, and need to understand it

Page 51: Basic COBOL Statements

51

PERFORMPERFORM – External Paragraph or Section – External Paragraph or Section

Structured coding method of branching to – and returning from COBOL paragraphs or sections

With PERFORMPERFORM, the compiler automatically returns control to the "next sequential instruction" after the block of statements in the paragraph or section ends This makes the program's flow of control easy to read,

easy to understand and easy to maintain Less worry about "fall thru" logic

PERFORMPERFORM May be nested:

This is known as a "PERFORMPERFORM chain" – or a series of

PERFORMPERFORM and return branches controlled by the Operating System at run-time.

May NOT be recursive: In this example, within 200-OPEN-FILES200-OPEN-FILES you

may not PERFORM 100-HOUSEKEEPINGPERFORM 100-HOUSEKEEPING Does not depend on physical placement or ordering in

the source files: Although it can help from a read-ability standpoint

to PERFORM PERFORM paragraphs lower (down) in the program listing.

Allows you do "divide and conquer" the design and development of large complex applications.

Do not scope external paragraph PERFORM PERFORM with END-PERFORMEND-PERFORM

PROCEDURE DIVISION.PROCEDURE DIVISION.

PERFORM 100-HOUSEKEEPING.PERFORM 100-HOUSEKEEPING.

PERFORM 300-MAINLINE-RTN.PERFORM 300-MAINLINE-RTN.

PERFORM 500-CLEANUP.PERFORM 500-CLEANUP.

GOBACK.GOBACK.

100-HOUSEKEEPING.100-HOUSEKEEPING.

PERFORM 150-INITIALIZE-FIELDS.PERFORM 150-INITIALIZE-FIELDS.

PERFORM 200-OPEN-FILES.PERFORM 200-OPEN-FILES.

PERFORM 800-READ-RTN.PERFORM 800-READ-RTN.

150-INITIALIZE-FIELDS.150-INITIALIZE-FIELDS.

……

200-OPEN-FILES.200-OPEN-FILES.

……

300-MAINLINE-RTN.300-MAINLINE-RTN.

PERFORM 400-PROCESS-RECORD.PERFORM 400-PROCESS-RECORD.

PERFORM 700-WRITE-RTN.PERFORM 700-WRITE-RTN.

PERFORM 800-READ-RTN.PERFORM 800-READ-RTN.

400-PROCESS-RECORD.400-PROCESS-RECORD.

… …

500-CLEANUP.500-CLEANUP.

PERFORM 900-CLOSE-FILES.PERFORM 900-CLOSE-FILES.

……

700-WRITE-RTN.700-WRITE-RTN.

……

PROCEDURE DIVISION.PROCEDURE DIVISION.

PERFORM 100-HOUSEKEEPING.PERFORM 100-HOUSEKEEPING.

PERFORM 300-MAINLINE-RTN.PERFORM 300-MAINLINE-RTN.

PERFORM 500-CLEANUP.PERFORM 500-CLEANUP.

GOBACK.GOBACK.

100-HOUSEKEEPING.100-HOUSEKEEPING.

PERFORM 150-INITIALIZE-FIELDS.PERFORM 150-INITIALIZE-FIELDS.

PERFORM 200-OPEN-FILES.PERFORM 200-OPEN-FILES.

PERFORM 800-READ-RTN.PERFORM 800-READ-RTN.

150-INITIALIZE-FIELDS.150-INITIALIZE-FIELDS.

……

200-OPEN-FILES.200-OPEN-FILES.

……

300-MAINLINE-RTN.300-MAINLINE-RTN.

PERFORM 400-PROCESS-RECORD.PERFORM 400-PROCESS-RECORD.

PERFORM 700-WRITE-RTN.PERFORM 700-WRITE-RTN.

PERFORM 800-READ-RTN.PERFORM 800-READ-RTN.

400-PROCESS-RECORD.400-PROCESS-RECORD.

… …

500-CLEANUP.500-CLEANUP.

PERFORM 900-CLOSE-FILES.PERFORM 900-CLOSE-FILES.

……

700-WRITE-RTN.700-WRITE-RTN.

……

Page 52: Basic COBOL Statements

52

PERFORM THRUPERFORM THRU

One variation on PERFORMPERFORM is PERFORM … THRU PERFORM … THRU

PERFORM … THRU PERFORM … THRU allows you to explicitly mark & bound the end of the PERFORMPERFORM chain with a labeled paragraph

All of the procedural statements between: PERFORMPERFORM <paragraphName> and THRU THRU <paragraphName>

…are executed

The best practice is for the exit paragraph to have one COBOL reserved word in it: EXITEXIT This returns control to the next sequential

instruction in the perform chain

Technically, you could PERFORMPERFORM a COBOL paragraph THRUTHRU any other paragraph. However, this often leads to complex and unstructured code Difficult to understand and maintain

So the convention is to PERFORM THRUPERFORM THRU a single paragraph EXITEXIT (as shown)

PROCEDURE DIVISION.PROCEDURE DIVISION.

PERFORM 100-HOUSEKEEPING PERFORM 100-HOUSEKEEPING

THRU 100-EXIT.THRU 100-EXIT.

PERFORM 300-MAINLINE-RTNPERFORM 300-MAINLINE-RTN

THRU 300-EXIT.THRU 300-EXIT.

PERFORM 500-CLEANUPPERFORM 500-CLEANUP

THRU 500-EXIT.THRU 500-EXIT.

GOBACK.GOBACK.

100-HOUSEKEEPING.100-HOUSEKEEPING.

PERFORM 150-INITIALIZE-FIELDSPERFORM 150-INITIALIZE-FIELDS

THRU 150-EXIT.THRU 150-EXIT.

PERFORM 200-OPEN-FILES PERFORM 200-OPEN-FILES

THRU 200-EXIT.THRU 200-EXIT.

PERFORM 800-READ-RTN PERFORM 800-READ-RTN

THRU 800-EXIT.THRU 800-EXIT.

100-EXIT.100-EXIT.

EXIT.EXIT.

150-INITIALIZE-FIELDS.150-INITIALIZE-FIELDS.

……

150-EXIT.150-EXIT.

EXIT.EXIT.

200-OPEN-FILES.200-OPEN-FILES.

……

200-EXIT.200-EXIT.

EXIT.EXIT.

……

PROCEDURE DIVISION.PROCEDURE DIVISION.

PERFORM 100-HOUSEKEEPING PERFORM 100-HOUSEKEEPING

THRU 100-EXIT.THRU 100-EXIT.

PERFORM 300-MAINLINE-RTNPERFORM 300-MAINLINE-RTN

THRU 300-EXIT.THRU 300-EXIT.

PERFORM 500-CLEANUPPERFORM 500-CLEANUP

THRU 500-EXIT.THRU 500-EXIT.

GOBACK.GOBACK.

100-HOUSEKEEPING.100-HOUSEKEEPING.

PERFORM 150-INITIALIZE-FIELDSPERFORM 150-INITIALIZE-FIELDS

THRU 150-EXIT.THRU 150-EXIT.

PERFORM 200-OPEN-FILES PERFORM 200-OPEN-FILES

THRU 200-EXIT.THRU 200-EXIT.

PERFORM 800-READ-RTN PERFORM 800-READ-RTN

THRU 800-EXIT.THRU 800-EXIT.

100-EXIT.100-EXIT.

EXIT.EXIT.

150-INITIALIZE-FIELDS.150-INITIALIZE-FIELDS.

……

150-EXIT.150-EXIT.

EXIT.EXIT.

200-OPEN-FILES.200-OPEN-FILES.

……

200-EXIT.200-EXIT.

EXIT.EXIT.

…… See Slide NotesSee Slide Notes

Page 53: Basic COBOL Statements

53

Inline Inline PERFORMPERFORM

Another variation on PERFORMPERFORM is what's known as an "inline perform"

An inline PERFORMPERFORM allows you to encase COBOL statements and business logic within a structured statement block – which you can group or loop through (looping is the next topic, but Inline PERFORMPERFORM is often used to control loops.

PERFORMPERFORM <statement>

<statement>

END-PERFORM.END-PERFORM.

An in-line PERFORMPERFORM must be delimited by the END-PERFORMEND-PERFORM phrase.

PROCEDURE DIVISION.PROCEDURE DIVISION. PERFORM UNTIL END-OF-FILE PERFORM UNTIL END-OF-FILE

IF NOT END-OF-FILE IF NOT END-OF-FILE

PERFORM 800-READ-INPUT-FILEPERFORM 800-READ-INPUT-FILE

IF NOT END-OF-FILEIF NOT END-OF-FILE

MOVE INPUT-REC TO OUTPUT-RECMOVE INPUT-REC TO OUTPUT-REC

PERFORM 900-WRITE-RECORDPERFORM 900-WRITE-RECORD

ELSEELSE

MOVE HIGH-VALUES MOVE HIGH-VALUES

TO INPUT-RECTO INPUT-REC

PERFORM 1000-CLOSE-FILESPERFORM 1000-CLOSE-FILES

DISPLAY 'NORMAL EOJDISPLAY 'NORMAL EOJ

END-IFEND-IF

END-IFEND-IF

END-PERFORM.END-PERFORM.

……

PERFORM VARYING IDX PERFORM VARYING IDX

FROM 1 BY 1 UNTIL IDX > 100FROM 1 BY 1 UNTIL IDX > 100

MOVE REC-IN MOVE REC-IN

TO REC-TABLE(IDX)TO REC-TABLE(IDX)

END-PERFORM.END-PERFORM.

……

PROCEDURE DIVISION.PROCEDURE DIVISION. PERFORM UNTIL END-OF-FILE PERFORM UNTIL END-OF-FILE

IF NOT END-OF-FILE IF NOT END-OF-FILE

PERFORM 800-READ-INPUT-FILEPERFORM 800-READ-INPUT-FILE

IF NOT END-OF-FILEIF NOT END-OF-FILE

MOVE INPUT-REC TO OUTPUT-RECMOVE INPUT-REC TO OUTPUT-REC

PERFORM 900-WRITE-RECORDPERFORM 900-WRITE-RECORD

ELSEELSE

MOVE HIGH-VALUES MOVE HIGH-VALUES

TO INPUT-RECTO INPUT-REC

PERFORM 1000-CLOSE-FILESPERFORM 1000-CLOSE-FILES

DISPLAY 'NORMAL EOJDISPLAY 'NORMAL EOJ

END-IFEND-IF

END-IFEND-IF

END-PERFORM.END-PERFORM.

……

PERFORM VARYING IDX PERFORM VARYING IDX

FROM 1 BY 1 UNTIL IDX > 100FROM 1 BY 1 UNTIL IDX > 100

MOVE REC-IN MOVE REC-IN

TO REC-TABLE(IDX)TO REC-TABLE(IDX)

END-PERFORM.END-PERFORM.

……

Page 54: Basic COBOL Statements

54

Scope Terminators and Paragraph Names

You have seen that many of the COBOL statements can have Scope Terminators: END-IF END-READ END-COMPUTE …

This is actually a coding best practice

However, the last statement before the paragraph (or "exit paragraph") must end in a period.

100-HOUSEKEEPING.100-HOUSEKEEPING.

… …

IF ITEM-2 = "AABBCC" OR "AACCDD" IF ITEM-2 = "AABBCC" OR "AACCDD"

OR "AADDEE"OR "AADDEE"

MOVE ITEM-2 TO ITEM-1MOVE ITEM-2 TO ITEM-1

ELSE ELSE

MOVE ITEM-3 TO ITEM-1MOVE ITEM-3 TO ITEM-1

END-IFEND-IF

100-EXIT.100-EXIT.

EXIT.EXIT. This will not compile!This will not compile!

100-HOUSEKEEPING.100-HOUSEKEEPING.

… …

IF ITEM-2 = "AABBCC" OR "AACCDD" IF ITEM-2 = "AABBCC" OR "AACCDD"

OR "AADDEE"OR "AADDEE"

MOVE ITEM-2 TO ITEM-1MOVE ITEM-2 TO ITEM-1

ELSE ELSE

MOVE ITEM-3 TO ITEM-1MOVE ITEM-3 TO ITEM-1

END-IF.END-IF.

100-EXIT.100-EXIT.

EXIT.EXIT.

Type a period after END-IFType a period after END-IF

Page 55: Basic COBOL Statements

55

GO TOGO TO – Unconditional Transfer of Control – Unconditional Transfer of Control

GO TOGO TO branches to the paragraph or section label after the statement. With no automatic, compiler-managed return to

the next sequential instruction Ergo all subsequent statements "fall through"

This can create what is termed "spaghetti code" – which is typically

Difficult to read Very difficult to maintain and modify

The use of GO TOGO TO is universally denounced in the academic computing world And we agree – except for under one very key

and common design pattern (combining GO TOGO TO with PERFORM … THRUPERFORM … THRU)

Our "Best Practices" advice: Do not use GO TOGO TO in COBOL coding, for

transferring control EXCEPT under one conditionEXCEPT under one condition – when you are

using GO TOGO TO - for branching to the exit paragraph in a PERFORM … THRUPERFORM … THRU

This honors the Perform Chain and execution will not "fall through"

PROCEDURE DIVISION.PROCEDURE DIVISION.

PERFORM 100-HOUSEKEEPING PERFORM 100-HOUSEKEEPING

THRU 100-EXIT.THRU 100-EXIT.

PERFORM 300-MAINLINE-RTNPERFORM 300-MAINLINE-RTN

THRU 300-EXIT.THRU 300-EXIT.

GOBACK.GOBACK.

100-HOUSEKEEPING.100-HOUSEKEEPING.

PERFORM 200-OPEN-FILES PERFORM 200-OPEN-FILES

THRU 200-EXIT.THRU 200-EXIT.

PERFORM 800-READ-RTN PERFORM 800-READ-RTN

THRU 800-EXIT.THRU 800-EXIT.

IF END-OF-FILEIF END-OF-FILE

DISPLAY "END-OF-JOB"DISPLAY "END-OF-JOB"

PERFORM 900-CLOSE FILESPERFORM 900-CLOSE FILES

THRU 900-EXITTHRU 900-EXIT

GO TO 100-EXITGO TO 100-EXIT ELSEELSE

ADD +1 TO REC-KTRADD +1 TO REC-KTR

MOVE ZEROS TO AMOUNT-TOTMOVE ZEROS TO AMOUNT-TOT

END-IFEND-IF

Perform 300-INIT-FIELDS.Perform 300-INIT-FIELDS.

100-EXIT.100-EXIT.

EXIT.EXIT.

……

PROCEDURE DIVISION.PROCEDURE DIVISION.

PERFORM 100-HOUSEKEEPING PERFORM 100-HOUSEKEEPING

THRU 100-EXIT.THRU 100-EXIT.

PERFORM 300-MAINLINE-RTNPERFORM 300-MAINLINE-RTN

THRU 300-EXIT.THRU 300-EXIT.

GOBACK.GOBACK.

100-HOUSEKEEPING.100-HOUSEKEEPING.

PERFORM 200-OPEN-FILES PERFORM 200-OPEN-FILES

THRU 200-EXIT.THRU 200-EXIT.

PERFORM 800-READ-RTN PERFORM 800-READ-RTN

THRU 800-EXIT.THRU 800-EXIT.

IF END-OF-FILEIF END-OF-FILE

DISPLAY "END-OF-JOB"DISPLAY "END-OF-JOB"

PERFORM 900-CLOSE FILESPERFORM 900-CLOSE FILES

THRU 900-EXITTHRU 900-EXIT

GO TO 100-EXITGO TO 100-EXIT ELSEELSE

ADD +1 TO REC-KTRADD +1 TO REC-KTR

MOVE ZEROS TO AMOUNT-TOTMOVE ZEROS TO AMOUNT-TOT

END-IFEND-IF

Perform 300-INIT-FIELDS.Perform 300-INIT-FIELDS.

100-EXIT.100-EXIT.

EXIT.EXIT.

……

Page 56: Basic COBOL Statements

56

Transfer of Control Best PracticesTransfer of Control Best Practices

We will cover structured COBOL programming and logic patterns and design in one of the upcoming units, but for now, consider the following:

Structure your program as a chain of PERFORMPERFORM THRUTHRU paragraphs

Within the paragraphs code anything you need to satisfy your business logic requirements, including: CALLCALLs to external programs – CALLCALL is covered in an upcoming unit Nested PERFORMPERFORM Inline PERFORMPERFORM Sequence and conditional logic GO TOGO TO – BUT ONLY GO TOGO TO a PERFORM THRUPERFORM THRU paragraph EXITEXIT

Try not to use COBOL SECTIONSECTIONs Within COBOL SECTIONSECTIONs – COBOL paragraphs are considered at the level of

statements – blocks of code where fall throughfall through will occur The only time you will need a COBOL SECTIONSECTION is when you're programming is invoking

the COBOL SORTSORT verb (which is tied to INPUT and OUTPUT SORTSORT SECTIONSECTIONs)

Page 57: Basic COBOL Statements

57

Unit

Topics:Topics:

COBOL General Language COBOL General Language RulesRules

Assignment Statements and Internal Data Representation

Math Operations

Conditional Logic

Transfer of control

COBOL Looping ConstructsCOBOL Looping Constructs

Sequential File Processing Patterns

Java and .NET Equivalents

Page 58: Basic COBOL Statements

58

Topic objectives

By the end of this unit you should - Be able to use the PERFORM..TIMES. Understand how the PERFORM..UNTIL works and be able to use it to

implement while or do/repeat loops. Be able to use PERFORM..VARYING to implement counting iteration

such as that implemented in other languages by the for construct.

Page 59: Basic COBOL Statements

59

COBOL Looping Options

There are three COBOL programming ways to loop: GO TO <paragraphName>GO TO <paragraphName> combined with an IFIF condition that ends the loop:

Unstructured – creates complex, un-maintainable code NOT a best practice – hence will not be covered

PERFORM <paragraphName> n TIMESPERFORM <paragraphName> n TIMES Structured and simple to understand But only applicable in cases where the number of loop iterations is known at design time

PERFORM <paragraphName> UNTILPERFORM <paragraphName> UNTIL a condition is met Structured ("Good") Can be used when the number of loop iterations is variable or known

Net: Use PERFORM <paragraphName> UNTILPERFORM <paragraphName> UNTIL for your COBOL looping requirements.

When do you need to loop in your COBOL programs? Reading/Writing a file until no more records Looping through rows returned from a database Loading a COBOL internal table Processing a COBOL table sequentially Calculations Algorithms

…in general – you will write few programs that don't loop

Page 60: Basic COBOL Statements

60

PERFORMPERFORM <paragraphName> <paragraphName> n n TIMESTIMES Can PERFORM a paragraph a specified

number of times, in a loop controlled by a: Numeric literal Numeric integer variable

Examples: Performs all of the COBOL statements between 300-MAINLINE-RTN300-MAINLINE-RTN and 300-EXIT 300-EXIT 12 12 TIMESTIMES

Performs all of the COBOL statements between 310-SUBTOTALS 310-SUBTOTALS and 310-EXIT 310-EXIT the number of times represented by the integer value in NBR-REPSNBR-REPS

Use PERFORM … n TIMES PERFORM … n TIMES – when you know during development how many loop iterations should be performed at run-time.

WORKKING-STORAGE SECTION.WORKKING-STORAGE SECTION.

77 NBR-REPS S9(4) COMP.77 NBR-REPS S9(4) COMP.

PROCEDURE DIVISION.PROCEDURE DIVISION.

… …

PERFORM 300-MAINLINE-RTNPERFORM 300-MAINLINE-RTN

THRU 300-EXITTHRU 300-EXIT

12 TIMES.12 TIMES.

GOBACK.GOBACK.

300-MAINLINE-RTN.300-MAINLINE-RTN.

… …

MOVE IN-REC-KTR TO NBR-REPS.MOVE IN-REC-KTR TO NBR-REPS.

PERFORM 310-SUBTOTALSPERFORM 310-SUBTOTALS

THRU 310-EXITTHRU 310-EXIT

NBR-REPS TIMES.NBR-REPS TIMES.

… …300-EXIT.300-EXIT.

EXIT.EXIT.

WORKKING-STORAGE SECTION.WORKKING-STORAGE SECTION.

77 NBR-REPS S9(4) COMP.77 NBR-REPS S9(4) COMP.

PROCEDURE DIVISION.PROCEDURE DIVISION.

… …

PERFORM 300-MAINLINE-RTNPERFORM 300-MAINLINE-RTN

THRU 300-EXITTHRU 300-EXIT

12 TIMES.12 TIMES.

GOBACK.GOBACK.

300-MAINLINE-RTN.300-MAINLINE-RTN.

… …

MOVE IN-REC-KTR TO NBR-REPS.MOVE IN-REC-KTR TO NBR-REPS.

PERFORM 310-SUBTOTALSPERFORM 310-SUBTOTALS

THRU 310-EXITTHRU 310-EXIT

NBR-REPS TIMES.NBR-REPS TIMES.

… …300-EXIT.300-EXIT.

EXIT.EXIT.

Page 61: Basic COBOL Statements

61

PERFORMPERFORM UNTIL UNTIL <condition><condition>

Structured method of looping when you only know at run-time how many times the loop should be iterated over

UNTILUNTIL Tests a condition for TRUE/FALSE

If NOT TRUE (repeat – if the condition is FALSE) PERFORMPERFORM the specified Paragraph

If TRUE

– End the loop

– Return program control to the next sequential instruction following the PERFORM UNTILPERFORM UNTIL statement

Additional notes: If the UNTIL condition never becomes true?

Infinite loop – If the program is batch, the TIME= parameter on the

JCL will most likely cancel it– If the program is an online transaction, the operator

will cancel it– Either way, this is not a good thing

There are actually two additional options for PERFORM UNTILPERFORM UNTIL (next slide)

PROCEDURE DIVISION.PROCEDURE DIVISION.

PERFORM 100-HOUSEKEEPINGPERFORM 100-HOUSEKEEPING

THRU 100-EXIT.THRU 100-EXIT.

PERFORM 300-MAINLINE-RTNPERFORM 300-MAINLINE-RTN

THRU 300-EXITTHRU 300-EXIT

UNTIL NO-MORE-RECORDS.UNTIL NO-MORE-RECORDS. GOBACK.GOBACK.

100-HOUSEKEEPING.100-HOUSEKEEPING.

OPEN INPUT IN-FILE.OPEN INPUT IN-FILE.

PERFORM 800-READ-RTNPERFORM 800-READ-RTN

THRU 800-EXIT.THRU 800-EXIT.

100-EXIT.100-EXIT.

EXIT.EXIT.

300-MAINLINE-RTN.300-MAINLINE-RTN.

… …

PERFORM 800-READ-RTN.PERFORM 800-READ-RTN.

300-EXIT.300-EXIT.

EXIT.EXIT.

800-READ-RTN.800-READ-RTN.

READ IN-FILE INTO WS-RECORDREAD IN-FILE INTO WS-RECORD

AT END MOVE 'Y' AT END MOVE 'Y'

TO SW-NO-MORE-RECORDS.TO SW-NO-MORE-RECORDS.

800-EXIT.800-EXIT.

EXIT.EXIT.

PROCEDURE DIVISION.PROCEDURE DIVISION.

PERFORM 100-HOUSEKEEPINGPERFORM 100-HOUSEKEEPING

THRU 100-EXIT.THRU 100-EXIT.

PERFORM 300-MAINLINE-RTNPERFORM 300-MAINLINE-RTN

THRU 300-EXITTHRU 300-EXIT

UNTIL NO-MORE-RECORDS.UNTIL NO-MORE-RECORDS. GOBACK.GOBACK.

100-HOUSEKEEPING.100-HOUSEKEEPING.

OPEN INPUT IN-FILE.OPEN INPUT IN-FILE.

PERFORM 800-READ-RTNPERFORM 800-READ-RTN

THRU 800-EXIT.THRU 800-EXIT.

100-EXIT.100-EXIT.

EXIT.EXIT.

300-MAINLINE-RTN.300-MAINLINE-RTN.

… …

PERFORM 800-READ-RTN.PERFORM 800-READ-RTN.

300-EXIT.300-EXIT.

EXIT.EXIT.

800-READ-RTN.800-READ-RTN.

READ IN-FILE INTO WS-RECORDREAD IN-FILE INTO WS-RECORD

AT END MOVE 'Y' AT END MOVE 'Y'

TO SW-NO-MORE-RECORDS.TO SW-NO-MORE-RECORDS.

800-EXIT.800-EXIT.

EXIT.EXIT.

Page 62: Basic COBOL Statements

62

PERFORMPERFORM UNTIL – With TEST UNTIL – With TEST BEFORE or AFTERBEFORE or AFTER PERFORM …UNTILPERFORM …UNTIL may be modified by

one of two clauses, coded before UNTILUNTIL and after the paragraph name:

1.1.WITH TEST BEFOREWITH TEST BEFORE The UNTILUNTIL condition is tested before condition is tested before

each each PERFORMPERFORM execution.  execution.  The Paragraphs will be executed The Paragraphs will be executed 00 or or

more timesmore times Is the default – if this clause is left Is the default – if this clause is left

unspecifiedunspecified

2.2.WITH TEST AFTERWITH TEST AFTER The UNTILUNTIL condition is tested after each condition is tested after each

PERFORMPERFORM execution.  execution.  The Paragraphs will be executed The Paragraphs will be executed 11 or or

more timesmore times

PROCEDURE DIVISION.PROCEDURE DIVISION.

PERFORM 100-HOUSEKEEPINGPERFORM 100-HOUSEKEEPING

THRU 100-EXIT.THRU 100-EXIT.

PERFORM 300-MAINLINE-RTNPERFORM 300-MAINLINE-RTN

THRU 300-EXIT THRU 300-EXIT

WITH TEST BEFOREWITH TEST BEFORE UNTIL NO-MORE-RECORDS.UNTIL NO-MORE-RECORDS. GOBACK.GOBACK.

100-HOUSEKEEPING.100-HOUSEKEEPING.

OPEN INPUT IN-FILE.OPEN INPUT IN-FILE.

PERFORM 800-READ-RTNPERFORM 800-READ-RTN

THRU 800-EXIT.THRU 800-EXIT.

100-EXIT.100-EXIT.

EXIT.EXIT.

300-MAINLINE-RTN.300-MAINLINE-RTN.

… …

PERFORM 800-READ-RTN.PERFORM 800-READ-RTN.

300-EXIT.300-EXIT.

EXIT.EXIT.

800-READ-RTN.800-READ-RTN.

READ IN-FILE INTO WS-RECORDREAD IN-FILE INTO WS-RECORD

……

800-EXIT.800-EXIT.

EXIT.EXIT.

PROCEDURE DIVISION.PROCEDURE DIVISION.

PERFORM 100-HOUSEKEEPINGPERFORM 100-HOUSEKEEPING

THRU 100-EXIT.THRU 100-EXIT.

PERFORM 300-MAINLINE-RTNPERFORM 300-MAINLINE-RTN

THRU 300-EXIT THRU 300-EXIT

WITH TEST BEFOREWITH TEST BEFORE UNTIL NO-MORE-RECORDS.UNTIL NO-MORE-RECORDS. GOBACK.GOBACK.

100-HOUSEKEEPING.100-HOUSEKEEPING.

OPEN INPUT IN-FILE.OPEN INPUT IN-FILE.

PERFORM 800-READ-RTNPERFORM 800-READ-RTN

THRU 800-EXIT.THRU 800-EXIT.

100-EXIT.100-EXIT.

EXIT.EXIT.

300-MAINLINE-RTN.300-MAINLINE-RTN.

… …

PERFORM 800-READ-RTN.PERFORM 800-READ-RTN.

300-EXIT.300-EXIT.

EXIT.EXIT.

800-READ-RTN.800-READ-RTN.

READ IN-FILE INTO WS-RECORDREAD IN-FILE INTO WS-RECORD

……

800-EXIT.800-EXIT.

EXIT.EXIT.

Page 63: Basic COBOL Statements

63

Lab Assignment

From the course workshop documents, do the following labs:1. COBOL Looping Lab

Page 64: Basic COBOL Statements

64

Unit

Topics:Topics:

COBOL General Language COBOL General Language RulesRules

Assignment Statements and Internal Data Representation

Math Operations

Conditional Logic

Transfer of control

COBOL Looping Constructs

Sequential File Processing PatternsSequential File Processing Patterns

Java and .NET Equivalents

Page 65: Basic COBOL Statements

65

Topic objectives

This topic covers basic (simple) sequential file processing – patterns: Open files Read an initial record from the input file Process all records until end-of-input-file

Edit and validate data Compute totals, subtotals and accumulators Write output records Read the next input file record

Close files and end the job In subsequent topics of this course, we will dive much more deeply into

file handling, as a majority of COBOL batch processing depends on concepts and coding patterns that are variations of the above

We will also touch on the basic batch program design patterns you will want to use going forward in this course and later in your production COBOL work

By the end of this chapter you will be able to: OPEN, READ, WRITE and CLOSE files Loop through and input file, processing all of the records until completed

Page 66: Basic COBOL Statements

66

Sequential File ProcessingSequential File Processing

Sequential File Processing consists of a well-documented set of processing – Sequential File Processing consists of a well-documented set of processing – or a pattern that you will see in many program requirementsor a pattern that you will see in many program requirements You read one or more input files until:You read one or more input files until:

Your business logic requirements are fulfilledYour business logic requirements are fulfilled End-of-FileEnd-of-File

While reading files you typically:While reading files you typically: Edit or evaluate dataEdit or evaluate data Add numeric values to total and sub-total fields – perform business calculationsAdd numeric values to total and sub-total fields – perform business calculations Assign (MOVE) valuesAssign (MOVE) values WRITE output record(s) – either to an output file, report or bothWRITE output record(s) – either to an output file, report or both

You must be cognizant of:You must be cognizant of: Bad or invalid data (and know what to do about it when it shows up in your fields)Bad or invalid data (and know what to do about it when it shows up in your fields) Empty input filesEmpty input files READ/WRITE I/O errors that may occurREAD/WRITE I/O errors that may occur

After reaching end-of-file you will typically:After reaching end-of-file you will typically: WRITE a final output record, with summary computed values WRITE a final output record, with summary computed values CLOSE all filesCLOSE all files DISPLAY a successful end-of-job messageDISPLAY a successful end-of-job message

Input FileInput FileNote - more Note - more than likely than likely NOTNOT a tape a tape

Device Device

COBOL ProgramCOBOL ProgramBusiness LogicBusiness Logic

Output FileOutput File

Output ReportOutput Report

Record

Bu

ffer

Record

Bu

ffer

Record

Bu

ffer

Record

Bu

ffer

Page 67: Basic COBOL Statements

67

Sequential File Processing Pattern – Simple Batch Design PatternSequential File Processing Pattern – Simple Batch Design Pattern

This first batch application pattern "Process One Input File" – consists of This first batch application pattern "Process One Input File" – consists of the following pattern the following pattern

Perform an initialization routinePerform an initialization routine Initialize values in Working-StorageInitialize values in Working-Storage OPEN the files – for either input or outputOPEN the files – for either input or output PERFORM a "priming" input-record read – an initial read statement that PERFORM a "priming" input-record read – an initial read statement that

simplifies:simplifies: Empty input-file-processing problemsEmpty input-file-processing problems Reading past end-of-file logic problemsReading past end-of-file logic problems

Perform a process-the-file routine, until end-of-input-filePerform a process-the-file routine, until end-of-input-file Validate the data Validate the data – using the conditional logic statements learned in this unit Move the data Move the data – using the assignment statements learned in this unit Do computations, calculations, etc. Do computations, calculations, etc. – using the COBOL math statements Write the recordWrite the record Read the next input recordRead the next input record

Perform an end-of-job routinePerform an end-of-job routine Complete final computationsComplete final computations WRITE final output record with final computationsWRITE final output record with final computations CLOSE all files and display an end-of-job message on the ConsoleCLOSE all files and display an end-of-job message on the Console

Page 68: Basic COBOL Statements

68

File I/O Review – OPENOPEN

…ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.

SELECT INTFILENAME ASSIGN TO … …DATA DIVISION.FILE SECTIONFD INTFILENAME…01 OUT-REC.

…PROCEDURE DIVISION.

OPEN OPEN

INPUT FILE1, FILE2INPUT FILE1, FILE2

OUTPUT FILE3, FILE4.OUTPUT FILE3, FILE4.…

ExternalExternalDeviceDevice

External FileExternal File

Recall the following:Recall the following: SELECT/ASSIGNSELECT/ASSIGN connects your

internal (logical) filename with external (physical) file-spec

FILE SECTIONFILE SECTION is required for each SELECT/ASSIGNSELECT/ASSIGN file

OPENOPEN references the logical (internal) filename

Can OPENOPEN multiple files with one statement (as shown)

Note carefully the syntax for OPEN See Slide Notes, for See Slide Notes, for additional learning contentadditional learning content

Record BufferRecord Buffer

Page 69: Basic COBOL Statements

69

File I/O Review – READ INTOREAD INTO

ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION.

SELECT INTFILENAME ASSIGN TO … DATA DIVISION. FILE SECTION FD INTFILENAME … 01 IN-REC. WORKING-STORAGE SECTION 01 IN-REC-WS. 01 END-OF-FILE-FLAG PIC X. PROCEDURE DIVISION.

OPEN INPUT INTFILENAME.

READ INTFILENAME INTO IN-RECREAD INTFILENAME INTO IN-REC

AT END MOVE ‘Y’ to END-OF-FILE-FLAG.AT END MOVE ‘Y’ to END-OF-FILE-FLAG.…

ExternalExternalDeviceDevice

External FileExternal File

See Slide Notes, See Slide Notes, for additional for additional learning contentlearning content

FILE

READ

Recall the following:Recall the following: File must be OPENOPEN before you try to READREAD from it READREAD retrieves each record from an external file:

- Into the record specified in your FILE SECTIONFILE SECTION

* Note that the DATA DIVISION's FILE SECTION is sometimes referred to as an I/O "buffer"* Note that the DATA DIVISION's FILE SECTION is sometimes referred to as an I/O "buffer"

- Into WORKING-STORAGEWORKING-STORAGE - if you've coded READ INTOREAD INTO AT ENDAT END condition occurs after the last record is READREAD from the file

- If you attempt to read past end-of-file your program will ABEND

Record BufferRecord Buffer

Page 70: Basic COBOL Statements

70

File I/O Review – WRITE FROMWRITE FROM

ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.

SELECT OUTFILENAME ASSIGN TO …DATA DIVISION.FILE SECTIONFD OUTFILENAME…01 OUT-REC. WORKING-STORAGE SECTION 01 OUT-REC-WS.PROCEDURE DIVISION.

OPEN OUTPUT OUTFILENAME.

WRITE OUT-REC WRITE OUT-REC

FROM OUT-REC-WS.FROM OUT-REC-WS.

……

ExternalExternalDeviceDevice

External FileExternal File

See Slide Notes, See Slide Notes, for additional for additional learning contentlearning content

Recall the following:Recall the following: File must be OPENOPEN before you try to WRITE WRITE a record to it

- An ABEND condition occurs, if try to write to an un-opened file WRITEWRITE creates a new record at the end of a sequential/external file:

- From the record specified in your FILE SECTIONFILE SECTION

- From WORKING-STORAGEWORKING-STORAGE - if you've coded WRITE FROMWRITE FROM CloseClose opened output files before your program ends

WRITE

OPERATION

Record BufferRecord Buffer

Page 71: Basic COBOL Statements

71

File I/O Review – CLOSECLOSE

ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.

SELECT INTFILENAME ASSIGN TO ……DATA DIVISION.FILE SECTIONFD INTFILENAME…01 OUT-REC.

…PROCEDURE DIVISION.

CLOSE CLOSE

FILE1, FILE2,FILE1, FILE2,

FILE3, FILE4.FILE3, FILE4.…

ExternalExternalDeviceDevice

External FileExternal File

Recall the following:Recall the following: CLOSE CLOSE every opened file

- Input file

- Output file Can CLOSECLOSE multiple files with one

statement (as shown) Can re-OPEN a file after closing

Note carefully the syntax for CLOSE

FILE

CLOSE

See Slide Notes, for additional learning content

Record BufferRecord Buffer

Page 72: Basic COBOL Statements

72

Sequential File Processing Pattern – Pseudo-Code

In a subsequent unit of this course we will cover the concept of design and programming patterns with COBOL

For now, here is your first simple, sequential file-handling pattern, in pseudo-code.

Study the control-flow to understand the paragraph PERFORM process, and purpose of each statement block

Tie this back to the code you the previous slide in this unit.

What is not part of this processing pattern are the actual details of the: Data Validation Calculations and computations… which can be extremely complex and will most

likely take up the majority percentage of your coding cycles.

There are other algorithms that can do the same sequential process, but we feel this is a simple, easy-to-read/maintain/debug-support/and extend approach

PROCEDURE DIVISION.PROCEDURE DIVISION.

Do Init-RoutineDo Init-Routine

Do Process-FilesDo Process-Files

until No-More-Datauntil No-More-Data

Do End-of-Job-RoutineDo End-of-Job-Routine

GOBACK.GOBACK.

Init-Routine.Init-Routine.

Open filesOpen files

READ Input-FileREAD Input-File

Process-Files.Process-Files.

Validate input dataValidate input data

Perform calculations and Perform calculations and

sub-totalssub-totals

Move data to output RecordMove data to output Record

Write Output-RecordWrite Output-Record

READ Input-FileREAD Input-File

End-of-Job-Routine.End-of-Job-Routine.

Final computationsFinal computations

Move Data to output RecordMove Data to output Record

Write output recordWrite output record

Close FilesClose Files

PROCEDURE DIVISION.PROCEDURE DIVISION.

Do Init-RoutineDo Init-Routine

Do Process-FilesDo Process-Files

until No-More-Datauntil No-More-Data

Do End-of-Job-RoutineDo End-of-Job-Routine

GOBACK.GOBACK.

Init-Routine.Init-Routine.

Open filesOpen files

READ Input-FileREAD Input-File

Process-Files.Process-Files.

Validate input dataValidate input data

Perform calculations and Perform calculations and

sub-totalssub-totals

Move data to output RecordMove data to output Record

Write Output-RecordWrite Output-Record

READ Input-FileREAD Input-File

End-of-Job-Routine.End-of-Job-Routine.

Final computationsFinal computations

Move Data to output RecordMove Data to output Record

Write output recordWrite output record

Close FilesClose Files

Page 73: Basic COBOL Statements

73

Putting it All Together - A Complete Example of a Sequential File Processing Program Read through (study) the code in this sample

small sequential file processing program. Trace the concepts, COBOL syntax and

statement semantics learned in this, and the previous Unit to the actual code in this program.

Feel free to refer-back to your slides, the course supplemental text or your notes – if necessary

Select External FileSelect External FileAssign to COBOL Assign to COBOL (internal) file name(internal) file name

FILE SECTION FDsFILE SECTION FDs

Matching the SELECT/ASSIGNMatching the SELECT/ASSIGNClauses for each external fileClauses for each external file

Note – this example continues over the next three slidesNote – this example continues over the next three slides

Page 74: Basic COBOL Statements

74

A Complete Example of a Sequential File Processing Program – WORKING-STORAGE SECTION

File Status fieldsFile Status fieldsAutomatically updatedAutomatically updatedBy COBOL and the O.S.By COBOL and the O.S.

Input and Output recordsInput and Output records

You will often see these You will often see these coded in WORKING-coded in WORKING-STORAGE because they STORAGE because they are easier to find in a are easier to find in a System log file (called a System log file (called a DUMP file) if your DUMP file) if your program files (ABENDS) program files (ABENDS) when executing on the when executing on the mainframemainframe

Holding fields for intermediateHolding fields for intermediateresult calculations and valuesresult calculations and values

A final-totals output recordA final-totals output record

Page 75: Basic COBOL Statements

75

A Complete Example of a Sequential File Processing Program – PROCEDURE DIVISION

Our Sequential File Pattern – in COBOLOur Sequential File Pattern – in COBOL

Read the code line-by-line (as if you were debugging it –Read the code line-by-line (as if you were debugging it –In other words, if there's a PERFORM – jump down to theIn other words, if there's a PERFORM – jump down to thePerformed paragraph. When finished jump back, etc.)Performed paragraph. When finished jump back, etc.)

Note the use of:Note the use of:• PERFORM THRU PERFORM THRU • AT END/GO TO "EXIT" AT END/GO TO "EXIT" • PERFORM UNTILPERFORM UNTIL

• For each record in the input file, do 100-MAINLINEFor each record in the input file, do 100-MAINLINE

EEDDIITTSS

ProcessingProcessing• CalculationsCalculations• ComputationsComputations

MMOOVVEE

Write the current recordWrite the current record

Read the next record in the fileRead the next record in the file

Page 76: Basic COBOL Statements

76

A Complete Example of a Sequential File Processing Program – No More Records in the File When there are no more When there are no more

records left to processrecords left to process Do final calculationsDo final calculations Move the fields to final output recordMove the fields to final output record WRITEWRITE CLOSE all filesCLOSE all files Display aDisplay a message on the console message on the console

Page 77: Basic COBOL Statements

77

Lab Assignment

From the course workshop documents, do the following labs:1. Process Input File1

2. Process InputFile2

Page 78: Basic COBOL Statements

78

Unit

Topics:Topics:

COBOL General Language COBOL General Language RulesRules

Assignment Statements and Internal Data Representation

Math Operations

Conditional Logic

Transfer of control

COBOL Looping Constructs

Reading and Writing Files - Review

Java and .NET EquivalentsJava and .NET Equivalents

Page 79: Basic COBOL Statements

79

Java .NET COBOL EquivalentsCOBOLCOBOL JAVAJAVA VB.NETVB.NETMOVE MOVE (elementary field) Java variable assignment (right to left) Variable assignment (right to left)

MOVE MOVE (group field move) Java OBJECT assignment (right to left) Variable assignment (right to left)

MOVE CORRESPONDINGMOVE CORRESPONDING N/A N/A

MOVE with OF qualifierMOVE with OF qualifier Qualified assignment var1.var2.var3 Qualified assignment var1.var2.var3

ADDADD Standard math computation (no separate statement) Standard math computation (no separate statement)

SUBTRACTSUBTRACT "" ""

MULTIPLYMULTIPLY "" ""

DIVIDEDIVIDE "" ""

COMPUTECOMPUTE "" ""

IF/ELSE AND/ORIF/ELSE AND/OR If If

EVALUATE EVALUATE case case

PERFORMPERFORM Method invocation Method invocation

PERFORM THRUPERFORM THRU While or FOR – method invocation While or FOR – method invocation

COBOL Paragraphs and SectionsCOBOL Paragraphs and Sections Java Labels Label

GO TOGO TO Break/Continue can refer to a Label (same behavior as GO TO EXIT) Break/Continue can refer to a Label (same behavior as GO TO EXIT)

PERFORM THRU UNTILPERFORM THRU UNTIL While or FOR – method invocation While or FOR – method invocation

OPENOPEN //comment, as Java opens files automatically OPEN()

CLOSECLOSE DataInputStream.close() CLOSE()

WRITEWRITE DataInputStream/BufferedInputStream/FileInputStream StreamWriter/BinaryWriter

READREAD DataInputStream/BufferedInputStream/FileInputStream StreamReader/BinaryReader

ACCEPTACCEPT Java.util.Scannner (System.in) Console.Read

DISPLAYDISPLAY System.out.println Console.WriteLine – or Console.Write