Enterprise COBOL Education Using Rational Developer for System Z Module 3 Basic COBOL Statements
Jon Sayles, IBM Software Group, Rational EcoSystems Team
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 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
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
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
10
11
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
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 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
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
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)
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
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
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
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.
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
PIC X(10) VALUE 'SMITH'. PIC X(01) VALUE 'A'. PIC X(10) VALUE 'ALEXANDER'.
19
Syntax:
<to-variable>.
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:
<to-group-variable>.
See Notes
You can also INITIALIZE fields, replacing classes of datatypes with specific values
This is used less frequently, and is shown in the slide
notes
22
to to to to TO
Syntax:
<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
Transfer of control COBOL Looping Constructs Sequential File Processing Patterns Java and .NET Equivalents
25
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
RANDOM RANGE REM REVERSE SIN SQRT STANDARD-DEVIATION SUM TAN VARIANCE
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
***See Notes
Value: 040156
Value: 000000
28
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
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
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
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
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
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
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:
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
Unit
Transfer of control COBOL Looping Constructs Sequential File Processing Patterns Java and .NET Equivalents
36
IF condition
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
"Nested" IF/ELSE
Nested IF/ELSE refactored as IF with AND connectors Note only one END-IF
39
Condition-name condition:
88-LEVEL Data Items
See Notes
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
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
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.
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
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 OTHER
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
Lab Assignment From the course workshop documents, do the following labs:
1. Conditionals Lab
47
Unit
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
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
PERFORM
May be nested:
This is known as a "PERFORM chain" or a series of
PERFORM
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.
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.
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
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.
53
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 100-EXIT
ELSE ADD +1 TO REC-KTR MOVE ZEROS TO AMOUNT-TOT END-IF Perform 300-INIT-FIELDS. 100-EXIT. EXIT.
This honors the Perform Chain and execution will not "fall through"
55
56
Unit
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
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
Examples:
Performs all of the COBOL statements between 300-MAINLINE-RTN and 300-EXIT 12 TIMES
Performs all of the COBOL statements between 310-SUBTOTALS and 310-EXIT the number of times represented by the integer value in NBR-REPS
Use PERFORM n TIMES when you know during development how many loop iterations should be performed at run-time.
60
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
62
Lab Assignment From the course workshop documents, do the following labs:
1. COBOL Looping Lab
63
Unit
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
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
Input File
Output File
66
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)
F I L E R E A D
* Note that the DATA DIVISION's FILE SECTION is sometimes referred to as an I/O "buffer"
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
the following:
Can CLOSE multiple files with one statement (as shown) Can re-OPEN a file after closing
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
FILE SECTION FDs Matching the SELECT/ASSIGN Clauses for each external file
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
74
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
76
Lab Assignment From the course workshop documents, do the following labs:
1. Process Input File1 2. Process InputFile2
77
Unit
Transfer of control COBOL Looping Constructs Reading and Writing Files - Review Java and .NET Equivalents
78
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
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