Presentation is loading. Please wait.

Presentation is loading. Please wait.

Jon Sayles, IBM Software Group, Rational EcoSystems Team

Similar presentations


Presentation on theme: "Jon Sayles, IBM Software Group, Rational EcoSystems Team"— Presentation transcript:

1 Jon Sayles, IBM Software Group, Rational EcoSystems Team
Enterprise COBOL Education Using Rational Developer for System Z COBOL General Language Rules Jon Sayles, IBM Software Group, Rational EcoSystems Team

2 IBM Trademarks and Copyrights
© Copyright IBM Corporation 2007,2008, 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.

3 Course Contributing Authors
Thanks to the following individuals, for assisting with this course: David Myers/IBM, Ka Yin Lam/IBM John Fenyar Wilbert Kho/IBM Steven Wilcenski/Sabre Systems Inc. Mike Wrzinski/Sentry Insurance

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 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 Sequential File Match/Merge Patterns COBOL Subprograms and the Linkage Section Structured Programming Concepts 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 and Master File Update Coding Patterns Accessing DB2 Data and 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

5 COBOL General Language Rules
Unit COBOL General Language Rules Topics: Coding COBOL Identifying Your Program Describing Your Computing Environment Describing the Data Processing the Data Java and .NET Equivalents

6 Topic objectives After completing this topic, you should be able to:
Describe the areas of COBOL structured coding – and what kind of COBOL statements go into each Define the four DIVISIONs of a COBOL program List the kinds of alphanumeric characters that can be used in coding COBOL programs

7 COBOL Character Set COBOL code is written using:
Alphanumeric characters: A  Z 0  9 The following special characters: + - * / = $ : . , ; “ ‘ ( ) < >  Note – no underscore Upper and lower case characters are equivalent (case insensitive), except when they appear in a character string On the mainframe, the character set – and collating sequence is EBCDIC On the PC and on AIX systems, the character set and collating sequence is ASCII The differences between EBCDIC manifest themselves at run-time in: Alphanumeric sort routines and operations IBM built-in functions that process sorted data (Median, etc.)

8 Statement Format (Basic COBOL Coding Rules)
COBOL program development uses a fixed-column or fixed-position coding style: Statements must be coded within specified column-numbered area boundaries Columns 1  6 contain an optional (rarely used) sequence number for ordering statements Column 7 indicates either: COBOL comment line – by typing an asterisk * in column 7 Multi-line continuation of long literal values - by typing a dash – in column 7 Columns 8  11 are called the “A” or area – with column 8 termed the “A” margin. Columns 8  11 are reserved for: Division statements Procedure names Certain types of variable declarations Columns 12  72 are called the “B” area – you code all of your procedural (business) logic here, as well as the rest of the variable declarations Columns 73  80 are used by certain Source Code Management Systems for identifying line changes in versions. Sequence Numbers A Area B Area Version Control Numbers Note that column if column 7 contains a forward slash, it forces a page break, when printing See Slide Notes

9 COBOL Program Units (The Four Divisions)
Identification Division IDENTIFICATION DIVISION, which identifies the program with a name and, if optionally gives other identifying information. ENVIRONMENT DIVISION, where you describe the aspects of your program that depend on the computing environment. DATA DIVISION, where the characteristics of your data are defined PROCEDURE DIVISION, where the instructions related to your business logic are specified. The PROCEDURE DIVISION of a program is sub-divided into sections or paragraphs, which contain executable COBOL sentences and statements  The Divisions must be coded in the order described There are many optional statements and keywords in the Divisions Division and procedure (Paragraph and Section) names: Begin in the A margin, must end with a period, and must be the only statement on that line Your program ends when either a GOBACK or STOP RUN statement is executed Environment Division Data Division Notes: One way to remember about the four divisions, is to use the following word-sequence: "PIED Piper" Procedure Division Identification Division Environment Division Data Division Thanks to John Fenyar Procedure Division See Notes

10 COBOL General Language Rules
Unit COBOL General Language Rules Topics: Coding COBOL Identifying Your Program Describing Your Computing Environment Describing the Data Processing the Data Java and .NET Equivalents

11 Topic objectives After completing this topic, you should be able to:
Describe the purpose of the IDENTIFICATION DIVISION List the required elements of it Code a syntactically correct IDENTIFICATION DIVISION List a few optional paragraphs and sections of the IDENTIFICATION DIVISION

12 Identifying Your Program – Standard Grammar
IDENTIFICATION DIVISION. Program-ID. PROGRAM1. Author. Bill Hudson. Installation. Computing Labs Inc. Date-Written. 12/21/2009. Date-Compiled. 12/30/2009. Use the IDENTIFICATION DIVISION to name a program and optionally provide other identifying information. Required statements: PROGRAM-ID. PROGNAME. You can use the optional AUTHOR, INSTALLATION, DATE-WRITTEN, and DATE-COMPILED paragraphs for descriptive information about a program. The data you enter in the DATE-COMPILED paragraph is replaced with the latest compilation date.

13 IDENTIFICATION DIVISION – PROGRAM-ID
z/Series COBOL COBOL Program-ID names must follow these rules: For mainframe (z/OS) COBOL programs: Traditionally eight characters That restriction has been lifted in current language levels Name must start with an alphabetic letter Name can contain only alpha-numerics (letters and 0 – 9) For PC (“standard”) COBOL programs: Maximum of thirty characters Name can contain: Alpha-numerics The dash Cannot start or end the Program-ID name with a dash  Note: It is good programming practice to add in-line comments to the top of your COBOL program. Comments that document: The business/technical purpose of the program A program maintenance log Any unusual or complex coding patterns PC COBOL OO COBOL capabilities and language features: The ability to define classes, comprising class object definitions and object definitions. The ability to define data encapsulated inside class objects and objects. The ability to define methods for class objects and objects. The ability to use inheritance and define subclasses. The ability to use polymorphism and interfaces for maximum flexibility. The ability to define data items able to hold references to objects. The ability to invoke methods on objects. The ability to create and manage objects as required. The ability to use objects as a normal part of COBOL programming in developing new programs and maintaining existing programs. RECURSIVE optional clause that allows COBOL programs to be recursively reentered. You can specify the RECURSIVE clause only on the outermost program of a compilation unit. Recursive programs cannot contain nested subprograms. If the RECURSIVE clause is specified, program-name can be recursively reentered while a previous invocation is still active. If the RECURSIVE clause is not specified, an active program cannot be recursively reentered. The working-storage section of a recursive program defines storage that is statically allocated and initialized on the first entry to a program and is available in a last-used state to any of the recursive invocations. The local-storage section of a recursive program (as well as a nonrecursive program) defines storage that is automatically allocated, initialized, and deallocated on a per-invocation basis. Internal file connectors that correspond to an FD in the file section of a recursive program are statically allocated. The status of internal file connectors is part of the last-used state of a program that persists across invocations. The following language elements are not supported in a recursive program: ALTER GO TO without a specified procedure-name RERUN SEGMENT-LIMIT USE FOR DEBUGGING The RECURSIVE clause is required for programs compiled with the THREAD option. INITIAL Specifies that when program-name is called, program-name and any programs contained (nested) within it are placed in their initial state. When a program is in the initial state, the following occur: The program's internal data contained in the working-storage section is initialized. If a VALUE clause is used in the description of the data item, the data item is initialized to the defined value. If a VALUE clause is not associated with a data item, the initial value of the data item is undefined. Files with internal file connectors associated with the program are not in the open mode. The control mechanisms for all PERFORM statements contained in the program are set to their initial states. An altered GO TO statement contained in the program is set to its initial state.

14 IDENTIFICATION DIVISION – Optional Statements and Constructs
You can extend the PROGRAM-ID paragraph, with the following optional keywords that compile programs to allow for extended functionality: RECURSIVE – allows a program to be reentrant and called recursively PROGRAM-ID MYPROG IS RECURSIVE. INITIAL – tells the compiler to reset variables to specified initial values upon program execution PROGRAM-ID MYPROG IS INITIAL. CLASS-ID. Enterprise COBOL provides facilities for developing object-oriented programs using the COBOL programming language. OO COBOL programs contain a CLASS-ID paragraph, for defining an OO class, instead of PROGRAM-ID, which defines a structured program OO COBOL will be touched on later in this course, as it is considered an “emerging z/Series technology” in most I/T installations See slide notes for additional information on OO COBOL OO COBOL capabilities and language features: The ability to define classes, comprising class object definitions and object definitions. The ability to define data encapsulated inside class objects and objects. The ability to define methods for class objects and objects. The ability to use inheritance and define subclasses. The ability to use polymorphism and interfaces for maximum flexibility. The ability to define data items able to hold references to objects. The ability to invoke methods on objects. The ability to create and manage objects as required. The ability to use objects as a normal part of COBOL programming in developing new programs and maintaining existing programs. RECURSIVE optional clause that allows COBOL programs to be recursively reentered. You can specify the RECURSIVE clause only on the outermost program of a compilation unit. Recursive programs cannot contain nested subprograms. If the RECURSIVE clause is specified, program-name can be recursively reentered while a previous invocation is still active. If the RECURSIVE clause is not specified, an active program cannot be recursively reentered. The working-storage section of a recursive program defines storage that is statically allocated and initialized on the first entry to a program and is available in a last-used state to any of the recursive invocations. The local-storage section of a recursive program (as well as a nonrecursive program) defines storage that is automatically allocated, initialized, and deallocated on a per-invocation basis. Internal file connectors that correspond to an FD in the file section of a recursive program are statically allocated. The status of internal file connectors is part of the last-used state of a program that persists across invocations. The following language elements are not supported in a recursive program: ALTER GO TO without a specified procedure-name RERUN SEGMENT-LIMIT USE FOR DEBUGGING The RECURSIVE clause is required for programs compiled with the THREAD option. INITIAL Specifies that when program-name is called, program-name and any programs contained (nested) within it are placed in their initial state. When a program is in the initial state, the following occur: The program's internal data contained in the working-storage section is initialized. If a VALUE clause is used in the description of the data item, the data item is initialized to the defined value. If a VALUE clause is not associated with a data item, the initial value of the data item is undefined. Files with internal file connectors associated with the program are not in the open mode. The control mechanisms for all PERFORM statements contained in the program are set to their initial states. An altered GO TO statement contained in the program is set to its initial state.

15 COBOL General Language Rules
Unit COBOL General Language Rules Topics: Coding COBOL Identifying Your Program Describing Your Computing Environment Describing the Data Processing the Data Java and .NET Equivalents

16 Topic objectives After completing this topic, you should be able to:
Describe the purpose of the ENVIRONMENT DIVISION List the required elements of it Code a syntactically correct ENVIRONMENT DIVISION List a few optional paragraphs and sections of the ENVIRONMENT DIVISION

17 Environment Division – Standard Grammar
CONFIGURATION SECTION. SOURCE-COMPUTER. IBM-3081. OBJECT-COMPUTER. IBM-3081. INPUT-OUTPUT SECTION. SELECT PRINTFILE ASSIGN TO UPDPRINT ORGANIZATION IS SEQUENTIAL. Use the ENVIRONMENT DIVISION to identify input and output files for the program, and to describe aspects of the program that depend on the computing platform. ENVIRONMENT DIVISION and its sections can be optional. That is, you will code them when you need to specify elements of your program that connect to the operational environment your program runs in (example. Reading and writing to external files) The ENVIRONMENT DIVISION has two sections: CONFIGURATION SECTION – Optional section, used to specify the development and run: Source-Computer – the compiling computer. Object-Computer – the run-time computer INPUT-OUTPUT SECTION – Used to define external files used by the program (files are considered part of your program’s “environment”) The SELECT/ASSIGN statement is covered on the next slide  Note that: ENVIRONMENT DIVISION, CONFIGURATION SECTION and INPUT-OUTPUT SECTION are coded in the “A” area of your source code

18 Select/Assign – Input/Output Files and Datasets/Devices
The FILE-CONTROL part of the INPUT-OUTPUT SECTION identifies the external files your program reads and writes using COBOL “logical” name identifiers These logical file names in your program, are mapped to a physical input/output storage device attached to a mainframe (typically disk storage) By using Select/Assign in your program, you achieve Physical/Logical data independence - so you won’t have to change your code: If you move the physical file to a different device If you point to an altogether different file entirely All your program cares about is the internal (logical) file name in Select/Assign The system is responsible to find and attach the correct external dataset Your program source… ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT INPUT ASSIGN TO INPUT1 (your program’s internal COBOL filename) The mainframe “job” that runs your program //GO.INPUT1 DD DSN=MY.INPUT,DISP=SHR Your Program External z/OS Dataset (file) MY.INPUT Mainframe 3990 Disk Pack

19 ENVIRONMENT DIVISION – Assigning Input/Output Files to Your PC
For the programs in this course, you will use the ENVIRONMENT DIVISION’s SELECT/ASSIGN clauses to point to ASCII files on your machine. So your “environment” is the PC, not the mainframe  You will code your Select/Assign clauses for PC files like the following: ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT CUST-FILE ASSIGN TO "D:\CUST.DAT" ORGANIZATION IS LINE SEQUENTIAL ACCESS MODE IS SEQUENTIAL FILE STATUS IS CFCODE. SELECT PRINT-FILE ASSIGN TO "D:\CUSTOUT.DAT" FILE STATUS IS PRTCODE. See Slide Notes, for additional File Read/Write performance tips Internal file name PC file spec: Drive:\folder\filename.extension Tells the compiler how to treat the file's I/O Names a variable you can check for I/O errors Optimizing buffer and device space Use the APPLY WRITE-ONLY clause to make optimum use of buffer and device space when you create a sequential file with blocked variable-length records. With APPLY WRITE-ONLY specified, a buffer is truncated only when the next record does not fit in the unused portion of the buffer. Without APPLY WRITE-ONLY specified, a buffer is truncated when it does not have enough space for a maximum-size record. The APPLY WRITE-ONLY clause has meaning only for sequential files that have variable-length records and are blocked. The AWO compiler option applies an implicit APPLY WRITE-ONLY clause to all eligible files. The NOAWO compiler option has no effect on files that have the APPLY WRITE-ONLY clause specified. The APPLY WRITE-ONLY clause takes precedence over the NOAWO compiler option. The APPLY-WRITE ONLY clause can cause input files to use a record area rather than process the data in the buffer. This use might affect the processing of both input files and output files.

20 COBOL General Language Rules
Unit COBOL General Language Rules Topics: Coding COBOL Identifying Your Program Describing Your Computing Environment Describing Your Program’s Data Processing the Data Java and .NET Equivalents

21 Topic objectives After completing this topic, you should be able to:
Describe the purpose of the DATA DIVISION List the required elements of it Code a syntactically correct DATA DIVISION List a few optional paragraphs and sections of the DATA DIVISION

22 Identifying and Describing Your Program’s Data – Standard Grammar
DATA DIVISION. FILE SECTION. WORKING-STORAGE SECTION. LINKAGE SECTION. One of COBOL’s fortes is file handling and data manipulation – which COBOL makes: Simple – easy to code Efficient – as pertains to run-time processing efficiency) Sophisticated – allowing for complex data types and structures Define the characteristics of your data, and group your data definitions into one of the sections in the DATA DIVISION. You can use these sections of the DATA DIVISION to define the following types of data: Data used in input-output operations (FILE SECTION) Data defined for internal processing purposes, calculation fields, flags, counters, etc. (WORKING-STORAGE SECTION) Data passed as parameters from another program (LINKAGE SECTION)

23 FILE SECTION – Data used in File Input/Output Operations
DATA DIVISION. FILE SECTION. FD internalFileName RECORD CONTAINS n CHARACTERS DATA RECORD IS recordVariable. 01 recordVariable. 05 Field1 PIC X(40). 05 Field2 PIC X(40). Every Select/Assign file in the INPUT-OUTPUT SECTION of the ENVIRONMENT DIVISION must have a matching FD (File Definition) entry in the FILE SECTION You follow an FD by the declaration of the data record the file is read into/written from The RECORD CONTAINS clause is optional – but if explicitly coded, it causes the compiler to verify the DATA RECORD’s overall length with the “n CHARACTERS” specified The DATA RECORD clause is also optional, and specifies the COBOL variable that will be read into, or written from. . FILE SECTION, FD and the 01 level-number for the record variable are coded in the “A” area All other clauses and level-numbers > 01 must begin in the “B” area  Note that we'll cover COBOL level-numbers in a few slides

24 FILE SECTION – Optional Clauses
DATA DIVISION. FILE SECTION. FD internalFileName BLOCK CONTAINS n RECORDS LABEL RECORDS ARE STANDARD. BLOCK CONTAINS – defines a “blocking factor” for the file. Blocking factors are I/O efficiency features of COBOL and z/OS We will cover them later in the course For mainframe COBOL programs: Recommendation - code: BLOCK CONTAINS 0 RECORDS This allows the compiler to obtain the Blocking Factor directly from the program’s JCL For PC COBOL programs: Recommendation – leave this clause out LABEL RECORDS ARE STANDARD – determines whether there is a label on the z/OS dataset (external file). -LABEL RECORDS ARE STANDARD is the default if you omit the clause -Leave this clause off for PC files, print files and non-labeled datasets Label Records allows you to control the job execution (disk file, tape file and contains data such as date created, block size, etc). See Notes

25 WORKING-STORAGE SECTION – Declaring Program Work Variables
DATA DIVISION. FILE SECTION. WORKING-STORAGE SECTION. RECORD-KTR PIC 9(4). 77 END-OF-FILE-SW PIC X(1) VALUE 'N'. 01 StructureVariable. 05 Elementary-num-field PIC 9(4). 05 Elementary-char-field PIC X(40). The WORKING-STORAGE SECTION is where you code variables used throughout your program All of the variables in the WORKING-STORAGE SECTION are global in scope (can be referenced throughout your program) Use WORKING-STORAGE variables for: Temporary fields used in calculations Variable names for constant values Record structures used in data manipulation processing Switches and flags (i.e. end-of-file) Print file records and structures

26 WORKING-STORAGE SECTION – Coding COBOL Variables
RECORD-KTR PIC 9(4) COMP VALUE ZERO. 77 KTR-2 PIC 9999 COMP VALUE ZERO. 01 STRUCTURE-VARIABLE. 05 ELEM-FIELD PIC 9(7)V99 COMP-3 VALUE ZERO. 05 END-OF PIC X(40). COBOL variable names: Can use alphanumerics and the dash (but don’t start or end a variable name with a dash) Must be shorter than 30 characters, no embedded blanks , and contain at least one letter Code individual (single) COBOL variables as follows: Type a 77 in the “A” area Type the variable name in the “B” area Follow the variable name with a “picture clause” – typically abbreviated as: PIC – that describes the type, size and scale of your variable End with the variable declaration with a period Code (related) variables grouped into a structure as follows: Type a 01 in the “A” area Type the structure name in the “B” area Type the remaining variables starting with a number > 01 in the “B” area and follow the above rules for coding 77 variables  See Slide Notes – for an explanation of COMP and COMP-3 COBOL provides qualifiers for Picture (PIC) clauses for different types of internal data representation. COMP – binary data COMP-3 – Packed decimal data Fields defined as COMP & COMP-3 are used for internal computations and data storage – not for displaying directly on reports and screens. In subsequent course units we will discuss fully, the aspects of internal data representation and COBOL variable clauses used

27 WORKING-STORAGE SECTION – PICTURE Clause Definitions
Every COBOL data variable must have a picture clause – typically abbreviated as: PIC A variable’s picture clause determines: The type and format of the data stored in the field Size of the data Numeric precision (scale, or # of digits to the right and left of the decimal place) You can code a number inside a parenthesis, which means that the preceding character is repeated “n” times (see below) Different PIC clauses are used for input and intermediate calculation results or holding areas and for output.  Note: We’ll cover input and output picture clauses in-depth, in a subsequent unit of this course. The Input or WORKING-STORAGE PIC clauses consist of: X Any character (Alpha, numeric, or special) 9 Only numeric data - digits (0 9) V Part of numeric definition. Assumed decimal point S Part of numeric definition. Sign – allows for negative numbers COBOL FILLER is a reserved word meaning – "set aside this (PIC clause) many bytes of storage in the Structure Variable It is used often in output records to align report columns In older COBOL versions FILLER was required to set aside record storage. In new COBOL you can actually leave the reserved word FILLER out. 01 WS-EMP-RECORD. PIC XXX. 05 ER-LAST-NAME PIC X(20). 05 ER-FIRST-NAME PIC X(20). 05 ER-SOC-SEC-NUM PIC 9(9). 05 ER-PAY-RATE PIC S999V99. 05 ER-HOURS-WORKED PIC 999. PIC X(28). 01 WS-EMP-RECORD. 05 FILLER PIC XXX. 05 ER-LAST-NAME PIC X(20). 05 ER-FIRST-NAME PIC X(20). 05 ER-SOC-SEC-NUM PIC 9(9). 05 ER-PAY-RATE PIC S999V99. 05 ER-HOURS-WORKED PIC 999. 05 FILLER PIC X(28). What's with FILLER? See Slide Notes

28 COBOL Records – Level Numbers and Hierarchically Structured Group Variables
01 ADDRESS-REC. 05 STREET PIC X(40). 05 ADDRESS-2. 10 CITY PIC X(17). 10 STATE-CODE PIC XX. 10 POSTAL-CODE1 PIC 9(5). 10 FILLER PIC X VALUE "-". 10 POSTAL-CODE2 PIC 9(4). You may want to sub-divide data into groups of fields that show relationships, or that organize variables in a hierarchical structure known as a COBOL “record”. Records are COBOL variables that begin with a “level-number” in the range of (which denotes the record as a whole)  49. COBOL records consist of: Group fields: Which do NOT have a picture clause Typically contain elementary fields (lower level fields that sub-divide a group variable) And have a lower level number (representing higher “parentage” level” in the structure) than their children (elementary) fields Elementary fields: Which must have a picture clause And have a higher level number (representing lower or dependent level in the structure) than their group field “parent” variables You can manipulate both group and elementary fields in COBOL COBOL Group Structure variable Elementary field Another group variable Elementary character field Elementary numeric field Value clause – initializes variable Level Numbers Note: FILLER is optional, if you are compiling with the COBOL 85 standard 01 INPUT-REC. 03 INP-KEY PIC 9(4) COMP. 03 LASTNAME PIC X(25). 03 FIRSTNAME PIC X(25). 03 REC-TYPE PIC X(5). 03 EMP-CLASS PIC X(1). 03 EMP-SSN PIC X(11). PIC X(5). 03 ACTY-DATE PIC 9(5). PIC X(40). From the above, you can see that, with COBOL 85 code, you simply leave out the keyword FILLER – which will displace the variables in the record n number of bytes

29 LINKAGE SECTION – Declaring Variables Passed as Parameters by Other Programs
DATA DIVISION. FILE SECTION. WORKING-STORAGE SECTION. LINKAGE SECTION. 01 StructureVariableName. 05 BinaryIntVariable PIC 9(4) COMP. 05 FixedStringVariable PIC X(40). The LINKAGE SECTION is where you define variables that are used to receive parameters passed by other programs in your application All of the variables in the LINKAGE SECTION are global in scope LINKAGE SECTION variables adhere to the same COBOL variable coding rules as data in the FILE SECTION and WORKING-STORAGE SECTION: COBOL variable naming rules Picture clause definitions Group/Structure record declaration rules LINKAGE SECTION variables obtain their values through data passed as parameters in “calling” COBOL programs This will be described in greater detail later in the course

30 Wow… This Seems Like a Lot to Remember!
Memorizing all these rules seems like a steep ladder to climb… Have no fear… the compiler and Workbench tools will remind you!

31 COBOL General Language Rules
Unit COBOL General Language Rules Topics: Coding COBOL Identifying Your Program Describing Your Computing Environment Describing the Data Processing the Data Java and .NET Equivalents

32 Topic objectives After completing this topic, you should be able to:
Describe the purpose of the PROCEDURE DIVISION List the required elements of it Code a syntactically correct PROCEDURE DIVISION statement List a few optional paragraphs and sections of the PROCEDURE DIVISION

33 Processing Your Data – the PROCEDURE DIVISION
IDENTIFICATION DIVISION. ENVIRONMENT DIVISION. DATA DIVISION. PROCEDURE DIVISION. In the PROCEDURE DIVISION of a program, you code the executable statements (business logic) that process data. The division header for a program can be: PROCEDURE DIVISION USING VAR1, VAR2… PROCEDURE DIVISION RETURNING VAR1, VAR2… -- Note that VAR1, VAR2, etc. are variables defined in a program’s LINKAGE SECTION Accepting parameter values into VAR1, VAR2 Returning parameter values to a program that called this program

34 How Logic is Divided in the PROCEDURE DIVISION
Section Logical subdivision of your processing logic. A section has a procedure name – declared in the “A” area, and is optionally followed by one or more paragraphs. A section can be the subject of a PERFORM statement. A section can have zero-to-many paragraphs Paragraph Subdivision of a section, procedure, or program. A paragraph has a procedure name – declared in the “A” area, followed by a period and zero or more sentences. A paragraph can be the subject of a PERFORM or THRU statement. Sentence Series of one or more COBOL statements – coded in the “B” area, that ends with a period. Statement Performs a defined step of COBOL processing, such as adding two numbers. A statement is a valid combination of words, and begins with a COBOL verb. Statements are Imperative (indicating unconditional action) Conditional Compiler-directing Statements are terminated by a period Some statements can be terminated by an explicit Scope Terminator (see screen capture) Using explicit scope terminators instead of periods to show the logical end of a statement is a “Best Practice” Imperative Statements S E N T C S E C T I O N Conditional Statement P A R H Scope Terminator The PROCEDURE DIVISION of a COBOL program is divided into sections and paragraphs, which contain sentences, statements, and phrases. Section and Paragraph procedure names follow the same COBOL naming rules as variables

35 PROCEDURE DIVISION – Imperative Statements
An imperative statement - such as ADD MOVE INSPECT COMPUTE DISPLAY ACCEPT GOBACK READ WRITE CLOSE …indicates an unconditional action to be taken. End an imperative statement with a period Or if allowed (READ, WRITE, COMPUTE), end with a scope-terminator Examples of Imperative Statements More examples can be found in:

36 PROCEDURE DIVISION – Conditional Statements
A conditional statement is either a simple conditional statement IF EVALUATE SEARCH or a conditional statement made up of an imperative statement that includes a conditional phrase or option PERFORM … UNTIL READ … AT END You can end a conditional statement with an implicit or explicit scope terminator.

37 PROCEDURE DIVISION – Imperative Statements – ACCEPT – 1 of 2
WORKING-STORAGE SECTION. 77 INPUT-DATA PIC X(40). PROCEDURE DIVISION. ACCEPT INPUT-DATA. Accept waits for user data entry from your keyboard (and waits for you to press  Enter. The alpha-numeric value you enter is assigned to the variable following ACCEPT. It is not necessary to make the accepted input variable of type PIC X – but is probably a best practice, to avoid user-entry and data-type errors On the Mainframe, ACCEPT retrieves its value from a reserved JCL “DD card” named: SYSIN. We will discuss this in more depth later in the course

38 PROCEDURE DIVISION – Imperative Statements – ACCEPT – 2 of 2
ACCEPT is often used to retrieve certain useful operating system "special-register" values: Current Date – formatted with a number of different date masks: Date DAY-OF-WEEK (a value 1  7, representing Monday  Sunday) Day – the ordinal day of the year (1  365) Time – formatted from the operating system's time: hhmmssss  Date/Time Structure Variables  ACCEPT statements, that return the current date and time in different formats

39 PROCEDURE DIVISION – Imperative Statements – DISPLAY
Something on the console. WORKING-STORAGE SECTION. PROCEDURE DIVISION. DISPLAY "Something on the console". Display presents a literal or the contents of a PIC X(nn) field in the console: On the mainframe DISPLAY writes to a reserved JCL DD statement named: //SYSOUT On your PC a DOS window is opened, and the data is displayed inside it Also – a new line is opened and your cursor moves to the new line (which works, in case you want to ACCEPT data into the program) You can DISPLAY: A literal A PIC X field A PIC 9 field A record Multiple fields and/or literals, separated by commas Code DISPLAY in the "B" area of your program In mainframe batch systems, because DISPLAY also writes to the operator's console (and to //SYSOUT) it is sometimes used to highlight end-of-program messages, such as: Reason for job failure – known as a ABEND condition Record counts and file balancing statistics Etc. See Slide Notes

40 PROCEDURE DIVISION – 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-variable’s storage contents. Alpha-numeric values are copied from left-to-right, byte-for-byte If the receiving field is longer than the sending field blanks (spaces) pad the receiving field to the end of its PIC X length If the receiving field is shorter than the sending field truncation occurs We will study MOVE variations, and COBOL internal storage contents in subsequent chapters

41 PROCEDURE DIVISION – Sequential File Input/Output Routines
FILE SECTION FD EXTFILE … OUT-REC PIC X(80). WORKING-STORAGE SECTION. PROCEDURE DIVISION. OPEN <input/output> EXTFILE. WRITE OUT-REC. CLOSE EXTFILE. COBOL file I/O consists three steps (done roughly in this order): OPEN the file you wish to read from or write to – for INPUT or OUTPUT (see example next slide) Begin an iterative processing loop. Somewhere in the loop: READ the input file - until “end-of-file” …and/or… WRITE the record in the COBOL FILE SECTION FD – for all records that should be written out CLOSE the file In subsequent chapters we will cover COBOL loop statements Steps/Order: 1. OPEN <input/output> <FILENAME>. 2. WRITE <OUTPUT-RECORD>. 3. CLOSE <FILENAME>. L O P Sequential files (sometimes called "flat file") are simple data structures. With records that are read consecutively – or written consecutively one after the next We will devote additional chapters to sequential file processing, index files and handling databases  See Slide Notes, for additional learning content

42 PROCEDURE DIVISION – Imperative Statements – OPEN
External Device External File ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. SELECT INTFILENAME ASSIGN TO … DATA DIVISION. FILE SECTION FD INTFILENAME… 01 OUT-REC. PROCEDURE DIVISION. OPEN OUTPUT INTFILENAME. WRITE OUT-REC. CLOSE INTFILENAME. Syntax: OPEN OUTPUT INPUT EXTEND <InternalFileName>. OPEN connects your program to the external device assigned in your ENVIRONMENT DIVISION. Your program must issue an OPEN statement, before you can READ to or WRITE from the file OPEN INPUT – for files you READ from OPEN OUTPUT – for files you WRITE to from scratch (over-writing the contents of any existing records in the file) OPEN EXTEND – for files you WRITE to and append new records starting at the end of the file CLOSE all OPEN files before ending your program You can OPEN multiple files in one statement (see Slide Notes) COBOL (internal) File Name Opening multiple files with one statement: Open INPUT File1, File2, File3 Output File4, File5. You can also OPEN a FILE Additional notes: The file must exist or else OPEN INPUT or OPEN EXTEND will fail (ABEND) When a file is initially opened for INPUT, the first record in the file is available to be READ When the file is opened for EXTEND, the first WRITE will add records past the current end-of-file When a file is opened for OUTPUT, On PCs the file is created if it does not exist And is overwritten, if it exists On mainframes the file is created according the JCL for the job that runs the program  See Slide Notes, for additional learning content

43 PROCEDURE DIVISION – Imperative Statements – WRITE
External Device External File ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. SELECT INTFILENAME ASSIGN TO … DATA DIVISION. FILE SECTION FD INTFILENAME… 01 OUT-REC. PROCEDURE DIVISION. OPEN OUTPUT INTFILENAME. WRITE OUT-REC. CLOSE INTFILENAME. Syntax: WRITE <OUTPUT-RECORD>. WRITE adds one record to the end of an OPEN OUTPUT file. You write: The record in the FD for the file in the FILE SECTION The record in the FD for the file in the FILE SECTION FROM a record in the WORKING-STORAGE SECTION WRITE-ing data to a file means moving the data in the record buffer (declared in the FD entry) and WRITE-ing the record's contents to the file physical file connected by the INPUT-OUTPUT SECTION's Select/Assign clause. Put another way, WRITE copies (externalizes – or "persists") data from the FILE SECTION's FD (sometimes called a "record buffer") to the external and physical file-spec: On PCs: Hard-drive Network-drive Write-able CDs Printer On Mainframes: Disk storage Tape storage Not shown here, WRITE <OUT-REC> FROM <WORKING-STORAGE-REC> is a best practice, because, in the event of a program I/O error it is easier to debug problem data in WORKING-STORAGE than in the FD – which is actually a z/OS buffer  See Slide Notes, for additional learning content

44 PROCEDURE DIVISION – Imperative Statements – CLOSE
External Device External File ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. SELECT INTFILENAME ASSIGN TO … DATA DIVISION. FILE SECTION FD INTFILENAME… 01 OUT-REC. PROCEDURE DIVISION. OPEN OUTPUT INTFILENAME. WRITE OUT-REC. CLOSE INTFILENAME. Syntax: CLOSE <InternalFileName>. Issue a CLOSE statement for every file you are using before your program ends. CLOSE: Closes an external file And makes it unavailable for processing Unless/until a subsequent OPEN statement occurs You can close multiple files in a single statement F I L E C O S Closing multiple files with one statement: CLOSE File1, File2, File3, File4, File5. Be sure (in your COBOL logic) that, before your program ends (STOP RUN, or GOBACK) it closes all OPEN files it has opened. If you don't: On the PC some data not be written to output files Or the O.S. may lock the file (making it inaccessible to users) On mainframes: Some data may not be written The job the runs your program may fail (ABEND)  See Slide Notes, for additional learning content

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

46 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

47 COBOL General Language Rules
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 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

49 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 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:  F0 F0 F3 F2 F1 F1 C9 D - is negative number PIC S9(5)V99 - value:  F0 F0 F3 F2 F1 F1 D9 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 Stored as: 0123 PIC S9(4) COMP Value 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 PIC S9(5)V99 COMP-3 Value Stored as: C PIC S9(5)V99 COMP-3 Value Stored as: D EBCDIC Internal Data Representation Notes: Even though PIC S9(4) COMP – in binary – can contain up to 32,767 (value) – for all practical purposes the maximum value you can move to it is 9,999 (and -9,999, if Signed). This same concept is true for S9 packed data – where an extra slack byte is inserted by the compiler for even-numbered PIC clauses (i.e. PIC S9(4), PIC S9(2), etc.) The maximum value is the number of digits defined in the picture clause PIC A is seldom used in practice For Binary (COMP) data – this might help understand how to code the PIC clauses: PIC S9(01) COMP -> PIC S9(04) COMP :Takes 2 bytes. PIC S9(05) COMP -> PIC S9(09) COMP :Takes 4 bytes. PIC S9(10) COMP -> PIC S9(18) COMP :Takes 8 bytes. COBOL also allows for Floating Point Numeric types – with: COMP1 … 4 byte Floating Point variable COMP2 … 8 byte Floating Point variable To calculate the size of a comp-3 field: Count the number of digits in the PIC clause Add 1 – for the sign of the field (even if there is no S in the PIC clause) If the result of the above is an odd # - add 1 (to make it an even #) Divide the result in step 3 by 2 Example: PIC 9(6)V99 COMP-3. 8 bytes +1 = 9 It's an odd # - add +1 – now it's 10 Divide by 2 Total? 5 Important – See Slide Notes

50 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 green-screen 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. Z Suppress leading zeroes – insert floating blanks PIC ZZ,ZZZ,Z99.99 B Alphanumeric "mask" – Positionally insert a blank into alphanumeric data PIC XBXBXB Numeric "mask" - Positionally insert a zero into a numeric field. PIC / 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.99- CR 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 The ILE reference manual has an excellent sample guide to Picture Clause editing

51 ILE Reference Manual – Picture Clause Editing Examples – 1 of 2
The ILE reference manual has an excellent sample guide to Picture Clause editing

52 ILE Reference Manual – Picture Clause Editing Examples – 2 of 2
The ILE reference manual has an excellent sample guide to Picture Clause editing

53 COBOL Storage Representation – Reference Chart
Picture Clause Meaning Value Internal Value Internal Storage (EBCDIC bytes) PIC X(10) Fixed alpha-numeric data 'ABC' ABCbbbbbbb (seven trailing blanks) CCC PIC 9(5) Display numeric (Zoned Decimal) numbers -321 Note - without S (sign) value get "absolute value" FFFFF 00321 PIC S9(5) Zoned decimal - with sign Value is negative in math operations FFFFD PIC S9(5)V99 Zoned decimal with implied decimal place 321.5 00321V50 FFFFFFC PIC S9(4) COMP Small binary number - 2 byte - note, negative binary #s stored as two's complement 321 0321 04 11 PIC S9(5) ==> S9(9) COMP Binary number - 4 bytes 0004 0011 PIC S9(9) ==> S9(18) COMP Large Binary number PIC 9(4) COMP-3 Packed decimal number 031 02F PIC S9(5)V99 COMP-3 321.99 0319 029C – Value is negative in math operations 029D External PIC clauses Value Output/Display Value Notes PIC Z(3) Zero-suppressed -2.99 2 No decimal places, no sign PIC ZZ,ZZZ,ZZZ.99- Zero-suppressed, with commas and minus sign Sign on right (can be on left). Zeroes suppressed PIC $$,$$$,$99.99 Dollar-sign suppressed $321.99 One resulting $, if need sign, must use dash (-) PIC XBXBXB Blank insertion ABC AbBbCb Positional blank (b) inserted PIC Zero insertion 030210 High-order inserted, numbers 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.99CR If number was positive, CR would not appear PIC ****9999 Asterisk suppressed **321 Like Z and $ - asterisk suppresses leading zeros PIC Z,ZZZ,Z99.99DB Zero-suppressed, with commas and Debit sign If number was negative, DB would appear

54 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 PIC A is seldom used in practice For Binary (COMP) data – this might help understand how to code the PIC clauses: PIC S9(01) COMP -> PIC S9(04) COMP :Takes 2 bytes. PIC S9(05) COMP -> PIC S9(09) COMP :Takes 4 bytes. PIC S9(10) COMP -> PIC S9(18) COMP :Takes 8 bytes. COBOL also allows for Floating Point Numeric types – with: COMP1 … 4 byte Floating Point variable COMP2 … 8 byte Floating Point variable To calculate the size of a comp-3 field: Count the number of digits in the PIC clause Add 1 – for the sign of the field (even if there is no S in the PIC clause) If the result of the above is an odd # - add 1 (to make it an even #) Divide the result in step 3 by 2 Example: PIC 9(6)V99 COMP-3. 8 bytes +1 = 9 It's an odd # - add +1 – now it's 10 Divide by 2 Total? 5 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

55 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-variable’s 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

56 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 PIC X(4) VALUE 'ABCD'. FLD2 PIC X(10) JUSTIFY RIGHT. MOVE 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

57 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…)

58 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 I believe the sending field (TEST6) is just 6 plain alphanumeric characters. (in C term, that would be char TEST6[6];, ignoring the string termination). When you use MOVE from TEST6 to TEST7. MOVE just assume the characters in TEST6 is numeric only, which, in both case of ASCII and EBCDIC, the lower order 4 bits of the binary representation is same as if the number value. (e.g. "1" is (binary) in ASCII, and (binary) in EBCDIC). So, MOVE simply take the lower 4 bits of each character from TEST6, and pack them into packed decimal. Now, when the data in TEST6's lower-ordered 4 bits contains something that's bigger then 0101 (in binary), then it's NOT a legit packed decimal representation. But the MOVE itself doesn't check for that, so only when we try to do printing or calculation on the TEST7 field would we run into problem. So let's try 2 examples: TEST6 in characters "123456" in memory: (ASCII in hex) When we MOVE to TEST7, we get (in hex) (this over-simplify it, as I ignored the sign-bit) TEST6 in characters "JABCDE" in memory: 4a (ASCII in hex) When we MOVE to TEST7, we get A (in hex) Notice in the first case, is legal packed decimal, so a display of that is ok. In the 2nd case, A is NOT a legal packed decimal digit, so an error would come up. In your code, TEST6 is "A BCDE", a space's hex code is 20 (in ASCII), so the lower order bits are 0, in the overall number in TEST7 would be " " (so why's the 1 not showing up in your debug display? It may have to do with the location of the sign bit. The packed decimal on z/OS has the sign bit at the end of the number, I am not 100% sure about that in AIX/Windows.) The net is, your can't really move non-numerical character string into a COMP-3 (packed decimal) field. The compiler won't stop you, the COBOL standard doesn't say anything about it being illegal, but the behaviour is undefined, and is obviously platform dependent. (it depends on the ASCII/EBCDIC encoding, during my investigation, on z/OS, because it use EBCDIC, moving a "J" into COMP3 is ok, that's due to the lower 4 bits of J's encoding is < 0xA. Sending Fields Receiving Fields PIC X PIC 9 Numeric Edited Y N Treated as an alphanumeric MOVE (digits may be lost, trailing blanks may be added, etc.)

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

60 Alphanumeric MOVE Statements - Examples
Sending Field Receiving Field Sending Field Value Result in Receiving Field PIC X(5) ABCDE PIC X(3) ABC PIC X(8) ABCDEbbb PIC 9(5) 12345 12345bbb Not allowed by the compiler N/A PIC S9(5)V99 COMP-3 Not allowed by the compiler – as is non-integer numeric (see table of moves) (hex) 246C0000 PIC S9(4) COMP PIC X(4) 1234 1344 2400 PIC X(10) JUSTIFY RIGHT. ABCD bbbbbbABCD Numeric Value PIC 9(5)V99 PIC 9(3)V9 345.67 PIC S9(7)V99 PIC 9(4) COMP 6789 PIC S9(5)V99 PIC S9(7)V999 COMP-3 (minus carried in sign bit) PIC S9(9) COMP PIC 9 5 Group Moves CUSTOMER-NAME PIC X(18) SMITHbbbbbAALEXAND CUSTOMER-RECORD PIC X(40) 1201SMITHbbbbbAALEXANDERbbbbbbbbbbbbbbbbbbbbbb 01 CUSTOMER-RECORD. 05 ID-NUMBER PIC 9(2) VALUE 12. 05 CUST-TYPE PIC 9(2) VALUE 01. 05 CUSTOMER-NAME. 10 FIRST-NAME PIC X(10) VALUE 'SMITH'. 10 MIDINIT PIC X(01) VALUE 'A'. 10 LAST-NAME PIC X(10) VALUE 'ALEXANDER'.

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

62 See Notes 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 CUSTTYP PIC 9(2). 10 FIRSTNAME 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 Field's data not moved Field's data not moved MOVE CORRESPONDING does not move values in FILLER fields It has a few important pluses and minuses: Pluses – besides the obvious time-saving nature? Good for common recasting MOVES – example: MOVE ccyymmdd-date to mm/dd/ccyy – formatted date Minuses: When storage structures change (which they inevitably seem to do) MOVE CORRESPONDING code will require additional maintenance – and possibly allow for bugs to creep in (if you forget what you've done with it) See Notes

63 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. Note 1. INITIALIZE … REPLACING Format INITIALIZE ----identifier-1 REPLACING----+-ALPHABETIC, ALPHANUMERIC, ALPHANUMERIC-EDITED, NATIONAL, NATIONAL-EDITED, NUMERIC, NUMERIC-EDITED, DBCS, EGCS BY '…value…' Note 2. It is inefficient to initialize an entire group unless you really need all the items in the group to be initialized.

64 COBOL Figurative Constants
FILE SECTION. 01 CUSTOMER-RECORD-IN. 77 COBOL-CHAR-FIELD PIC X(4). 77 COBOL-NUM-FIELD PIC X(4). 77 COBOL-QT PIC X(1) VALUE QUOTE. PROCEDURE DIVISION. MOVE LOW-VALUES to CUSTOMER-RECORD-IN. MOVE HIGH-VALUES to COBOL-CHAR-FIELD. MOVE SPACES to COBOL-CHAR-FIELD. MOVE ZEROS to COBOL-NUM-FIELD. MOVE ALL '_' TO 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>.

65 COBOL General Language Rules
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

66 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: RANDOM RANGE REM REVERSE SIN SQRT STANDARD-DEVIATION SUM TAN VARIANCE LOG10 MAX MEAN MEDIAN MIDRANGE MIN MOD PRESENT-VALUE RANDOM ACOS ANNUITY ASIN ATAN CHAR COS FACTORIAL LOG

67 Fixed-Point Arithmetic Statements*** – ADD
WORKING-STORAGE SECTION. 01 WORK-FIELDS. 05 ITEM-1 PIC S9(3)V99 VALUE 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 DISPLAY '** ON SIZE ERROR **' Format 1 Adds the addend to the sum 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 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. Additional note: You can substitute a numeric literal for the variables in the ADD and TO (but not GIVING) clauses in the statement Fixed-Point Arithmetic: COBOL supports both fixed and floating point arithmetic. This section covers fixed-point arithmetic – which is precise and flexible enough to handle most business financial data operations However, you may wish to use floating point arithmetic – in which case you will need to read sections of the IBM Language Reference and Programmer's Guide on that topic Additionally you will want to study the following topics extremely carefully – as business math is at the heart of many commercial COBOL applications: Internal numeric datatypes and representation ROUNDING Intermediate Results 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. ***See Notes

68 Arithmetic Statements – ROUNDED and ON SIZE ERROR
WORKING-STORAGE SECTION. 01 WORK-FIELDS. 05 ITEM-1 PIC S9(5)V99 VALUE 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 TO ITEM-1. MOVE 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:  Value:

69 Arithmetic Statements – SUBTRACT
WORKING-STORAGE SECTION. 01 WORK-FIELDS. 05 ITEM PIC S9(3)V99 VALUE 05 ITEM 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 DISPLAY '** ON SIZE ERROR **' 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 Rounded Rounds to the decimal digits in the PIC clause ON SIZE ERROR Allows you to handle arithmetic overflow conditions with imperative statements. Additional note: You can substitute a numeric literal for the variables in the SUBTRACT and FROM (but not GIVING) clauses in the statement

70 Arithmetic Statements – MULTIPLY
WORKING-STORAGE SECTION. 01 INPUT-FIELDS. 05 ITEM-1 PIC S9(3)V99 VALUE 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 DISPLAY '** ON SIZE ERROR **' 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

71 Arithmetic Statements – DIVIDE – Common Usage and Formats
WORKING-STORAGE SECTION. 01 INPUT-FIELDS. 05 ITEM-1 PIC S9(3)V99 VALUE 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 DISPLAY '** ON SIZE ERROR **' DIVIDE ITEM-1 BY ITEM-3 ROUNDED REMAINDER ITEM-3 Five separate Formats for DIVIDE (see Slide Notes) Rounded Rounds to the decimal digits in the PIC clause ON SIZE ERROR Allows you to handle arithmetic overflow conditions with imperative statements. Additional note: You can substitute a numeric literal for the variables in the DIVIDE, BY and INTO, (but not GIVING) clauses in the statement Formats: DIVIDE A INTO B DIVIDE A INTO B GIVING C DIVIDE A BY B GIVING C DIVIDE A BY B GIVING C REMAINDER D DIVIDE A INTO B GIVING C REMAINDER D

72 Arithmetic Statements – COMPUTE
WORKING-STORAGE SECTION. 01 INPUT-FIELDS. 05 ITEM-1 PIC S9(3)V99 VALUE 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). 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 Note: Blanks (the white space) between elements of your equation are significant with COMPUTE. For example: Compute celsius rounded = (5/9) * (fahrenheit - 32) will not work ( 5 / 9 ) * (fahrenheit - 32) will work Formats: DIVIDE A INTO B DIVIDE A INTO B GIVING C DIVIDE A BY B GIVING C DIVIDE A BY B GIVING C REMAINDER D DIVIDE A INTO B GIVING C REMAINDER D

73 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). (ITEM-1 * (ITEM-2 + ITEM-3)).

74 Intermediate Results of Fixed Point Math
From the IBM Enterprise COBOL Programmer's Guide - Document Number: SC 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: 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: Instead of: COMPUTE FIELD-1 ROUNDED = 100 * (32.78 / 1000). Include decimal places in your literals: COMPUTE FIELD-1 ROUNDED = * (32.78 / ).

75 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 = ; interest = .05; nbrYears = 10; //Invoke simple interest calculation function calculateSimpleInterest(); end function calculateSimpleInterest() amount = principal * (1 + (nbrYears * interest));

76 COBOL General Language Rules
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

77 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 Note: PERFORM UNTIL, and SEARCH are also technically conditional expressions. But their primary purpose (PERFORM transfers program control and SEARCH is used in COBOL table look-ups) in our mind takes precedence So we've opted to cover these statements in subsequent sections of the course.

78 Conditional Statements – IF Statement Overview
THEN Statement Block ELSE END-IF IF statement has two operational modes: Alphanumeric compare: On variables of type: PIC X PIC A Group 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 '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"

79 IF Statement Examples Simple IF - No ELSE IF/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 IF HOURS-WORKED > 40             IF HOURLY-EMPLOYEE = "Y"                         IF NO-ERRORS-FOUND                                     PERFORM 900-CALCULATE-HOURLY-OT                         END-IF             END-IF IF HOURS-WORKED > 40 AND       HOURLY-EMPLOYEE = "Y" AND       NO-ERRORS-FOUND              PERFORM 900-CALCULATE-HOURLY-OT Simple IF - No ELSE 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

80 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: 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 The CLASS Conditions can only be tested for on Alphanumeric fields (even IF NUMERIC – as data in PIC 9 fields is assumed by the compiler to already be in numeric format, so any test is already "after the fact". See Notes

81 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, PROCEDURE DIVISION. IF ITEM-1 > "10" MOVE "X" TO ITEMB ELSE PERFORM PROC-A END-IF IF ITEM-1 = ITEM-2 ADD 1 TO ITEM-3 MOVE ALL "X" TO OUT-REC MOVE "X" TO ITEM-2 IF ITEM-1 NUMERIC MOVE ITEM-1 TO ITEM-3 END-IF IF VALID-ITEM MOVE ITEM-2 TO ITEM-1 ELSE MOVE FUNCTION UPPER-CASE(ITEM-2) TO ITEM-1 IF ( ITEM-3 IS POSITIVE ) AND ( ITEM-1 NOT > ITEM-2 ) THEN IF ITEM-3 = 22222 THEN DISPLAY "22222-RECORD" ELSE DISPLAY "11111-RECORD" ELSE DISPLAY "BAD RECORD" IF NOT (ITEM-3 < 10 OR ITEM-3 > 500) AND ITEM-1 <= "Z" THEN DISPLAY "Done" Class Condition Condition-Name Condition Complex Nested IF Relation Condition Simple Relation Condition Note that you can spell out in English, conditional expressions such as: >= (GREATER THAN OR EQUAL TO) = (IS EQUAL TO) Etc. This coding idiom goes along with COBOL's English-sentence orientation, and you may well see examples of this, when maintaining older application code. And you might want to maintain the code in the same vocabulary and style. However, it's considered a best practice to use the algebraic symbols, when writing new logic. Complex Nested IF Relation Condition Complex Nested IF Condition Combing OR/AND

82 Implied IF Condition Statements
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 IF NOT (ITEM-3 < 10 OR > 500) AND ITEM-1 <= "Z" THEN DISPLAY "Done" 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 > AND EMPLOYEE-ID < 3000 Can be coded as: IF 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 Examples of implied IF statement conditions

83 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: 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 What if I want to bypass more than the current logic statement block? See Slide Notes 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. 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. To bypass more than the IF logic: In the next topic you will learn about transfer of control. Typically in structured modular design you will PERFORM a COBOL paragraph, THRU that paragraph's EXIT. This allows you to – at any point in a conditional statement code: GO TO Paragraph-Exit – which: Branches out of the code – in a controlled fashion But does not fall-through

84 Conditional Statements – 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 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" WHEN condition TRUE Statement Block WHEN condition TRUE Statement Block WHEN OTHER TRUE Statement Block END-EVALUATE

85 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 IF CARPOOL-SIZE >= 3 and CARPOOL-SIZE <= 6 THEN MOVE "SMALL GRP" TO PRINT-CARPOOL-STATUS MOVE "BIG GRP" TO PRINT-CARPOOL-STATUS 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 EVALUATE MARITAL-CODE WHEN "M" ADD 2 TO PEOPLE-COUNT WHEN "S" WHEN "D" WHEN "W" ADD 1 TO PEOPLE-COUNT END-EVALUATE

86 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 01 F PIC 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 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 Move "Case Other" To Description "True ALSO True" means that both conditions in the WHEN clause must be true to take the WHEN path

87 COBOL General Language Rules
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

88 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

89 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

90 PERFORM – External Paragraph or Section
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. 400-PROCESS-RECORD. 500-CLEANUP. PERFORM 900-CLOSE-FILES. 700-WRITE-RTN. 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 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

91 PERFORM THRU See Slide Notes
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. 200-OPEN-FILES. 200-EXIT. 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 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)  Two of the reasons to use PERFORM … THRU in production-quality COBOL programs are for: 1. program maintain-ability, 2. Program "hot-fixes" (solving a production ABEND by modifying the code quickly and getting the program back online, or in the batch job queue to finish its cycle within the batch window). Why can PERFORM THRU be better than PERFORM, in the context of maintenance and production support? Production business logic can get complicated. Very complicated. No – very, very, very complicated Sometimes you need to make a change to a COBOL paragraph – say to add some new use case – without affecting existing use cases and the run-time behavior (e.g. "flow of control" for the program. This can be problematic – especially not affecting the "flow of control" – as production COBOL PROCEDURE DIVISIONS can be lengthy and hard to wrap your head around. So – often the choice you'll have to make when designing an algorithm that fixes the problem without introducing another problem is between: Coding a nested IF (and this can get really hairy) Using PERFORM THRU – which allows you to: Code your new use case GO TO the PERFORM'd through paragraph exit More about this in the unit in this course on structured COBOL programming and logic patterns and design Finally – a COBOL EXIT paragraph can have only the reserved word EXIT in it. See Slide Notes

92 Inline PERFORM 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-PERFORM. PERFORM VARYING IDX FROM 1 BY 1 UNTIL IDX > 100 MOVE REC-IN TO REC-TABLE(IDX) 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> END-PERFORM. An in-line PERFORM must be delimited by the END-PERFORM phrase.

93 Scope Terminators and Paragraph Names
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. 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. This will not compile! 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.

94 GO TO – Unconditional Transfer of Control
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 GO TO 100-EXIT ELSE ADD +1 TO REC-KTR MOVE ZEROS TO AMOUNT-TOT END-IF Perform 300-INIT-FIELDS. 100-EXIT. EXIT. 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" 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)  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"

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

96 COBOL General Language Rules
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

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

98 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

99 PERFORM <paragraphName> n TIMES
WORKKING-STORAGE SECTION. 77 NBR-REPS S9(4) COMP. PROCEDURE DIVISION. PERFORM 300-MAINLINE-RTN THRU 300-EXIT 12 TIMES. GOBACK. 300-MAINLINE-RTN. MOVE IN-REC-KTR TO NBR-REPS. PERFORM 310-SUBTOTALS THRU 310-EXIT NBR-REPS TIMES. 300-EXIT. EXIT. PERFORM <paragraphName> n TIMES 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-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.

100 PERFORM UNTIL <condition>
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. 800-READ-RTN. READ IN-FILE INTO WS-RECORD AT END MOVE 'Y' TO SW-NO-MORE-RECORDS. 800-EXIT. PERFORM UNTIL <condition> Structured method of looping when you only know at run-time how many times the loop should be iterated over 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)

101 PERFORM UNTIL – With TEST BEFORE or AFTER
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. 800-READ-RTN. READ IN-FILE INTO WS-RECORD 800-EXIT. 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: 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 WITH TEST AFTER The UNTIL condition is tested after each PERFORM execution.  The Paragraphs will be executed 1 or more times

102 COBOL General Language Rules
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

103 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

104 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 While reading files you typically: 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 You must be cognizant of: 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 After reaching end-of-file you will typically: WRITE a final output record, with summary computed values CLOSE all files DISPLAY a successful end-of-job message Output Report Input File Note - more than likely NOT a tape Device  COBOL Program Business Logic Output File Record Buffer Record Buffer

105 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

106  See Slide Notes, for additional learning content
File I/O Review – OPEN ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. SELECT INTFILENAME ASSIGN TO … DATA DIVISION. FILE SECTION FD INTFILENAME… 01 OUT-REC. PROCEDURE DIVISION. OPEN INPUT FILE1, FILE2 OUTPUT FILE3, FILE4. External Device External File Record Buffer Recall the following: SELECT/ASSIGN connects your internal (logical) filename with 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) Note carefully the syntax for OPEN OPEN connects your program to the external device assigned in your ENVIRONMENT DIVISION – and makes the first record in the file available to be read into a Record Buffer (see next slide for more about Record Buffers and file I/O) Your program must issue an OPEN statement, before you can READ to or WRITE from the file OPEN INPUT – for files you will READ from OPEN OUTPUT – for files you will WRITE to You should CLOSE all OPEN files before ending your program You can OPEN multiple files in one statement (see Slide Notes)  See Slide Notes, for additional learning content

107 File I/O Review – READ INTO
External Device External File 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-REC AT END MOVE ‘Y’ to END-OF-FILE-FLAG. F I L E R A D Record Buffer READ transfers one record at a time from an external sequential file to your program’s storage. You READ the FILENAME one record at a time, into the FD for the file in the FILE SECTION An FD is really an I/O buffer used to store the data for only one record in the file (there's more to this at the physical I/O level with "blocks of data" – which you will understand when we cover JCL later). To READ a file sequentially, a program must read records one at a time into the record buffer. The record buffer is the I/O connection between the program and the records in the file. When your READ statements hit an end of file marker (which all sequential files have created by the operating system), the AT END clause is taken and your COBOL statements following AT END are executed. READ INTO copies the record from the FD buffer to a WORKING-STORAGE record. The AT END clause tests true after the last record is read from the external file BEST PRACTICES: READ <INTFILENAME> INTO <WORKING-STORAGE-REC> is a best practice, because, in the event of a program I/O error it is easier to debug problem data in WORKING-STORAGE than in the FD – which is actually a z/OS buffer You can code an optional NOT AT END clause – which will execute until the last read – which causes the AT END to be true. READ INTFILENAME INTO IN-REC AT END MOVE ‘Y’ to END-OF-FILE-FLAG NOT AT END ADD 1 TO WS-INPUT-REC-CTR. 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 * Note that the DATA DIVISION's FILE SECTION is sometimes referred to as an I/O "buffer" - 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  See Slide Notes, for additional learning content

108 File I/O Review – WRITE FROM
External Device External File ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. SELECT OUTFILENAME ASSIGN TO … DATA DIVISION. FILE SECTION FD OUTFILENAME… 01 OUT-REC. WORKING-STORAGE SECTION 01 OUT-REC-WS. PROCEDURE DIVISION. OPEN OUTPUT OUTFILENAME. WRITE OUT-REC FROM OUT-REC-WS. W R I T E O P A N Record Buffer WRITE adds one record to the end of an OPEN OUTPUT file. You write: The record in the FD for the file in the FILE SECTION The record in the FD for the file in the FILE SECTION FROM a record in the WORKING-STORAGE SECTION WRITE <OUT-REC> FROM <WORKING-STORAGE-REC> is a best practice, because, in the event of a program I/O error it is easier to debug problem data in WORKING-STORAGE than in the FD – which is actually a z/OS buffer 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 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  See Slide Notes, for additional learning content

109  See Slide Notes, for additional learning content
File I/O Review – CLOSE External Device External File ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. SELECT INTFILENAME ASSIGN TO … DATA DIVISION. FILE SECTION FD INTFILENAME… 01 OUT-REC. PROCEDURE DIVISION. CLOSE FILE1, FILE2, FILE3, FILE4. F I L E C O S Record Buffer Recall the following: 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 Issue a CLOSE statement for every file you are using before your program ends. CLOSE: Closes an external file And makes it unavailable for processing Unless/until a subsequent OPEN statement occurs You can close multiple files in a single statement (see Slide Notes).  See Slide Notes, for additional learning content

110 Sequential File Processing Pattern – Pseudo-Code
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 End-of-Job-Routine. Final computations Move Data to output Record Write output record Close Files 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 NUMBER OF EMPLOYEE RECORDS READ: 9999 NUMBER OF HOURLY EMPLOYEES: AVERAGE HOURLY RATE: $999.99 NUMBER OF SALARIED EMPLOYEES: AVERAGE SALARIED RATE: $9,999.99 TYPE 1: 999 TYPE 2: 999 TYPE 3: TYPE 4: TYPE 5: 999 TYPE 6: 999 TYPE 7: 999 TYPE 8: TYPE 9: TYPE 10: 999 The above represents the necessary counters required in homework #2. What you need in Working-Storage: Variables for: count of the number of employee records read from the file count of the number of those records which have an ‘H’ in the status total for all of the hourly rates on these records count of the number of those records which have an ‘S’ in the status total for all of the salaried rates on these records counts of the number of those records having the different values in the type field What else: variable to hold the calculated average for those in the hourly category variable to hold the calculated average for those in the salaried category variable to increment for the page number variable to increment for records per page

111 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

112 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 WORKING-STORAGE 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

113 A Complete Example of a Sequential File Processing Program – PROCEDURE DIVISION
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 M O V E Write the current record Read the next record in the file

114 When there are no more records left to process
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

115 Jon Sayles, IBM Software Group, Rational EcoSystems Team
Enterprise COBOL Education Using Rational Developer for System Z COBOL Report Writing Patterns Jon Sayles, IBM Software Group, Rational EcoSystems Team

116 Purpose of This Document
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

117 Course Details Audience Prerequisites
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.

118 COBOL Report Writing Patterns
Unit COBOL Report Writing Patterns Topics: Report Writing Concepts COBOL Print and Report Layouts COBOL Control Break Reports Appendices

119 COBOL Reporting – a Little History
Since its inception (the late 1950's) COBOL has been the dominant language of business application development For the first years (yes, a COBOL application's shelf-life measure in decades what some application languages aspire towards, measured in years) businesses founded on COBOL used the language for: Data capture and storage – using: Sequential files Indexed files Hierarchical databases Networked (CODASYL) and other pointer-based databases (such as Model 204) Relational databases Object databases Reporting applications – both broad and deep, used in every aspect of the business world Online applications Batch (non-reporting) applications – data consolidation, computationally intensive applications, etc Internet application Now in its 6th decade, COBOL applications still do all of the above – but certainly not in the same ratio and proportion they did in the 70's, 80's and 90's In fact, one type of COBOL business application that is only marginally as important as it was in the past is the reporting application – specifically traditional print reports or "green bar" reports (See Slides)

120 Why Learn About COBOL Reporting Applications
Traditional reporting applications consumed a large portion of early COBOL practitioner time and attention The COBOL language even has a REPORT SECTION – in the DATA DIVISION that provides special keyword vocabulary for creating reports Business reports in fact were so critical to commercial shops that throughout the 1970's  1990's dozens of high-quality reporting products emerged on the market to simplify and streamline report development Some by IBM Many, many, many others – by 3rd Party IBM Business Partners *** See Slide Notes The reason for these non-COBOL/3rd Party products was that essentially, Reporting Applications written in any general-purpose 3rd generation computing language: Are time-consuming and labor-intensive to create Can be built from special-purpose tools and using proprietary report-programming languages: Quickly Cost-effectively Often are time-dependent, in that unlike data, which has intrinsic and lasting value to organizations, reports are essential "the original" U.I. of business applications And U.I.s have changed drastically since 1960 – haven't they While the production source-code assets represented by the 3rd Party products have not necessarily maintained their position, you will still most likely find the knowledge of how create COBOL reports useful for the following reasons: You may end up writing a "quick-and-dirty" report against production data (these are sometimes called "one-offs" You will most likely have to maintain and/or support COBOL reporting applications still running in production. *** Notes Some commonly-used Report Writer tools include: Crystal Reports - IBM's Report Writer: (note the above is a very long URL) This product is RELATIVELY commonly available at Enterprise COBOL shops (and there is a PC version of it at: For more information on the (official) IBM position on this, check out: RPG – Report Program Generator – a 4GL from IBM, prevalent on System z and System i CA-Easytrieve - And there are many Java, .NET and EGL front-end technologies for doing reporting applications on web platforms

121 COBOL Reporting Applications – Big Picture
The figure below shows a typical COBOL reporting application, which contains the following elements: A sorted sequential data source – one of the following: On the mainframe a QSAM file – on the PC a "flat file" or sequential file One the mainframe a VSAM or off the mainframe an indexed file – read sequentially A database (IMS-DL/I, CA-IDMS, DB2, or other) read sequentially A program that processes records from the data source: Read file – usually sequentially, until end-of-file Validate/Compute each record, move fields Write report – that there are a few new COBOL WRITE clauses specific to reporting applications A report – or report file, that is laid out according to precise U.I. record descriptions And quite possibly a file of error records, produced by the COBOL program's validation routine We continue by looking at each part of the above Error Report Sorted Sequential File COBOL Program Business Logic Record Buffer Record Buffer

122 Sequential Input Files – For COBOL Reporting Applications
Sequential File – Sorted Sequential File - Unsorted RECORD1…………………………. RECORD5…………………………. RECORD2…………………………. RECORD3…………………………. RECORD6…………………………. RECORD4…………………………. If you've been following along in this course you've already done a bit of work with Sequential Files. Which are simple data structures that store records serially Such that the records are read one after another These records can be sorted or un-sorted. We will cover sorting in an upcoming unit COBOL Reports will just about always require the data to be sorted, and we will discuss various means of doing that in subsequent course sections: COBOL internal sort Operating System (JCL) sort 3rd Party Sort packages The data in the sorted sequential file records will be read into 01 record structures Typically READ <fileName> INTO <ws-RecordName>. The input record layouts correspond to the input data – which you've seen a number of times now 01 records Group fields (levels 05 and higher) Elementary fields, 88 levels, etc.

123 A Simple Report Have a look at this report 
Let's break down the output or report-specific elements 1. 2. 3. 4. Page Heading This line should be at the top of each page Question … how will we know when to do a "Page Break"? Answer: A page break should occur when the total # of lines written exceeds the max-lines-per-page print specification Column Headings These lines (sometimes the faux-underlines are there…sometimes they're not) should be just under the Page Heading Detail Rows We will format one row of output/detail report values for each input record Report Footer This line is displayed at the end of the entire report. It would typically include additional report totals, counters and accumulators – although we have not coded for this in our example

124 Working Storage for the Simple Report
From the code shown here  Match each of the 01s to the output shown (below) One 01 is not shown in the report You will add this in, when you do your work Answer the following questions: Why the VALUE SPACES next to the FILLER fields? Are the report columns lined up? What do you think the input for this report looks like?

125  Input Data and Record Layout for the Simple Report*** See Slide Notes
From the graphic below, note the input fields in the input file (Sorted Sequential File). Map each field to its respective variable in CustomerRec Answer the following questions: How many fields are there (total) – not counting the 10-level break out of the date field? Are any of the fields packed decimal or binary data? Is the data as shown, sorted? What "key" (what input field variable) is it sorted on Ascending or Descending sort? This is a workshop slide. On your workstation (using Notepad), create a new data file on your c:\ drive, named: c:\customerIn.dat Copy and paste in the following text lines – then close and save the file: My Big Fortune 100 Company A My Dad's Insurance Company I My Aunt's Local Bake Shop, LTD A My Sister's HMO I My Little Brother's Insurance A My Son's Music Publishing Biz I My Other Sons Performance Auto A My Dog's Bone and Treat .org I Error Report Sorted Sequential File COBOL Program Business Logic *** Slide Notes

126 Procedure Division for the Simple Report
So – as this example is primarily: Read  Move to output file  Write we can assume the logic is relatively straightforward And? It is. Read the code shown here, and follow the flow of control. Note the following: File OPEN/CLOSE statements Initial report heading and file read statements Logic to perform the main business logic and report production paragraph until no more data. Within that paragraph: Check for page break condition Move statements from the input to the output variables Write detail line: AFTER ADVANCING LINE forces the printer to skip # lines between Read next input record Final Print Headings

127 Workshop – Sequential File Processing – 1 of 7
As you have done several times so far, Create a new, Workstation Local, COBOL project Name it: chapter4 Be sure to select  COBOL Sample Property Group In the chapter4 Project, create a new cobol folder (as shown) Copy the COBOL source code from the Notes section of the slide Create a new file in the chapter4 project, in the cobol folder, named: rpt1.cbl Paste the code in the editor Do a Local Syntax check of the program Right-click and Nominate rpt1 as the Entry Point Rebuild the chapter4 project Expand the BuildOutput folder, right-click and select Debug As > Debug Configurations Setup a new Debug Configuration as shown Debug the program Step to understand the code flow Resume (run) to end of program Look at the output file produced  (probably: c:\customerOut.dat) IDENTIFICATION DIVISION. PROGRAM-ID. rpt1. AUTHOR. IBM. * A simple Report Program with straight-line reporting logic * Read-and-Print-Read-and-Print, but check for Page Breaks ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT customerDetailsReport ASSIGN TO "c:\customerOut.dat" ORGANIZATION IS LINE SEQUENTIAL ACCESS MODE IS SEQUENTIAL FILE STATUS IS IFCODE. SELECT customerFile ASSIGN TO "c:\customerIn.dat" FILE STATUS IS OFCODE. DATA DIVISION. FILE SECTION. FD CustomerFile. 01 CustomerRec. 05 customerId PIC 9(7). 05 customerName PIC X(30). 05 LastActivityDate. 10 yyyy PIC 9(4). 10 MM PIC 9(2). 10 dddd PIC 9(2). 05 TerritoryCode PIC X(4). 05 ActiveInd PIC X. FD CustomerDetailsReport. 01 PrintLine PIC X(80). WORKING-STORAGE SECTION. **** Report Header and Footer Records 01 Page-Heading. 05 FILLER PIC X(12) VALUE SPACES. 05 FILLER PIC X(35) VALUE "IBM Customer Territory Report". 01 Rpt-Detail-Hdg-1. 05 FILLER PIC X(41) VALUE "CustomerId CustomerName". 05 FILLER PIC X(33) VALUE " Territory Active/Inactive". 01 Rpt-Detail-Hdg-2. VALUE "========== ==============================". VALUE " ========= ===============". 01 PageFooter. 05 FILLER PIC X(19) VALUE SPACES. 05 FILLER PIC X(7) VALUE "Page> ". 05 PrintCustPageNbr PIC Z9. 01 ReportFooter. 05 FILLER PIC X(12) VALUE SPACES. 05 End-Literal PIC X(58) VALUE "*** End of Customer Territory Report ***". **** Report Detail line record 01 CustomerDetailLine. 05 Filler PIC X VALUE SPACES. 05 PrintCustCustId PIC X(11). 05 PrintCustCustName PIC X(31). 05 PrintCustTerritory PIC X(15). 05 PrintCustInd PIC X. **** Standard report processing line, page counters, etc. 01 Misc-Ctrs-Flags. 05 LineCount PIC 99 VALUE ZEROS. 88 PageBrkReq VALUE 50 THRU 99. 05 PageNbr PIC 99 VALUE ZEROS. 05 EOF-Flag PIC X. 88 EndOfCustomerFile VALUE Spaces. 05 IFCODE PIC X(2). 88 CODE-READ VALUE SPACES. 88 NO-MORE-DATA VALUE "10". 05 OFCODE PIC X(2). 88 CODE-WRITE VALUE SPACES. PROCEDURE DIVISION. **** Main business logic (driver logic) area OPEN INPUT customerFile OPEN OUTPUT customerDetailsReport **** Do initiail Heading Routine and priming file read PERFORM 200-PrtHdrs READ CustomerFile AT END SET EndOfCustomerFile TO TRUE END-READ **** Do report logic - until no more input records PERFORM 100-PrintReportBody UNTIL EndOfcustomerFile **** Do end-of-job tasks WRITE PrintLine FROM ReportFooter AFTER ADVANCING 3 LINES CLOSE customerFile, customerDetailsReport GOBACK. 100-PrintReportBody. **** Is LineCount > 50? If yes, do Page Break Logic IF PageBrkReq ADD 1 TO PageNbr MOVE PageNbr TO PrintCustPageNbr WRITE PrintLine FROM PageFooter END-IF **** Report body logic MOVE customerId TO PrintCustCustId MOVE customerName TO PrintCustCustName MOVE TerritoryCode TO PrintCustTerritory IF activeInd = "A" MOVE "Active" TO PrintCustInd IN customerDetailLine else MOVE "InActive" TO PrintCustInd IN customerDetailLine WRITE PrintLine FROM customerDetailLine AFTER ADVANCING 1 LINE ADD 1 TO LineCount **** Read next record/prepare for next report-line READ customerFile AT END SET EndOfcustomerFile TO TRUE END-READ. 200-PrtHdrs. **** Print next page - and reset counters WRITE PrintLine FROM Page-Heading AFTER ADVANCING PAGE WRITE PrintLine FROM Rpt-Detail-Hdg-1 AFTER ADVANCING 2 LINES WRITE PrintLine FROM Rpt-Detail-Hdg-2 MOVE 3 TO LineCount.

128 Workshop – Sequential File Processing – 2 of 7 – Maintenance Specs
 Let's throw in some new specs for a "maintenance" workshop. To complete the work required, you will need to: Edit the input records read. Only allow records with: Valid numeric CustomerIDs The year-in (YYYY) between 1990 and the current year You will have to ACCEPT the CURRENT DATE into an 8-byte date format (see code example in upcoming slide for an example of this) All records in error should be written to a new error output file – unformatted Add counters for: # of error records found # of Good error records written Total # of input records read – the sum of this should equal the # of error records + the number of good records*** See Notes Change Page Break to occur after 10 records Fix the bug in the Active/Inactive output value – currently it's only writing I or A, and should write out Inactive or Active See the next slide for an example new report Use the values in the slide notes for new input test records Sometimes known as test cases Please read through all of the Workshop Slides before beginning to code. Note the use of PERFORM … THRU EXIT – which simplifies modifying logic My Big Fortune 100 Company A My Dad's Insurance Company I My Aunt's Local Bake Shop, LTD A My Sister's HMO I My Little Brother's Insurance A My Son's Music Publishing Biz I My Other Sons Performance Auto A My Dog's Bone and Treat .org I My Big Fortune 100 Company A My Dad's Insurance Company I My Bad year (low) A My Bad year (high) I 555555My Bad CustomerID Key A My Son's Music Publishing Biz I My Other Sons Performance Auto A My Dog's Bone and Treat .org I My Big Fortune 100 Company A My Dad's Insurance Company I My Aunt's Local Bake Shop, LTD A My Sister's HMO I My Little Brother's Insurance A My Son's Music Publishing Biz I My Other Sons Performance Auto A My Dog's Bone and Treat .org I

129 Workshop – 3 of 7 – Output Report
Note the following: Page #s at the bottom of each page Statistics 

130 Workshop – 4 of 7 – Environment and Data Division
Note the following: New file Select/Assign and FD for the Error records Redefinition of CustomerID – in order to do a numeric Class test on it

131 Workshop – 5 of 7 – Data Division and Procedure Division
Note the following: New value for PageBrkReq New counters for records read/written, good, bad, indifferent, etc. Current-Date variable and Aceppt statement New file open/close/read/write Added EXIT statements to the paragraph, to simplify maintaining the code

132 Workshop – 6 of 7 Note the following:
Code for adding to the various record counters New routine for handling the error records – inline within the current logic New input edit sample Note the use of the following logic pattern: Find an error Deal with the error Skip to the end of the function

133 Workshop – Sequential File Processing – 7 of 7
 Suggested course of action: Code the ENVIRONMENT, and DATA Division elements Syntax check and Build the Project Code the remaining PROCEDURE DIVISION logic Use Content Assist to help you code references to the fields and records This is why you'll do the data variable coding first  Syntax check Build the Project Debug your program Run your program – and verify your work by reviewing the output files If time permits, add the following new requirements: Additional Working Storage and output variables that count the # of Active and Inactive accounts Add the current date to the top right-hand corner of the page, in ISO format Move the page # to the top-left of each page

134 COBOL Report Writing Patterns
Unit COBOL Report Writing Patterns Topics: Report Writing Concepts COBOL Print and Report Layouts COBOL Control Break Reports Appendices

135 COBOL Report Writing Statements – WRITE AFTER ADVANCING Options
ENVIRONMENT DIVISION. CONFIGURATION SECTION. SOURCE-COMPUTER. IBM OBJECT-COMPUTER. IBM SPECIAL-NAMES. C01 IS TO-TOP-OF-PAGE. 01 HEADER-1. 05 FILLER PIC X(12) Value Spaces. 05 FILLER PIC X(21) VALUE 'ANNUAL INCOME STATEMENT'. 05 FILLER PIC X(03) Value Spaces. 05 DATE-OUT PIC 99/99/99. 05 FILLER PIC X(02) Value Spaces. 01 HEADER-2. 05 FILLER PIC X(08) VALUE 'EMPLOYEE'. 05 FILLER PIC X(19) Value Spaces. 05 FILLER PIC X(17) VALUE 'ANNUAL TAKE HOME'. 01 HEADER-3. 05 FILLER PIC X(02) VALUE SPACES. 05 FILLER PIC X(08) VALUE 'EMP-ID'. 05 FILLER PIC X(24) VALUE SPACES. 05 FILLER PIC X(03) VALUE 'SALARY'. 700-WRITE-REPORT-HEADING-LINES. WRITE EMPL-REPORT-REC FROM HEADER-1 AFTER ADVANCING TO-TOP-OF-PAGE. WRITE EMPL-REPORT-REC FROM HEADER-2 AFTER ADVANCING 2 LINES. WRITE EMPL-REPORT-REC FROM HEADER-3 AFTER ADVANCING 1. WRITE EMPL-REPORT-REC FROM TOTAL-LINE BEFORE ADVANCING 0 LINES. The SPECIAL-NAMES paragraph: Relates IBM-specified environment-names to user-defined mnemonic-names. Relates alphabetic-names to character sets or collating sequences. Relates class names to sets of characters. Specifies a substitute character for the currency sign. In this example C01 is a "special name" that is used with the WRITE I/O verb, to skip to the top of the next page when the output file is attached to a printer that accepts files formatted for printing (i.e. with special characters for advancing to the next physical page, etc.). AFTER ADVANCING n LINES Is a clause of the WRITE statement, that directs the printer to advance the next physical line in the report paper Can specify AFTER or BEFORE LINES is optional Note the use of BEFORE ADVANCING 0 LINES – executed multiple times. This is used to make a header or bold on a report

136 Workshop – Open Ended  One more maintenance assignment. We now have to account for four quarters worth of taxes (this program is run at end-of-year). Replace the existing c:\customerIn.dat data, with the records in the Slide Notes Recode the input file's layout to match the new test case values Create an output report that matches the next slide's screen capture Add in one more statistic kept: Average annual taxes paid (see next slide for snapshot of result) You will have to be cognizant of: Numeric output formatted fields Lining up the columns of the report and the final average value My Big Fortune 100 Company A My Dad's Insurance Company I My Aunt's Local Bake Shop, LTD A My Sister's HMO I My Little Brother's Insurance A My Son's Music Publishing Biz I My Other Sons Performance Auto A My Dog's Bone and Treat .org I My Big Fortune 100 Company A My Dad's Insurance Company I My Bad year (low) A My Bad year (high) I 555555My Bad CustomerID Key A My Son's Music Publishing Biz I My Other Sons Performance Auto A My Dog's Bone and Treat .org I My Big Fortune 100 Company A My Dad's Insurance Company I My Aunt's Local Bake Shop, LTD A My Sister's HMO I My Little Brother's Insurance A re6 My Son's Music Publishing Biz I My Other Sons Performance Auto A My Dog's Bone and Treat .org I

137 Workshop – Open Ended

138 Workshop Coding Solution
There is a coding solution to this simple report programming problem in the slide notes. Considerations: This is only one interpretation of how to do this workshop It is offered here as – Caveat Emptor If you choose to use this, we recommend you rename the program So that if you want to finish your own version of this workshop you won't have to rename files, etc. Optional Add the State values into the output print (Rpt-Detail-Hdg-1 and Rpt-Detail-Hdg-2) lines IDENTIFICATION DIVISION. PROGRAM-ID. rpt1. AUTHOR. IBM. * A simple Report Program with straight-line reporting logic * Read-and-Print-Read-and-Print, but check for Page Breaks ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT customerDetailsReport ASSIGN TO "c:\customerOut.dat" ORGANIZATION IS LINE SEQUENTIAL ACCESS MODE IS SEQUENTIAL FILE STATUS IS IFCODE. SELECT customerFile ASSIGN TO "c:\customerIn.dat" FILE STATUS IS OFCODE. SELECT errorFile ASSIGN TO "c:\customerErr.dat" FILE STATUS IS EFCODE. DATA DIVISION. FILE SECTION. FD CustomerFile. 01 CustomerRec. 05 customerId PIC 9(7). 05 customerID-RDF REDEFINES customerId PIC X(7). 05 customerName PIC X(30). 05 LastActivityDate. 10 yyyy PIC 9(4). 10 MM PIC 9(2). 10 dddd PIC 9(2). 05 TerritoryCode PIC X(4). 05 ActiveInd PIC X. 05 Q1-Tax PIC 9(5)V99. 05 Q2-Tax PIC 9(5)V99. 05 Q3-Tax PIC 9(5)V99. 05 Q4-Tax PIC 9(5)V99. FD CustomerDetailsReport. 01 PrintLine PIC X(133). FD errorFile. 01 ErrorRec PIC X(80). WORKING-STORAGE SECTION. **** Report Header and Footer Records 01 Page-Heading. 05 FILLER PIC X(12) VALUE SPACES. 05 FILLER PIC X(35) VALUE "IBM Customer Territory Report". 01 Rpt-Detail-Hdg-1. 05 FILLER PIC X(41) VALUE "CustomerId CustomerName". 05 FILLER PIC X(27) VALUE " Territory Active/Inactive". 05 FILLER PIC X(33) VALUE "Q1 Taxes Q2 Taxes Q3 Taxes ". 05 FILLER PIC X(26) VALUE "Q4 Taxes Total Taxes". 01 Rpt-Detail-Hdg-2. VALUE "========== ==============================". VALUE " ========= ===============". 05 FILLER PIC X(34) VALUE "========= ========= ========= ". VALUE "========= ============". 01 PageFooter. 05 FILLER PIC X(19) VALUE SPACES. 05 FILLER PIC X(7) VALUE "Page: ". 05 PrintCustPageNbr PIC Z9. 01 ReportFooter. 05 FILLER PIC X(1) VALUE SPACES. 05 End-Literal PIC X(58) VALUE "*** End of Customer Territory Report ***". 01 ReportFinalStats-1. VALUE " Number of Records in:". 05 InRecCount-Final PIC Z(4). 01 ReportFinalStats-2. 05 Filler PIC X(33) VALUE " Number of Error Records:". 05 BadRecCount-Final PIC Z(4). 01 ReportFinalStats-3. VALUE " Number of Good Output Records:". 05 OutGoodRecCount-Final PIC Z(4). 01 ReportFinalStats-4. 05 Filler PIC X(24) VALUE " Average Taxes Paid:". 05 AvgTaxesPaidOut PIC $$,$$$,$$$.99. **** Report Detail line record 01 CustomerDetailLine. 05 Filler PIC X VALUE SPACES. 05 PrintCustCustId PIC X(11). 05 PrintCustCustName PIC X(31). 05 PrintCustTerritory PIC X(10). 05 PrintCustInd PIC X(15). 05 Q1-Tax-Out PIC $$,$$$.99. 05 Filler PIC XX VALUE SPACES. 05 Q2-Tax-Out PIC $$,$$$.99. 05 Q3-Tax-Out PIC $$,$$$.99. 05 Q4-Tax-Out PIC $$,$$$.99. 05 Total-Tax-Out PIC $$,$$$,$$$.99. **** Standard report processing line, page counters, etc. 01 Misc-Ctrs-Flags. 05 LineCount PIC 99 VALUE ZEROS. 88 PageBrkReq VALUE 10 THRU 99. 05 PageNbr PIC 99 VALUE ZEROS. 05 BadRecCount PIC 9(4) comp value zeros. 05 OutGoodRecCount PIC 9(4) comp value zeros. 05 InRecCount PIC 9(4) comp value zeros. 05 BadRecSw PIC X(1) value spaces. 88 BadRecord value "Y". 05 Total-Tax PIC 9(7)V99 comp-3. 05 RPT-Total-Tax PIC 9(9)V99 comp-3 value 0. 05 EOF-Flag PIC X. 88 EndOfCustomerFile VALUE Spaces. 05 IFCODE PIC X(2). 88 CODE-READ VALUE SPACES. 88 NO-MORE-DATA VALUE "10". 05 OFCODE PIC X(2). 88 CODE-WRITE VALUE SPACES. 05 EFCODE PIC X(2). 01 WS-DATE. 05 CURR-YEAR PIC 9(4). 05 CURR-MONTH PIC 9(2). 05 CURR-DAY PIC 9(2). PROCEDURE DIVISION. **** Main business logic (driver logic) area ACCEPT WS-DATE FROM DATE YYYYMMDD. OPEN INPUT customerFile OPEN OUTPUT customerDetailsReport, errorFile **** Do initiail Heading Routine and priming file read PERFORM 200-PrtHdrs READ CustomerFile AT END SET EndOfCustomerFile TO TRUE END-READ **** Do report logic - until no more input records PERFORM 100-PrintReportBody thru 100-EXIT UNTIL EndOfcustomerFile **** Do end-of-job tasks move InRecCount to InRecCount-Final. move BadRecCount to BadRecCount-Final. move OutGoodRecCount to OutGoodRecCount-Final. compute AvgTaxesPaidOut = RPT-Total-Tax / OutGoodRecCount * 1.0. write PrintLine FROM ReportFinalStats-1 AFTER ADVANCING 2 LINES. write PrintLine FROM ReportFinalStats-2. write PrintLine FROM ReportFinalStats-3. write PrintLine FROM ReportFinalStats-4. WRITE PrintLine FROM ReportFooter AFTER ADVANCING 2 LINES CLOSE customerFile, customerDetailsReport, errorFile. GOBACK. 100-PrintReportBody. add +1 to InRecCount. Perform 300-EditInputRec thru 300-EXIT if BadRecord Write ErrorRec from CustomerRec READ customerFile AT END SET EndOfcustomerFile TO TRUE go to 100-EXIT end-if. **** Is LineCount > 10? If yes, do Page Break Logic IF PageBrkReq ADD 1 TO PageNbr MOVE PageNbr TO PrintCustPageNbr WRITE PrintLine FROM PageFooter AFTER ADVANCING 3 LINES END-IF **** Report body logic MOVE customerId TO PrintCustCustId MOVE customerName TO PrintCustCustName MOVE TerritoryCode TO PrintCustTerritory IF activeInd = "A" MOVE "Active" TO PrintCustInd IN customerDetailLine else MOVE "InActive" TO PrintCustInd IN customerDetailLine Move Q1-Tax to Q1-Tax-Out. Move Q2-Tax to Q2-Tax-Out. Move Q3-Tax to Q3-Tax-Out. Move Q4-Tax to Q4-Tax-Out. compute Total-Tax = Q1-TAX + Q2-TAX + Q3-TAX + Q4-TAX. move Total-Tax to Total-Tax-Out. WRITE PrintLine FROM customerDetailLine AFTER ADVANCING 1 LINE ADD 1 TO LineCount add 1 to OutGoodRecCount. add Total-Tax to RPT-Total-Tax. **** Read next record/prepare for next report-line END-READ. 100-EXIT. EXIT. 200-PrtHdrs. **** Print next page - and reset counters WRITE PrintLine FROM Page-Heading AFTER ADVANCING PAGE WRITE PrintLine FROM Rpt-Detail-Hdg-1 WRITE PrintLine FROM Rpt-Detail-Hdg-2 MOVE 3 TO LineCount. 300-EditInputRec. Move "N" to BadRecSw. If customerID-RDF is Not NUMERIC add +1 to BadRecCount move "Y" to BadRecSw go to 300-EXIT. If yyyy < 1990 or > CURR-YEAR 300-EXIT.

139 COBOL Report Writing Patterns
Unit COBOL Report Writing Patterns Topics: Report Writing Concepts COBOL Print and Report Layouts COBOL Control Break Reports Appendices

140 What Are Control Breaks?
A "Control Break" in COBL program vernacular, refers to a change in a control field value – typically in a sequential file, such that, upon successive reads when the value changes? A processing change happens in the program – and you would perform a routine that prints a control-break line containing: Summary values, sub-totals and/or statistics: Lines counted – for all of the records since the last control break Accumulators - numeric values such as: Number of items sold, Total expenses, etc. Statistics – average, min, max salaries, etc. The pre-requirement for Control Break functionality is for the sequential file to be sorted on the values in the control break field Or there would be random control breaks in the output processing Control Break reports are common in COBOL applications. They expose summary values and statistics, and help turn raw data into the information necessary to run a business. Show me the total sales for our retail stores broken out by: State Store Departments Months of the year Individual stores

141 Single-Level Control Break Report – Example Break on U.S. State Values
Note that the "control break" occurs: Each time the State changes And at the end of the report (an implied final control break)

142 What Are Control Breaks?
Do Initial Process Do Process All Records until end-of-file Do End-of-Program Process Initial Process Write headers Process first record Move control break field to a hold-area (for comparison) Process All Records Edit – or Do Edit Routine If good record If Current control-break-value <> hold-control-break-value Do Control Break Process Process Detail Record Read next input record Add to hold fields and accumulators Move fields to output fields Write Detail Record Control Break Process Move hold control break values to output fields Write Control Break Record Zero out control break hold areas Move Current control-break-value to hold-control-break-value End-of-Program Process Do final control break Do final output report processing The pseudo-code for a single-level Control Break report is as follows  Note that this logic could be divided up into COBOL paragraphs sections or simply inline routines – depending on the complexity and scope of each element

143 COBOL Program to do Control Break – DATA DIVISION Areas – 1 of 3
Here's a completed example of a Control Break program. Note the following: Input record with two new fields for control break values (we will use only StateCode for this first part of the unit) The Control Break report line Hold areas for the Control Break interim-values The Control Break "hold keys" – that will be used to as comparison values with each new record read, to determine if there has been a "control break" in the file 2. …more fields… 3. …more fields… 1. 4.

144 COBOL Program to do Control Break – Procedure Division – 2 of 3
5. Driver Logic (from our pseudo-code) Process All Records – which includes PERFORM statements to paragraphs on the next slide Control Break Process – note the detailed logic in the comments 6. 7. Note that this is actually the same program we have been working with all along in this unit, just better structured

145 COBOL Program to do Control Break – Final Paragraphs – 3 of 3
8. COBOL Program to do Control Break – Final Paragraphs – 3 of 3 Process Detail Records – note the additional code to add to the Control Break hold areas Initial Process paragraph – to setup the report, do the priming file read, and initialize the control break values End-of-Program Process – which does the final control break, and writes out the standard end-of-job report summary lines 10. 9. Note also that we've made the Read Routine into a separately performed paragraph. This is a "best practice"

146 Workshop – Control Break Reports – 1 of 4
From the slide notes, copy all of the new data records – that contain the State code, and paste them into c:\customerIn.dat – replacing the existing records View the state values in the file – note that they are sorted from low to high (from California to Hawaii). My Big Fortune 100 Company CA0001A My Dad's Insurance Company CA0011I My Aunt's Local Bake Shop, LTD CA0111A My Sister's HMO CA1111I My Little Brother's Insurance CA0002A My Son's Music Publishing Biz CA0022I My Other Sons Performance Auto CA0222A My Dog's Bone and Treat .org CT2222I My Big Fortune 100 Company CT3333A My Dad's Insurance Company CT4444I My Bad year (low) CT0111A My Bad year (high) CT1111I 555555My Bad CustomerID Key DE0002A My Son's Music Publishing Biz DE0022I My Other Sons Performance Auto DE0222A My Dog's Bone and Treat .org DE2222I My Big Fortune 100 Company FL0001A My Dad's Insurance Company FL0011I My Aunt's Local Bake Shop, LTD FL0111A My Sister's HMO HI1111I My Little Brother's Insurance HI2222A re6 My Son's Music Publishing Biz HI3333I My Other Sons Performance Auto HI4444A My Dog's Bone and Treat .org HI5555I

147 Workshop – Control Break Reports – 2 of 4
From the slide notes, copy the program source (all of the COBOL statements) Create a new file in the chapter4 project, in the cobol folder, named: rpt2.cbl Paste the code in the editor Do a Local Syntax check of the program – ensure no errors Right-click over rpt2, and Nominate as Entry Point Rebuild the chapter4 project Expand the BuildOutput folder, right-click and select Debug As > Debug Configurations Setup a new Debug Configuration as shown Debug the program Step to understand the code flow Resume (run) to end of program Look at the output file produced  (probably: c:\customerOut.dat) Unless you've changed the file Return to z/OS Project Perspective IDENTIFICATION DIVISION. PROGRAM-ID. rpt2. AUTHOR. IBM. * A simple Report Program with straight-line reporting logic * Read-and-Print-Read-and-Print, but check for Page Breaks ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT customerDetailsReport ASSIGN TO "c:\customerOut.dat" ORGANIZATION IS LINE SEQUENTIAL ACCESS MODE IS SEQUENTIAL FILE STATUS IS IFCODE. SELECT customerFile ASSIGN TO "c:\customerIn.dat" FILE STATUS IS OFCODE. SELECT errorFile ASSIGN TO "c:\customerErr.dat" FILE STATUS IS EFCODE. DATA DIVISION. FILE SECTION. FD CustomerFile. 01 CustomerRec. 05 customerId PIC 9(7). 05 customerID-RDF REDEFINES customerId PIC X(7). 05 customerName PIC X(30). 05 LastActivityDate. 10 yyyy PIC 9(4). 10 MM PIC 9(2). 10 dddd PIC 9(2). 05 StateCode PIC X(2). 05 TerritoryCode PIC X(4). 05 ActiveInd PIC X. 05 Q1-Tax PIC 9(5)V99. 05 Q2-Tax PIC 9(5)V99. 05 Q3-Tax PIC 9(5)V99. 05 Q4-Tax PIC 9(5)V99. FD CustomerDetailsReport. 01 PrintLine PIC X(133). FD errorFile. 01 ErrorRec PIC X(80). WORKING-STORAGE SECTION. **** Report Header and Footer Records 01 Page-Heading. 05 FILLER PIC X(12) VALUE SPACES. 05 FILLER PIC X(35) VALUE "IBM Customer Territory Report". 01 Rpt-Detail-Hdg-1. 05 FILLER PIC X(41) VALUE "CustomerId CustomerName". 05 FILLER PIC X(27) VALUE " Territory Active/Inactive". 05 FILLER PIC X(34) VALUE "Q1 Taxes Q2 Taxes Q3 Taxes ". 05 FILLER PIC X(26) VALUE "Q4 Taxes Total Taxes". 01 Rpt-Detail-Hdg-2. VALUE "========== ==============================". VALUE " ========= ===============". 05 FILLER PIC X(33) VALUE "========= ========= ========= ". VALUE "========= ============". 01 PageFooter. 05 FILLER PIC X(19) VALUE SPACES. 05 FILLER PIC X(7) VALUE "Page: ". 05 PrintCustPageNbr PIC Z9. 01 ReportFooter. 05 FILLER PIC X(1) VALUE SPACES. 05 End-Literal PIC X(58) VALUE "*** End of Customer Territory Report ***". 01 ReportFinalStats-1. VALUE " Number of Records in:". 05 InRecCount-Final PIC Z(4). 01 ReportFinalStats-2. 05 Filler PIC X(33) VALUE " Number of Error Records:". 05 BadRecCount-Final PIC Z(4). 01 ReportFinalStats-3. VALUE " Number of Good Output Records:". 05 OutGoodRecCount-Final PIC Z(4). 01 ReportFinalStats-4. 05 Filler PIC X(24) VALUE " Average Taxes Paid:". 05 AvgTaxesPaidOut PIC $$,$$$,$$$.99. 01 ControlBreakStats-1. 05 FILLER PIC X(23) 05 ControlBreakState PIC X(3). 05 ControlBreakCount PIC Z(3). 05 FILLER PIC X(28) VALUE " Amount of taxes paid:". 05 ControlBreakTaxes PIC $,$$$,$$$.99. **** Report Detail line record 01 CustomerDetailLine. 05 Filler PIC X VALUE SPACES. 05 PrintCustCustId PIC X(11). 05 PrintCustCustName PIC X(31). 05 PrintCustTerritory PIC X(10). 05 PrintCustInd PIC X(15). 05 Q1-Tax-Out PIC $$,$$$.99. 05 Filler PIC XX VALUE SPACES. 05 Q2-Tax-Out PIC $$,$$$.99. 05 Q3-Tax-Out PIC $$,$$$.99. 05 Q4-Tax-Out PIC $$,$$$.99. 05 Total-Tax-Out PIC $$,$$$,$$$.99. **** Standard report processing line, page counters, etc. 01 Misc-Ctrs-Flags. 05 LineCount PIC 99 VALUE ZEROS. 88 PageBrkReq VALUE 10 THRU 99. 05 PageNbr PIC 99 VALUE ZEROS. 05 BadRecCount PIC 9(4) comp value zeros. 05 OutGoodRecCount PIC 9(4) comp value zeros. 05 InRecCount PIC 9(4) comp value zeros. 05 HoldContrBreakRecCount PIC 9(4) comp value zeros. 05 HoldContrBreakRecTaxes PIC 9(9)V99 comp-3 value 0. 05 BadRecSw PIC X(1) value spaces. 88 BadRecord value "Y". 05 Total-Tax PIC 9(7)V99 comp-3. 05 RPT-Total-Tax PIC 9(9)V99 comp-3 value 0. 05 EOF-Flag PIC X. 88 EndOfCustomerFile VALUE Spaces. 05 IFCODE PIC X(2). 88 CODE-READ VALUE SPACES. 88 NO-MORE-DATA VALUE "10". 05 OFCODE PIC X(2). 88 CODE-WRITE VALUE SPACES. 05 EFCODE PIC X(2). 01 WS-DATE. 05 CURR-YEAR PIC 9(4). 05 CURR-MONTH PIC 9(2). 05 CURR-DAY PIC 9(2). **** Hold-Keys. 05 HoldState PIC X(2). 05 HoldTerritory PIC X(4). PROCEDURE DIVISION. **** Do initial program logic PERFORM 600-InitRoutine thru 600-Exit. **** Do report logic and control break - until no more records PERFORM 100-PrintReportBody thru 100-EXIT UNTIL EndOfcustomerFile **** Do end-of-job tasks PERFORM 900-End-of-Report THRU 900-EXIT. GOBACK. 100-PrintReportBody. Add +1 to InRecCount. PERFORM 300-EditInputRec THRU 300-EXIT. if BadRecord PERFORM 800-ReadRoutine THRU 800-Exit go to 100-EXIT. If HoldState Not EQUAL TO StateCode PERFORM 400-NewState thru 400-Exit. PERFORM 500-DetailLine THRU 500-Exit. **** Read next record/prepare for next report-line PERFORM 800-ReadRoutine thru 800-Exit. 100-EXIT. EXIT. 200-PrtHdrs. **** Print next page - and reset counters WRITE PrintLine FROM Page-Heading AFTER ADVANCING PAGE WRITE PrintLine FROM Rpt-Detail-Hdg-1 AFTER ADVANCING 2 LINES WRITE PrintLine FROM Rpt-Detail-Hdg-2 MOVE 3 TO LineCount. 300-EditInputRec. Move "N" to BadRecSw. If customerID-RDF is Not NUMERIC add +1 to BadRecCount move "Y" to BadRecSw go to 300-EXIT. If yyyy < 1990 or > CURR-YEAR 300-EXIT. 400-NewState. **** New state - write out control break report line(s) move HoldState to ControlBreakState. move HoldContrBreakRecCount to ControlBreakCount. move HoldContrBreakRecTaxes to ControlBreakTaxes. WRITE PrintLine FROM ControlBreakStats-1 AFTER ADVANCING 2. move SPACES to PrintLine. write PrintLine. **** Add to line counter add +3 to LineCount. **** Zero out accumulators for next control break state Move zero to HoldContrBreakRecCount, HoldContrBreakRecTaxes. **** Initialize the comparison key for the control break values Move StateCode to HoldState. 400-Exit. Exit. 500-DetailLine. **** Report body logic MOVE customerId TO PrintCustCustId MOVE customerName TO PrintCustCustName MOVE TerritoryCode TO PrintCustTerritory IF activeInd = "A" MOVE "Active" TO PrintCustInd IN customerDetailLine else MOVE "InActive" TO PrintCustInd IN customerDetailLine END-IF Move Q1-Tax to Q1-Tax-Out. Move Q2-Tax to Q2-Tax-Out. Move Q3-Tax to Q3-Tax-Out. Move Q4-Tax to Q4-Tax-Out. compute Total-Tax = Q1-TAX + Q2-TAX + Q3-TAX + Q4-TAX. move Total-Tax to Total-Tax-Out. WRITE PrintLine FROM customerDetailLine AFTER ADVANCING 1 LINE. **** Add to all totals and accumulators ADD 1 TO LineCount, OutGoodRecCount, HoldContrBreakRecCount. add Total-Tax to RPT-Total-Tax, HoldContrBreakRecTaxes. 500-Exit. 600-InitRoutine. **** Main business logic (driver logic) area ACCEPT WS-DATE FROM DATE YYYYMMDD. OPEN INPUT customerFile OPEN OUTPUT customerDetailsReport, errorFile **** Do initiail Heading Routine and priming file read PERFORM 200-PrtHdrs **** Setup Initial control break Comparison Logic Move TerritoryCode to HoldTerritory. 600-Exit. 800-ReadRoutine. READ customerFile AT END SET EndOfcustomerFile TO TRUE END-READ. 800-Exit. 900-End-of-Report. **** Do final control break state Perform 400-NewState THRU 400-Exit. move InRecCount to InRecCount-Final. move BadRecCount to BadRecCount-Final. move OutGoodRecCount to OutGoodRecCount-Final. compute AvgTaxesPaidOut = RPT-Total-Tax / OutGoodRecCount * 1.0. write PrintLine FROM ReportFinalStats-1 AFTER ADVANCING 2 LINES. write PrintLine FROM ReportFinalStats-2. write PrintLine FROM ReportFinalStats-3. write PrintLine FROM ReportFinalStats-4. WRITE PrintLine FROM ReportFooter CLOSE customerFile, customerDetailsReport, errorFile. 900-EXIT.

148 Workshop – Control Break Reports – 3 of 4 – Development Specs
 Let's throw in some new specs for a brand new control break program that produces a listing of employee salaries by state. Using the data in the Slide Notes, create: c:\employee.dat. (see screen capture) Note – these are well-paid employees. Probably hedge fund managers. It will line up the with the EMPLOYEE-RECORD layout shown below Using the Control Break pattern from rpt3.cbl – create a program in the chapter4 cobol folder that produces the Control Break report shown on the next slide  There are no edit errors in this file, so you can just concentrate on coding the Control Break logic pattern Mr. Allen Lefkowitz Ridgewood AZ Mr. Elway Bevin Glen Rock AZ Ms. Alison Baier Fairlawn AZ Ms. Kathleen Crumpitz Sacramento AZ Mr. Brad Ellington Rahway CA Mr. Jamison Peter Trenton CA Mr. Christopher Leland Baltimore CA Ms. Maryellen J Adams Wake Forest CA Dr. Robert Kirk San Francisco CA Ms. Sarah Nocturne Chicago CT Ms. Sally Nostradamus Washington Heights CT Mr. Elliot G. Ould Hartford DE Ms. Astrid Gilberto Manchester NM Mr. David Brubeck Old Lyme NM Mr. Allen Lefkowitz Coventry NM Mr. Claude LeJeuene Storrs NM Mr. Heinrich Isaac Knoxville NM Break on EMPLOYEE-STATE value change c:\employee.dat

149 Workshop – Control Break Reports – 4 of 4 – Development Specs
 The employee salary Control Break Report  Optional workshop functionality includes: A report header With the current date And page# And edit routine for: Valid numeric salary A more realistic salary range for employees (who are not hedge fund managers)

150 What About Multi-Level Control Break Reports?
As common as single-level control break functionality in COBOL business applications are multi-level control break reports, that have: Major key Middle key Minor key Or more levels of control break, and that process data in files that is sorted on the same key sequence. Consider this example of a (fictitious) grocery store report Note keys of: State, City, Store# And coincidentally, note that additional data control breaks would be possible (probable?) along the lines of Store Department and SKU At the risk of repeating ourselves, control break processing turns data into information Major Key Middle Key Minor Key

151 Data For a Two-Level Control Break Report
If you're going to break on two control fields, you need to columns of data, both sorted, in a Parent  Child, or Master  Detail sequence: Sort on Parent key values Within the Parent key, sort on Child key values Note the following – in our current customerIn.dat file: Master/Parent Key data: State code Detail/Child Key data: Territory code Find both sets of values in this screen capture  Question: So if we have our data arranged by this two-level control break sequence, what elements in our program do you think we'll have to change? Answer: Output report lines A Parent/Master control break test and processing paragraph A Child/Detail control break test and processing paragraph The various hold areas, counters and accumulators coded for both Parent and Child control breaks This will be clearer if we have a look at the output produced (next slide)

152 A Two-Level Control Break Report
Note the following: Detail/Child control break line Master/Parent control break line  Let's have a look at the actual COBOL code used to produce this.

153 COBOL Code For a Two-Level Control Break – 1 of 2
We're going to reuse the rpt2.cbl program for this example. We will enhance it to add: A Control Break output line for Territory Control Breaks Hold fields for Territory values Note that we will have to rename the generically-named State fields In the PROCEDURE DIVISION we see the key logic modification Test for a Major/Parent key control break … then … Test for a Minor/Child key control break In that order …more fields… …more fields… and begin Procedure Division

154 COBOL Code For a Two-Level Control Break – 2 of 2
We will need a new Minor/Child control break processing paragraph – that will eerily resemble the Major/Parent control break process. With a few exceptions: The Parent control break will perform the child control break Note that this could happen for any # of intermediate levels as well – following the data sort key relationships from highest to lowest sort-key What's important is that the Perform of lower-level control breaks happen BEFORE the upper-level control breaks. The Child control break will print out the Territory line – and re-initialize the counters and accumulators

155 Workshop – A Two-Level Control Break Program
Return to your single-level Control Break program. You will use the new data records for c:\employee.dat  They are in the Slide Notes Enhance the program to produce the report shown on the next slide Mr. Allen Lefkowitz Fairlawn AZ Mr. Elway Bevin Fairlawn AZ Ms. Alison Baier Fairlawn AZ Ms. Kathleen Crumpitz Glen Rock AZ Mr. Brad Ellington Baltimore CA Mr. Jamison Peter Baltimore CA Mr. Christopher Leland Baltimore CA Ms. Maryellen J Adams Wake Forest CA Dr. Robert Kirk Wake Forest CA Ms. Sarah Nocturne Chicago CT Ms. Sally Nostradamus Chicago CT Mr. Elliot G. Ould Hartford DE Ms. Astrid Gilberto Manchester NM Mr. David Brubeck Manchester NM Mr. Allen Lefkowitz Manchester NM Mr. Claude LeJeuene Storrs NM Mr. Heinrich Isaac Storrs NM

156 Workshop – A Two-Level Control Break Program
Note the Sub-Totals and total values.

157 COBOL Report Writing Patterns
Unit COBOL Report Writing Patterns Topics: Report Writing Concepts COBOL Print and Report Layouts Simple COBOL Reports Control Break Reports Appendices


Download ppt "Jon Sayles, IBM Software Group, Rational EcoSystems Team"

Similar presentations


Ads by Google