Anda di halaman 1dari 79

IBM Software Group

Enterprise COBOL Education Using Rational Developer for System Z Module 3 Basic COBOL Statements
Jon Sayles, IBM Software Group, Rational EcoSystems Team

2006 IBM Corporation

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 IBMs 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.

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

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 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

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.

Unit

COBOL General Language Rules


Topics:
Assignment Statements and Internal Data Representation Math Operations
Conditional Logic

Transfer of control COBOL Looping Constructs Sequential File Processing Patterns Java and .NET Equivalents

Topic objectives
After completing this topic, you should be able to:
Describe the COBOL MOVE and assignment operation List the three types of COBOL assignment statements and what causes the COBOL compiler to choose one type over the other Define 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 correct Describe the underlying COBOL storage representation for:
Alphanumeric data Numeric data

List the common COBOL Figurative Constants

Describe what the COBOL INITIALIZE statement does

COBOL Picture Clauses and Internal Data Representation


COBOL Data types are PIC clause dependent, and come in several broad categories:
Character Data: Fixed Length: PIC X(nn) or PIC A(nn) Note, A "Alphabetic data" Stored as EBCDIC bytes examples: A Hex: C1, B Hex: C2, 9 Hex: F9, etc
http://theamericanprogrammer.com/code7302/ebcdic.txt

Numeric Data: Display numeric (aka Zoned Decimal): PIC 9(5), PIC S9(5)V99 Stored as EBCDIC bytes, with "assumed" decimal place one byte per digit Hex values: F0 F9 With V in declaration COBOL takes care of decimal alignment in math/MOVE operations With S (sign) in declaration, the last byte of internal storage holds the sign (C or D):

C - is positive number: PIC S9(5)V99 - value: D - is negative number PIC S9(5)V99 - value:

321.19 321.19

F0 F0 F3 F2 F1 F1 C9 F0 F0 F3 F2 F1 F1 D9
EBCDIC Internal Data Representation

Binary (COMP) numeric used to improve run-time COBOL arithmetic instruction performance:
Small binary: PIC S9(4) COMP stored in two bytes, pure binary (base 16) data Medium binary: PIC S9(9) COMP stored in four bytes Large binary: PIC 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: 0123 Stored as twos complement of 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 nibble
Ex.
PIC S9(5)V99 COMP-3 Value PIC S9(5)V99 COMP-3 Value 123.99. -123.99. Stored as: Stored as: 00 12 39 9C 00 12 39 9D

Important See Slide Notes

COBOL Picture Clause Editing and External (Output) Field Values


There are a number of other PIC clauses used for output result data on reports and greenscreen I/O. They are simple to understand, and very convenient. Note that the numeric PIC clauses force decimal-point alignment. The alphanumeric PIC clauses all align the data left.
Suppress leading zeroes insert floating blanks PIC ZZ,ZZZ,Z99.99 B Alphanumeric "mask" Positionally insert a blank into alphanumeric data PIC XBXBXB 0 Numeric "mask" - Positionally insert a zero into a numeric field. PIC 990990 / Data mask - Insert a slash into alphanumeric data typically used for dates PIC XX/XX/XX , Insert a comma into numeric data PIC Z,ZZZ,Z99.99 . Insert a decimal point, into numeric data Z,ZZZ,Z99.99 + Insert a plus sign IF the value in the variable is > 0 PIC Z,ZZZ,Z99.99+ Insert a negative sign IF the value in the variable is < 0 PIC Z,ZZZ,Z99.99CR Insert a "CR" literal IF the value in the variable is < 0 PIC Z,ZZZ,Z99.99CR DB Insert a "DB" literal IF the value in the variable is < 0 PIC Z,ZZZ,Z99.99DB * Insert asterisks instead of leading zeros for numeric values PIC ********9999 $ Dollar-sign suppressions - Insert a floating, left-justified $ sign for numeric values PIC $$,$$$,$99.99 Z
9

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

10

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

11

COBOL Storage Representation Reference Chart


Picture Clause
PIC X(10) PIC 9(5) PIC S9(5) PIC S9(5)V99 PIC S9(4) COMP PIC S9(5) ==> S9(9) COMP PIC S9(9) ==> S9(18) COMP

Meaning
Fixed alpha-numeric data Display numeric (Zoned Decimal) numbers Zoned decimal - with sign Zoned decimal with implied decimal place Small binary number - 2 byte - note, negative binary #s stored as two's complement Binary number - 4 bytes Large Binary number

Value
'ABC' -321 -321 321.5 321 321 321

Internal Value
ABCbbbbbbb (seven trailing blanks) 00321 - Note - without S (sign) value get "absolute value" 00321 - Value is negative in math operations 00321V50 0321 00000321 000000000000000321

Internal Storage (EBCDIC bytes)


CCC4444444 12300000000 FFFFF 00321 FFFFD 00321 FFFFFFC 0032150 04 11 0004 0011 00000004 00000011 031 02F 0319 029C 0319 029D

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

Packed decimal number Packed decimal number Packed decimal number

321 321.99 -321.99

0321 00321.99 00321.99 Value is negative in math operations

External PIC clauses


PIC Z(3) PIC ZZ,ZZZ,ZZZ.99PIC $$,$$$,$99.99 PIC XBXBXB PIC 990990 PIC XX/XX/XX PIC Z,ZZZ,Z99.99CR PIC ****9999 PIC Z,ZZZ,Z99.99DB Zero-suppressed Zero-suppressed, with commas and minus sign Dollar-sign suppressed Blank insertion Zero insertion Slash insertion Zero-suppressed, with commas and Credit sign Asterisk suppressed Zero-suppressed, with commas and Debit sign

Value
-2.99 -321.99 -321.99 ABC -321.99 012099 -321.99 -333321.99 321.99 12

Output/Display Value
2 321.99$321.99 AbBbCb 030210 01/10/99 321.99CR **321 321.99

Notes
No decimal places, no sign Sign on right (can be on left). Zeroes suppressed One resulting $, if need sign, must use dash (-) Positional blank (b) inserted High-order inserted, numbers inserted @ PIC 9 Date mask If number was positive, CR would not appear Like Z and $ - asterisk suppresses leading zeros If number was negative, DB would appear

88-Level Variables in the Data Division

88-level variables in COBOL programs are "conditionals, built in to the variable declarations" They:
Have no PIC clause Have one or more VALUES specified as literals (see a few valid expressions below) Are used effectively to make COBOL IF conditional expressions readable/maintain-able
01 MONTH-IND PIC XXX. 88 SHORTEST-MONTH VALUE 'FEB'. 88 THIRTY-DAY-MONTH VALUES ARE 'JUN', 'SEP', 'APR', 'NOV'. 88 THIRTY-ONE-DAY MONTH VALUES ARE 'JAN' 'MAR' 'MAY' 'JUL' 'AUG' 'OCT' 'DEC'. IF THIRTY-DAY-MONTH 01 STUDENT-GRADE-RANGE PIC S9(3). 88 A-OK VALUE 90 THRU 100. 88 NOT-BAD VALUE 80 THRU 89. 88 PRETTY-GOOD VALUE 70 THRU 79. 88 RUH-ROH VALUE 60 THRU 79. 88 FAIL VALUE 0 THRU 59. IF NOT-BAD MOVE 'DOIN ALRIGHT' TO MSG-TEXT DISPLAY GRADE-MSG
13

Pluses:

Make code more "English" read-able Allow you to centralize conditions in one place - in the DATA DIVISION

Minuses:

Force you to refer to the DATA DIVISION for the actual values tested in the code in the PROCEDURE DIVISION

Review Imperative Statements MOVE


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.

Syntax:

MOVE

<to-variable> TO <from-variable>.

MOVE copies the value in the to-variable to the from-variable (receiving field), over-writing the from-variables storage contents. There are two types of MOVE operations:
Alphanumeric MOVE Numeric MOVE

The receiving field's datatype (PIC clause) dictates the type of MOVE operation It is important to understand how the contents of variable storage are affected by MOVE. So, let's drill-down now, on PIC clauses and COBOL internal data storage representation
14

Alphanumeric MOVE Statements


Alphanumeric MOVE statements:
Occur when the receiving field is considered Alphanumeric by the compiler
PIC X PIC 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 MOVE statement that truncates data)

Except can JUSTIFY the receiving field data RIGHT



FLD1 FLD2 MOVE

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

FLD1 TO FLD2. Results in FLD2 value of: bbbbbbABCD

If JUSTIFY RIGHT, and the receiving field is shorter than the sending field, truncation occurs in the right-most characters If JUSTIFY 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' result of MOVE is: ABCDbbbbbb. Why?

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

Group data (structures) are considered Alphanumeric in MOVE operations


15

Numeric MOVE Statements

Numeric MOVE statements:


Occur when the receiving field's PIC clause is numeric
9 anywhere in the PIC clause Input field declaration:
V, S

Output (formatted numeric PIC clause in declaration)


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

MOVE 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 V in PIC clause
Pad to the left with leading, and to the right with trailing zeroes, 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 MOVE 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)
16

MOVE Statements When the Datatypes Are Not The Same


Obviously you can move PIC X fields to other PIC X and PIC 9 fields to other PIC 9 fields, but sometimes, due to business requirements you will have to code MOVE 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 MOVE

Sending Fields
PIC X PIC X PIC 9 Y Y

Receiving Fields
PIC 9 N Y Numeric Edited N Y

Treated as an alphanumeric MOVE (digits may be lost, trailing blanks may be added, etc.)

Numeric Edited

Y
17

Allowable MOVE 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
18

Alphanumeric MOVE Statements - Examples


Sending Field
PIC X(5) PIC X(5) PIC X(5) PIC 9(5) PIC X(5) PIC S9(5)V99 COMP-3 PIC S9(4) COMP PIC X(4)

Receiving Field
PIC X(5) PIC X(3) PIC X(8) PIC X(8) PIC 9(5) PIC X(8) PIC X(4) PIC X(10) JUSTIFY RIGHT.

Sending Field Value


ABCDE ABCDE ABCDE 12345 Not allowed by the compiler Not allowed by the compiler as is noninteger numeric (see table of moves) 1234 ABCD

Result in Receiving Field


ABCDE ABC ABCDEbbb 12345bbb N/A 13574444 246C0000 1344 2400 bbbbbbABCD (hex)

Numeric Value
PIC 9(5)V99 PIC S9(7)V99 PIC S9(5)V99 PIC S9(9) COMP PIC S9(5)V99 COMP-3 PIC 9(3)V9 PIC 9(4) COMP PIC S9(7)V999 COMP-3 PIC 9(5)V99 PIC 9 12345.67 123456789.99 -12345.67 1234567912 -12345.67 345.67 6789 0012345.670 (minus carried in sign bit) 67912.00 5

Group Moves
CUSTOMER-NAME
CUSTOMER-RECORD

PIC X(18)
PIC X(40)

SMITHbbbbbAALEXAND
1201SMITHbbbbbAALEXANDERbbbbbbbbbbbbbbbbbbbbbb

01 CUSTOMER-RECORD. 05 ID-NUMBER 05 CUST-TYPE 05 CUSTOMER-NAME. 10 FIRST-NAME 10 MIDINIT 10 LAST-NAME

PIC 9(2) PIC 9(2)

VALUE 12. VALUE 01.

PIC X(10) VALUE 'SMITH'. PIC X(01) VALUE 'A'. PIC X(10) VALUE 'ALEXANDER'.

19

MOVE With OF Modifier


FILE SECTION. 01 CUSTOMER-RECORD-IN. 05 ID-NUMBER PIC 9(2). 05 CUST-TYPE PIC 9(2). 05 CUSTOMER-NAME. 10 FIRST-NAME PIC X(10). 10 MIDINIT PIC X(01). 10 LAST-NAME PIC X(10). 01 CUSTOMER-RECORD-OUT. 05 ID-NUMBER PIC 9(2). 05 CUST-TYPE PIC 9(2). 05 CUSTOMER-NAME. 10 FIRST-NAME PIC X(10). 10 MIDINIT PIC X(01). 10 LAST-NAME PIC X(10). PROCEDURE DIVISION. MOVE FIRST-NAME OF CUSTOMER-RECORD-IN TO FIRST-NAME OF CUSTOMER-RECORD-OUT.

Syntax:

MOVE <from-variable> of <from-Group> to

<to-variable>.

The OF modifier allows you to:


Fully-qualify elementary field names making large programs with 1,000's variables easier to maintain Compile programs with duplicate elementary field names

20

MOVE CORRESPONDING
FILE SECTION. 01 CUSTOMER-RECORD-IN. 05 ID-NUMBER PIC 9(2). 05 CUST-TYPE PIC 9(2). 05 CUSTOMER-NAME. 10 FIRST-NAME PIC X(10). 10 MIDINIT PIC X(01). 10 LAST-NAME PIC X(10). 01 CUSTOMER-RECORD-OUT. 05 ID-NUMBER PIC 9(2). Field's data not moved 05 CUSTTYP PIC 9(2). 05 CUSTOMER-NAME. Field's data not moved 10 FIRSTNAME PIC X(10). 10 MIDINIT PIC X(01). 10 LAST-NAME PIC X(10). PROCEDURE DIVISION. MOVE CORRESPONDING CUSTOMER-RECORD-IN TO CUSTOMER-RECORD-OUT.

Syntax:

MOVE CORRESPONDING <from-group-variable> to

<to-group-variable>.

The CORRESPONDING modifier allows you to MOVE group records:


When COBOL variable names match between the from and to groups, data is copied And only when COBOL variable names match
21

See Notes

COBOL INITIALIZE 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

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.

22

COBOL Figurative Constants


FILE SECTION. 01 CUSTOMER-RECORD-IN. 77 COBOL-CHAR-FIELD 77 COBOL-NUM-FIELD 77 COBOL-QT
PROCEDURE DIVISION. MOVE LOW-VALUES MOVE HIGH-VALUES MOVE SPACES MOVE ZEROS MOVE ALL '_'

PIC X(4). PIC X(4). PIC X(1) VALUE QUOTE.

to to to to TO

CUSTOMER-RECORD-IN. COBOL-CHAR-FIELD. COBOL-CHAR-FIELD. COBOL-NUM-FIELD. COBOL-CHAR-FIELD.

Syntax:

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 MOVE 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>.
23

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

24

Unit

COBOL General Language Rules


Topics:
Assignment Statements and Internal Data Representation Math Operations
Conditional Logic

Transfer of control COBOL Looping Constructs Sequential File Processing Patterns Java and .NET Equivalents

25

COBOL Mathematical Operators


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

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

Algebraic statements:
COMPUTE 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 ANNUITY ASIN ATAN CHAR COS FACTORIAL LOG LOG10 MAX MEAN MEDIAN MIDRANGE MIN MOD PRESENT-VALUE RANDOM
26

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

Fixed-Point Arithmetic Statements*** ADD


WORKING-STORAGE SECTION. 01 WORK-FIELDS. 05 ITEM-1 PIC S9(3)V99 VALUE 85.52. 05 ITEM-2 PIC S9(3)V99 VALUE 2.34. 05 SUM PIC S9(5)V99 VALUE 0. PROCEDURE DIVISION. ADD ITEM-1, ITEM-2 TO SUM ROUNDED ON SIZE ERROR MOVE 0 TO SUM END-ADD
ADD ITEM-1 ITEM-2 GIVING SUM ROUNDED ON SIZE ERROR MOVE 0 TO SUM DISPLAY '** ON SIZE ERROR **' END-ADD

Rounded
Rounds to the decimal digits in the PIC clause (See Slide Notes)

ON SIZE ERROR
Allows you to handle arithmetic overflow conditions with imperative statements.

Format 1
Adds the addend to the sum

Additional note: You can substitute a numeric literal for the variables in the ADD and TO (but not GIVING) clauses in the statement

Format 2
The values of all operands preceding the word GIVING are added together, and the sum is stored as the new value. None of the values in the operands preceding GIVING are changed

Note: There is a Format 3 statement: ADD CORRESPONDING


27

***See Notes

Arithmetic Statements ROUNDED and ON SIZE ERROR


WORKING-STORAGE SECTION. 01 WORK-FIELDS. 05 ITEM-1 PIC S9(5)V99 VALUE 85.56. 05 RESULT PIC S9(6) VALUE 100. PROCEDURE DIVISION. ADD ITEM-1 TO RESULT.
MOVE 100 TO RESULT. ADD ITEM-1 TO RESULT ROUNDED. MOVE 140156.33 TO ITEM-1. MOVE 900000 TO RESULT. ADD ITEM-1 TO RESULT ROUNDED. MOVE 900000 TO RESULT. ADD ITEM-1 TO RESULT ON SIZE ERROR MOVE 0 TO SUM DISPLAY '** ON SIZE ERROR **'.

Value: 185 Value: 186


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

Value: 040156

Value: 000000

28

Arithmetic Statements SUBTRACT


WORKING-STORAGE SECTION. 01 WORK-FIELDS. 05 ITEM-1 PIC S9(3)V99 VALUE 85.52. 05 ITEM-2 PIC S9(3)V99 VALUE 2.34. 05 DIFFERENCE PIC S9(5)V99 VALUE 0. PROCEDURE DIVISION. SUBTRACT ITEM-1, ITEM-2 FROM DIFFERENCE ROUNDED ON SIZE ERROR MOVE 0 TO DIFFERENCE END-SUBTRACT
SUBTRACT ITEM-1 FROM ITEM-2 GIVING DIFFERENCE ROUNDED ON SIZE ERROR MOVE 0 TO DIFFERENCE DISPLAY '** ON SIZE ERROR **' END-SUBTRACT

Rounded
Rounds to the decimal digits in the PIC clause Allows you to handle arithmetic overflow conditions with imperative statements.

ON SIZE ERROR

Additional note: You can substitute a numeric literal for the variables in the SUBTRACT and FROM (but not GIVING) clauses in the statement

Format 1 Subtracts all minuends from the sum Format 2 The values of all operands preceding the word GIVING are added together, and the sum is subtracted from the difference (in the above) None of the values in the operands preceding GIVING are changed Note: There is a Format 3: SUBTRACT CORRESPONDING
29

Arithmetic Statements MULTIPLY


WORKING-STORAGE SECTION. 01 INPUT-FIELDS. 05 ITEM-1 PIC S9(3)V99 VALUE 85.52. 05 ITEM-2 PIC S9(3)V99 VALUE 2.34. 05 ITEM-3 PIC S9(3)V99 VALUE 6.01. 05 RESULT PIC S9(5)V99. PROCEDURE DIVISION. MULTIPLY ITEM-1 BY ITEM-3 ROUNDED ON SIZE ERROR MOVE 0 TO DIFFERENCE END-MULTIPLY
MULTIPLY ITEM-1 BY ITEM-2 GIVING RESULT ROUNDED ON SIZE ERROR MOVE 0 TO DIFFERENCE DISPLAY '** ON SIZE ERROR **' END-MULTIPLY

Format 1 The values of the operand preceding the word BY is multiplied by the operand after the word BY Format 2 The value of the operand after the word GIVING is replaced by the multiplication of ITEM-1 BY ITEM-2 None of the values in the operands preceding GIVING are changed
30

Arithmetic Statements DIVIDE Common Usage and Formats


WORKING-STORAGE SECTION. 01 INPUT-FIELDS. 05 ITEM-1 PIC S9(3)V99 VALUE 85.52. 05 ITEM-2 PIC S9(3)V99 VALUE 2.34. 05 ITEM-3 PIC S9(3)V99 VALUE 6.01. 05 RESULT PIC S9(5)V99. PROCEDURE DIVISION. DIVIDE ITEM-1 INTO ITEM-3 ROUNDED ON SIZE ERROR MOVE 0 TO DIFFERENCE END-DIVIDE
DIVIDE ITEM-1 INTO ITEM-2 GIVING RESULT ROUNDED ON SIZE ERROR MOVE 0 TO DIFFERENCE DISPLAY '** ON SIZE ERROR **' END-DIVIDE DIVIDE ITEM-1 BY ITEM-3 ROUNDED REMAINDER ITEM-3 END-DIVIDE DIVIDE ITEM-1 INTO ITEM-2 GIVING RESULT ROUNDED REMAINDER ITEM-3 END-DIVIDE

Rounded
Rounds to the decimal digits in the PIC clause Allows you to handle arithmetic overflow conditions with imperative statements.

ON SIZE ERROR

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

Five separate Formats for DIVIDE (see Slide Notes)


31

Arithmetic Statements COMPUTE


WORKING-STORAGE SECTION. 01 INPUT-FIELDS. 05 ITEM-1 PIC S9(3)V99 VALUE 85.52. 05 ITEM-2 PIC S9(3)V99 VALUE 2.34. 05 ITEM-3 PIC S9(3)V99 VALUE 6.01. 05 RESULT PIC S9(5)V99. PROCEDURE DIVISION. COMPUTE RESULT ROUNDED = (ITEM-1 * ITEM-2 / ITEM-3).

Note:

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

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

--- will work

The COMPUTE 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, and DIVIDE 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 COMPUTE with COBOL intrinsic functions
32

COMPUTE Arithmetic Operators

Use the above arithmetic operators to in your COMPUTE statements The operations proceed as follows:
Unary Operators Multiplication/Division/Exponentiation Addition/Subtraction

from left to right within the COMPUTE and following the order of parenthesis

Thus, it's always a good idea to force an explicit arithmetic order of precedence using parenthesis in COMPUTE statements
These two statements are not algebraically equivalent:
COMPUTE RESULT ROUNDED = (ITEM-1 * ITEM-2 + ITEM-3). COMPUTE RESULT ROUNDED = (ITEM-1 * (ITEM-2 + ITEM-3)).
33

Intermediate 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) 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

Net:

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


Include decimal places in your literals:

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


34

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 principal interest nbrYears PIC PIC PIC PIC 9(7)V99. 9(7)V99. 9(2)V99. 9(4) COMP.

//Business logic in pseudo-code. //Initialize values amount = 0; principal = 10000.01; interest = .05; nbrYears = 10; //Invoke simple interest calculation function calculateSimpleInterest(); end

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


end
35

Unit

COBOL General Language Rules


Topics:
Assignment Statements and Internal Data Representation Math Operations
Conditional Logic

Transfer of control COBOL Looping Constructs Sequential File Processing Patterns Java and .NET Equivalents

36

COBOL Conditional Expressions


Two statement options: IF/ELSE EVALUATE statement
Both useful and have many language patterns and options (you'll see ) In general:
Use IF for coding:
Simple expressions Conditional statements with tests against multiple fields Complex statements with tests against multiple fields

Use EVALUATE 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 Notes


37

Conditional Statements IF Statement Overview


IF statement has two operational modes:
Alphanumeric compare:
On variables of type:
PIC X PIC A Group data items Alphanumeric literal
ELSE Statement Block

IF condition

THEN Statement Block

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


Comparison proceeds from Left-to-Right Alphanumeric range ( < or > ) is based on platform's collating sequence

END-IF

the

Shorter fields are padded with spaces (HEX '40') to length of longer variable
Regardless of which side of the IF statement is shorter/longer

Numeric comparison:
On variables of type PIC 9 or a numeric literal
Algebraic compare Decimal positions automatically aligned Note that overall, the IF statement comparison values must be "data type compatible"
38

IF Statement Examples
Simple IF - No ELSE
IF POLICY-OVERDUE-DAYS > 90 ADD +100 TO AMT-DUE END-IF _____________________________________________________________________ IF EMPLOYEE-SALARY-TYPE = "H" PERFORM 400-PROCESS-HOURLY-PAY ELSE IF EMPLOYEE-SALARY-TYPE = "S" PERFORM 400-PROCESS-SALARIED-PAY ELSE MOVE "***" TO EMPLOYEE-SALARY-TYP ADD +1 TO ERRORS-FOUND-KTR END-IF END-IF _____________________________________________________________________ IF HOURS-WORKED > 40 IF HOURLY-EMPLOYEE = "Y" IF NO-ERRORS-FOUND PERFORM 900-CALCULATE-HOURLY-OT END-IF END-IF END-IF _____________________________________________________________________ IF HOURS-WORKED > 40 AND HOURLY-EMPLOYEE = "Y" AND NO-ERRORS-FOUND PERFORM 900-CALCULATE-HOURLY-OT END-IF

IF/ELSE Note matching END-IF for each IF/ELSE

"Nested" IF/ELSE

Nested IF/ELSE refactored as IF with AND connectors Note only one END-IF

39

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. 2. 3. 4. 5. Class condition:
ALPHABETIC, NUMERIC, ALPHABETIC-UPPER

Condition-name condition:
88-LEVEL Data Items

Relation condition (value-based comparisons) Sign condition


POSITIVE, NEGATIVE, ZERO

Switch-status condition used with SPECIAL NAMES (rare)

Use Content-Assist (Ctrl/Spacebar) to view options


A complex condition is formed by combining simple conditions, combined conditions, and/or complex conditions with logical operators, or negating these conditions with logical negation: AND OR NOT 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
40

See Notes

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-2 PIC X(15). 77 ITEM-3 PIC 9(05). 88 VALID-ITEM VALUES ARE 11111, 22222. PROCEDURE DIVISION. Simple IF ITEM-1 > "10" Relation Condition MOVE "X" TO ITEMB ELSE PERFORM PROC-A END-IF
IF ITEM-1 > "10" Nested IF Relation IF ITEM-1 = ITEM-2 Condition ADD 1 TO ITEM-3 MOVE ALL "X" TO OUT-REC END-IF MOVE "X" TO ITEM-2 END-IF
41

IF ITEM-1 NUMERIC MOVE ITEM-1 TO ITEM-3 END-IF

Class Condition

IF VALID-ITEM Condition-Name Condition MOVE ITEM-2 TO ITEM-1 ELSE MOVE FUNCTION UPPER-CASE(ITEM-2) TO ITEM-1 END-IF IF ( ITEM-3 IS POSITIVE ) AND ( ITEM-1 NOT > ITEM-2 ) THEN IF ITEM-3 = 22222 THEN DISPLAY "22222-RECORD" ELSE DISPLAY "11111-RECORD" END-IF ELSE DISPLAY "BAD RECORD" END-IF
Complex Nested IF Relation Condition

Complex

IF NOT (ITEM-3 < 10 OR ITEM-3 > 500) AND ITEM-1 <= "Z" Complex Nested IF THEN DISPLAY "Done" Condition END-IF Combing
OR/AND

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 AND EMPLOYEE-ID < 3000 Can be coded as: IF EMPLOYEE-ID > 2000 AND < 3000
IF ITEM-1 NUMERIC AND > 10000 MOVE ITEM-1 TO ITEM-3 END-IF IF ITEM-2 = "AABBCC" OR "AACCDD" OR "AADDEE" MOVE ITEM-2 TO ITEM-1 ELSE MOVE FUNCTION UPPER-CASE(ITEM-2) TO ITEM-1 END-IF IF NOT (ITEM-3 < 10 OR > 500) ITEM-1 <= "Z" THEN DISPLAY "Done" END-IF AND

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

Examples of implied IF statement conditions

Might be misunderstood if merely browsing or scanning code


42

Bypassing Conditional Logic (NEXT SENTENCE and CONTINUE)


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:
IF ITEM-2 ALPHABETIC-UPPER

NEXT SENTENCE
ELSE MOVE FUNCTION UPPER-CASE(ITEM-2)TO ITEM-1 ADD +10 TO AMOUNT-SUB-TOTAL END-IF ADD +1 TO REC-KTR ADD REC-TOTAL TO WS-TOTAL-CLAIMS-PYMNTS WRITE OUTPUT-RECORD FROM WS-OUT-REC. GOBACK.

NEXT SENTENCE which branches to


the next sequential statement after an ending period or

CONTINUE 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

IF ITEM-2 ALPHABETIC-UPPER

CONTINUE
ELSE MOVE FUNCTION UPPER-CASE(ITEM-2)TO ITEM-1 ADD +10 TO AMOUNT-SUB-TOTAL END-IF ADD +1 TO REC-KTR ADD REC-TOTAL TO WS-TOTAL-CLAIMS-PYMNTS WRITE OUTPUT-RECORD FROM WS-OUT-REC. GOBACK.
43

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

Conditional Statements EVALUATE Statement

EVALUATE Statement

The EVALUATE statement is COBOL's version of the (in other programming languages) "case" or "switch) statement. EVALUATE provides a shorthand notation for a series of nested IF statements. When your program has to test a single variable for more than two values, EVALUATE is probably a better choice than nest IF
See next slide

WHEN condition TRUE Statement Block

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


You can a single WHEN condition You can use multiple WHEN statements when several conditions lead to the same processing action You can use a WHEN <value> THRU <value> phrase to easily code several conditions in a range of values You can specify "TRUE" or "FALSE" as the testing criteria and can combine with "ALSO"
44

WHEN condition TRUE Statement Block

WHEN OTHER

TRUE Statement Block

END-EVALUATE

EVALUATE versus Nested IF Statement Comparison Example 1


IF CARPOOL-SIZE = 1 THEN MOVE "SINGLE" TO PRINT-CARPOOL-STATUS ELSE IF CARPOOL-SIZE = 2 THEN MOVE "COUPLE" TO PRINT-CARPOOL-STATUS ELSE IF CARPOOL-SIZE >= 3 and CARPOOL-SIZE <= 6 THEN MOVE "SMALL GRP" TO PRINT-CARPOOL-STATUS ELSE MOVE "BIG GRP" TO PRINT-CARPOOL-STATUS END-IF END-IF END-IF EVALUATE CARPOOL-SIZE WHEN 1 MOVE "SINGLE" TO PRINT-CARPOOL-STATUS WHEN 2 MOVE "COUPLE" TO PRINT-CARPOOL-STATUS WHEN 3 THRU 6 MOVE "SMALL GRP" TO PRINT-CARPOOL STATUS WHEN OTHER MOVE "BIG GRP" TO PRINT-CARPOOL STATUS END-EVALUATE

Example 2
IF MARITAL-CODE = "M" THEN ADD 2 TO PEOPLE-COUNT ELSE IF MARITAL-CODE = "S" OR MARITAL-CODE = "D" OR MARITAL-CODE = "W" THEN ADD 1 TO PEOPLE-COUNT END-IF END-IF
45

EVALUATE MARITAL-CODE WHEN "M" ADD 2 TO PEOPLE-COUNT WHEN "S" WHEN "D" WHEN "W" ADD 1 TO PEOPLE-COUNT END-EVALUATE

Conditional Statements EVALUATE Complex Examples


FILE SECTION 01 OUT-REC PIC X(80). Working-Storage Section. 01 Age PIC 999. 01 Sex PIC X. 01 Description PIC X(15). 01 A PIC 999. 01 B PIC 9999. 01 C PIC 9999. 01 D PIC 9999. 01 E PIC 99999. 01 F PIC 999999. Evaluate True Also True When Age < 13 Also Sex = "M" Move "Young Boy" To Description When Age < 13 Also Sex = "F" Move "Young Girl" To Description When Age > 12 And Age < 20 Also Sex = "M" Move "Teenage Boy" To Description When Age > 12 And Age < 20 Also Sex = "F" Move "Teenage Girl" To Description When Age > 19 Also Sex = "M" Move "Adult Man" To Description When Age > 19 Also Sex = "F" Move "Adult Woman" To Description When Other Move "Invalid Data" To Description End-Evaluate Evaluate True Also True When A + B < 10 Also C = 10 Move "Case 1" To Description When A + B > 50 Also C = ( D + E ) / F Move "Case 2" To Description When Other Move "Case Other" To Description End-Evaluate
"True ALSO True" means that both conditions in the WHEN clause must be true
to take the WHEN path 46

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

47

Unit

COBOL General Language Rules


Topics:
Assignment Statements and Internal Data Representation Math Operations
Conditional Logic

Transfer of control COBOL Looping Constructs Sequential File Processing Patterns Java and .NET Equivalents

48

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

49

COBOL Transfer of Control Options


Three keywords used to transfer control in traditional COBOL
PERFORM
Branches to the first statement in a block of code
Inline Or, organized in a labeled paragraph or section somewhere else in the PROCEDURE DIVISION

At the end of the performed code, control is automatically returned to the next sequential instruction following PERFORM PERFORM is a statement with a number of useful options and extensions

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

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

Of the above three options:


PERFORM and CALL are best practices for "structured programming" GO TO is not a best practice, but we will present it, as you will see many examples of GO TO in production COBOL, and need to understand it
50

PERFORM External Paragraph or Section


Structured coding method of branching to and returning from COBOL paragraphs or sections With PERFORM, 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 PROCEDURE DIVISION. PERFORM 100-HOUSEKEEPING. PERFORM 300-MAINLINE-RTN. PERFORM 500-CLEANUP. GOBACK. 100-HOUSEKEEPING. PERFORM 150-INITIALIZE-FIELDS. PERFORM 200-OPEN-FILES. PERFORM 800-READ-RTN. 150-INITIALIZE-FIELDS. 200-OPEN-FILES. 300-MAINLINE-RTN. PERFORM 400-PROCESS-RECORD. PERFORM 700-WRITE-RTN. PERFORM 800-READ-RTN. 400-PROCESS-RECORD. 500-CLEANUP. PERFORM 900-CLOSE-FILES. 700-WRITE-RTN.

PERFORM
May be nested:
This is known as a "PERFORM chain" or a series of

PERFORM

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

May NOT be recursive: In this example, within 200-OPEN-FILES you may not PERFORM 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 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 with END-PERFORM


51

PERFORM THRU
One variation on PERFORM is PERFORM THRU
PERFORM THRU allows you to explicitly mark & bound the end of the PERFORM chain with a labeled paragraph

PROCEDURE DIVISION. PERFORM 100-HOUSEKEEPING THRU 100-EXIT. PERFORM 300-MAINLINE-RTN THRU 300-EXIT. PERFORM 500-CLEANUP THRU 500-EXIT. GOBACK. 100-HOUSEKEEPING. PERFORM 150-INITIALIZE-FIELDS THRU 150-EXIT. PERFORM 200-OPEN-FILES THRU 200-EXIT. PERFORM 800-READ-RTN THRU 800-EXIT. 100-EXIT. EXIT. 150-INITIALIZE-FIELDS. 150-EXIT. EXIT. 200-OPEN-FILES. 200-EXIT. EXIT.

All of the procedural statements between:


PERFORM <paragraphName> and THRU <paragraphName>

are executed The best practice is for the exit paragraph to have one COBOL reserved word in it: EXIT This returns control to the next sequential instruction in the perform chain Technically, you could PERFORM a COBOL paragraph THRU any other paragraph. However, this often leads to complex and unstructured code
Difficult to understand and maintain

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


52

See Slide Notes

Inline PERFORM
Another variation on PERFORM is what's known as an "inline perform"
An inline PERFORM 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 PERFORM is often used to control loops. PERFORM
<statement> <statement>
PROCEDURE DIVISION. PERFORM UNTIL END-OF-FILE IF NOT END-OF-FILE PERFORM 800-READ-INPUT-FILE IF NOT END-OF-FILE MOVE INPUT-REC TO OUTPUT-REC PERFORM 900-WRITE-RECORD ELSE MOVE HIGH-VALUES TO INPUT-REC PERFORM 1000-CLOSE-FILES DISPLAY 'NORMAL EOJ END-IF END-IF END-PERFORM. PERFORM VARYING IDX FROM 1 BY 1 UNTIL IDX > 100 MOVE REC-IN TO REC-TABLE(IDX) END-PERFORM.

END-PERFORM.

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

53

Scope Terminators and Paragraph Names


You have seen that many of the COBOL statements can have Scope Terminators:
END-IF END-READ END-COMPUTE
100-HOUSEKEEPING. IF ITEM-2 = "AABBCC" OR "AACCDD" OR "AADDEE" MOVE ITEM-2 TO ITEM-1 ELSE MOVE ITEM-3 TO ITEM-1 END-IF 100-EXIT. This will not compile! EXIT.

This is actually a coding best practice However, the last statement before the paragraph (or "exit paragraph") must end in a period.
Type a period after END-IF
100-HOUSEKEEPING. IF ITEM-2 = "AABBCC" OR "AACCDD" OR "AADDEE" MOVE ITEM-2 TO ITEM-1 ELSE MOVE ITEM-3 TO ITEM-1 END-IF. 100-EXIT. EXIT.

54

GO TO Unconditional Transfer of Control


GO 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"
PROCEDURE DIVISION. PERFORM 100-HOUSEKEEPING THRU 100-EXIT. PERFORM 300-MAINLINE-RTN THRU 300-EXIT. GOBACK. 100-HOUSEKEEPING. PERFORM 200-OPEN-FILES THRU 200-EXIT. PERFORM 800-READ-RTN THRU 800-EXIT. IF END-OF-FILE DISPLAY "END-OF-JOB" PERFORM 900-CLOSE FILES THRU 900-EXIT

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


Difficult to read Very difficult to maintain and modify

The use of GO TO is universally denounced in the academic computing world


And we agree except for under one very key and common design pattern (combining GO TO with PERFORM THRU)

GO TO 100-EXIT
ELSE ADD +1 TO REC-KTR MOVE ZEROS TO AMOUNT-TOT END-IF Perform 300-INIT-FIELDS. 100-EXIT. EXIT.

Our "Best Practices" advice:


Do not use GO TO in COBOL coding, for transferring control
EXCEPT under one condition when you are using GO TO - for branching to the exit paragraph in a PERFORM THRU

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

Transfer 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 PERFORM THRU paragraphs Within the paragraphs code anything you need to satisfy your business logic requirements, including:
CALLs to external programs CALL is covered in an upcoming unit Nested PERFORM Inline PERFORM Sequence and conditional logic GO TO BUT ONLY GO TO a PERFORM THRU paragraph EXIT

Try not to use COBOL SECTIONs


Within COBOL SECTIONs COBOL paragraphs are considered at the level of statements blocks of code where fall through will occur The only time you will need a COBOL SECTION is when you're programming is invoking the COBOL SORT verb (which is tied to INPUT and OUTPUT SORT SECTIONs)

56

Unit

COBOL General Language Rules


Topics:
Assignment Statements and Internal Data Representation Math Operations
Conditional Logic

Transfer of control COBOL Looping Constructs Sequential File Processing Patterns Java and .NET Equivalents

57

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.

58

COBOL Looping Options


There are three COBOL programming ways to loop:
GO TO <paragraphName> combined with an IF condition that ends the loop:
Unstructured creates complex, un-maintainable code NOT a best practice hence will not be covered

PERFORM <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> UNTIL a condition is met


Structured ("Good") Can be used when the number of loop iterations is variable or known

Net: Use PERFORM <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


59

PERFORM <paragraphName> n TIMES


Can PERFORM a paragraph a specified number of times, in a loop controlled by a:
Numeric literal Numeric integer variable

WORKKING-STORAGE SECTION. 77 NBR-REPS S9(4) COMP. PROCEDURE DIVISION.

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

PERFORM 300-MAINLINE-RTN THRU 300-EXIT 12 TIMES.


GOBACK. 300-MAINLINE-RTN. MOVE IN-REC-KTR TO NBR-REPS.

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

PERFORM 310-SUBTOTALS THRU 310-EXIT NBR-REPS TIMES.


300-EXIT. EXIT.

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

PERFORM UNTIL <condition>


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

PROCEDURE DIVISION. PERFORM 100-HOUSEKEEPING THRU 100-EXIT.

PERFORM 300-MAINLINE-RTN THRU 300-EXIT UNTIL NO-MORE-RECORDS.


GOBACK. 100-HOUSEKEEPING. OPEN INPUT IN-FILE. PERFORM 800-READ-RTN THRU 800-EXIT. 100-EXIT. EXIT. 300-MAINLINE-RTN. PERFORM 800-READ-RTN. 300-EXIT. EXIT. 800-READ-RTN. READ IN-FILE INTO WS-RECORD AT END MOVE 'Y' TO SW-NO-MORE-RECORDS. 800-EXIT. EXIT.

UNTIL
Tests a condition for TRUE/FALSE
If NOT TRUE (repeat if the condition is FALSE) PERFORM the specified Paragraph If TRUE End the loop Return program control to the next sequential instruction following the PERFORM 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 UNTIL (next slide)
61

PERFORM UNTIL With TEST BEFORE or AFTER


PERFORM UNTIL may be modified by
one of two clauses, coded before UNTIL and after the paragraph name: 1. WITH TEST BEFORE
The UNTIL condition is tested before each PERFORM execution. The Paragraphs will be executed 0 or more times Is the default if this clause is left unspecified

PROCEDURE DIVISION. PERFORM 100-HOUSEKEEPING THRU 100-EXIT.

PERFORM 300-MAINLINE-RTN THRU 300-EXIT

WITH TEST BEFORE


UNTIL NO-MORE-RECORDS.
GOBACK. 100-HOUSEKEEPING. OPEN INPUT IN-FILE. PERFORM 800-READ-RTN THRU 800-EXIT. 100-EXIT. EXIT. 300-MAINLINE-RTN. PERFORM 800-READ-RTN. 300-EXIT. EXIT. 800-READ-RTN. READ IN-FILE INTO WS-RECORD 800-EXIT. EXIT.

2. WITH TEST AFTER


The UNTIL condition is tested after each PERFORM execution. The Paragraphs will be executed 1 or more times

62

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

63

Unit

COBOL General Language Rules


Topics:
Assignment Statements and Internal Data Representation Math Operations
Conditional Logic

Transfer of control COBOL Looping Constructs Sequential File Processing Patterns Java and .NET Equivalents

64

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
65

Sequential File Processing


Sequential File Processing consists of a well-documented set of processing or a pattern that you will see in many program requirements
You read one or more input files until:
Your business logic requirements are fulfilled End-of-File Edit or evaluate data Add numeric values to total and sub-total fields perform business calculations Assign (MOVE) values WRITE output record(s) either to an output file, report or both Bad or invalid data (and know what to do about it when it shows up in your fields) Empty input files READ/WRITE I/O errors that may occur WRITE a final output record, with summary computed values CLOSE all files DISPLAY a successful end-of-job message
Record Buffer Record Buffer

While reading files you typically:

You must be cognizant of:

After reaching end-of-file you will typically:


Output Report

Note - more than likely NOT a tape Device

Input File

COBOL Program Business Logic

Output File

66

Sequential File Processing Pattern Simple Batch Design Pattern


This first batch application pattern "Process One Input File" consists of the following pattern Perform an initialization routine
Initialize values in Working-Storage OPEN the files for either input or output PERFORM a "priming" input-record read an initial read statement that simplifies:
Empty input-file-processing problems Reading past end-of-file logic problems

Perform a process-the-file routine, until end-of-input-file


Validate the data using the conditional logic statements learned in this unit Move the data using the assignment statements learned in this unit Do computations, calculations, etc. using the COBOL math statements Write the record Read the next input record

Perform an end-of-job routine


Complete final computations WRITE final output record with final computations CLOSE all files and display an end-of-job message on the Console
67

File I/O Review OPEN


ENVIRONMENT DIVISION. External Device INPUT-OUTPUT SECTION. External File SELECT INTFILENAME ASSIGN TO DATA DIVISION. FILE SECTION Record Buffer FD INTFILENAME 01 OUT-REC. Recall the following: PROCEDURE DIVISION. SELECT/ASSIGN connects your internal (logical) filename with

OPEN INPUT FILE1, FILE2 OUTPUT FILE3, FILE4.

external (physical) file-spec FILE SECTION is required for each SELECT/ASSIGN file OPEN references the logical (internal) filename Can OPEN multiple files with one statement (as shown)

See Slide Notes, for

Note carefully the syntax for OPEN


68

additional learning content

File I/O Review READ INTO


ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. SELECT INTFILENAME ASSIGN TO DATA DIVISION. FILE SECTION FD INTFILENAME Record Buffer 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-REC AT END MOVE Y to END-OF-FILE-FLAG.
External Device External File

F I L E R E A D

Recall the following:


File must be OPEN before you try to READ from it READ retrieves each record from an external file: - Into the record specified in your FILE SECTION - Into WORKING-STORAGE - if you've coded READ INTO AT END condition occurs after the last record is READ from the file - If you attempt to read past end-of-file your program will ABEND
69

See Slide Notes,


for additional learning content

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

File I/O Review WRITE FROM


ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. SELECT OUTFILENAME ASSIGN TO DATA DIVISION. FILE SECTION FD OUTFILENAME Record Buffer 01 OUT-REC. WORKING-STORAGE SECTION 01 OUT-REC-WS. PROCEDURE DIVISION. OPEN OUTPUT OUTFILENAME.
External Device External File
W R I T E O P E R A T I O N

WRITE OUT-REC FROM OUT-REC-WS.

Recall the following:


File must be OPEN before you try to WRITE a record to it
- An ABEND condition occurs, if try to write to an un-opened file

See Slide Notes,


for additional learning content

WRITE creates a new record at the end of a sequential/external file: - From the record specified in your FILE SECTION - From WORKING-STORAGE - if you've coded WRITE FROM

Close opened output files before your program ends


70

File I/O Review CLOSE


ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. SELECT INTFILENAME ASSIGN TO DATA DIVISION. FILE SECTION Record Buffer FD INTFILENAME 01 OUT-REC. PROCEDURE DIVISION. Recall
F I L E C L O S E

External Device External File

the following:

CLOSE FILE1, FILE2, FILE3, FILE4.

CLOSE every opened file


- Input file - Output file

Can CLOSE multiple files with one statement (as shown) Can re-OPEN a file after closing

Note carefully the syntax for CLOSE

See Slide Notes, for additional learning content


71

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.

PROCEDURE DIVISION. Do Init-Routine Do Process-Files until No-More-Data Do End-of-Job-Routine GOBACK. Init-Routine. Open files READ Input-File Process-Files. Validate input data Perform calculations and sub-totals Move data to output Record Write Output-Record READ Input-File End-of-Job-Routine. Final computations Move Data to output Record Write output record Close Files

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

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 File Assign to COBOL (internal) file name

FILE SECTION FDs Matching the SELECT/ASSIGN Clauses for each external file

Note this example continues over the next three slides


73

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


File Status fields Automatically updated By COBOL and the O.S.

A final-totals output record

Input and Output records You will often see these coded in WORKINGSTORAGE because they are easier to find in a System log file (called a DUMP file) if your program files (ABENDS) when executing on the mainframe

Holding fields for intermediate result calculations and values

74

A Complete Example of a Sequential File Processing Program PROCEDURE DIVISION


E D I T S

Processing Calculations Computations

Our Sequential File Pattern in COBOL Read the code line-by-line (as if you were debugging it In other words, if there's a PERFORM jump down to the Performed paragraph. When finished jump back, etc.) Note the use of: PERFORM THRU AT END/GO TO "EXIT" PERFORM UNTIL For each record in the input file, do 100-MAINLINE Write the current record Read the next record in the file
75

M O V E

A Complete Example of a Sequential File Processing Program No More Records in the File

When there are no more records left to process


Do final calculations Move the fields to final output record WRITE CLOSE all files Display a message on the console

76

Lab Assignment From the course workshop documents, do the following labs:
1. Process Input File1 2. Process InputFile2

77

Unit

COBOL General Language Rules


Topics:
Assignment Statements and Internal Data Representation Math Operations
Conditional Logic

Transfer of control COBOL Looping Constructs Reading and Writing Files - Review Java and .NET Equivalents

78

Java .NET COBOL Equivalents


COBOL
MOVE (elementary field) MOVE (group field move) MOVE CORRESPONDING MOVE with OF qualifier ADD SUBTRACT MULTIPLY DIVIDE COMPUTE IF/ELSE AND/OR EVALUATE PERFORM PERFORM THRU

JAVA
Java variable assignment (right to left) Java OBJECT assignment (right to left) N/A Qualified assignment var1.var2.var3 Standard math computation (no separate statement) " " " " If case Method invocation While or FOR method invocation

VB.NET
Variable assignment (right to left) Variable assignment (right to left) N/A Qualified assignment var1.var2.var3 Standard math computation (no separate statement) " " " " If case Method invocation While or FOR method invocation

COBOL Paragraphs and Sections


GO TO PERFORM THRU UNTIL OPEN CLOSE WRITE READ ACCEPT DISPLAY

Java Labels
Break/Continue can refer to a Label (same behavior as GO TO EXIT) While or FOR method invocation //comment, as Java opens files automatically DataInputStream.close() DataInputStream/BufferedInputStream/FileInputStream DataInputStream/BufferedInputStream/FileInputStream Java.util.Scannner (System.in) System.out.println

Label
Break/Continue can refer to a Label (same behavior as GO TO EXIT) While or FOR method invocation OPEN() CLOSE() StreamWriter/BinaryWriter StreamReader/BinaryReader Console.Read Console.WriteLine or Console.Write

79

Anda mungkin juga menyukai