

COBOL for

the Approved

Workman

## by

# Wesley D. Sweetser, Jr.

wesleysweetser@netscape.net

## Companies, names and data used in examples in this text and the accompanying software are fictitious unless otherwise noted or Biblically true. No part of this book may be reprinted without written permission, except for brief quotations in books and critical reviews. The accompanying software on the student disk may be used by the purchaser in software development enterprises as long as credit is given to its source. Permission to use Micro Focus specific software is determined by the license granted by Micro Focus for each user or site.

Unless otherwise indicated, Scripture is taken from the New American Standard Bible Copyright © 1960, 1963, 1968, 1971, 1972, 1973, 1975, 1977, 1988 by the Lockman Foundation. Used by permission.

Scripture (marked NIV) taken from the HOLY BIBLE, NEW INTERNATIONAL VERSION Copyright © 1973, 1978, 1984 International Bible Society. Used by permission of Zondervan Bible Publishers.

Micro Focus COBOL, Micro Focus COBOL Toolset and Micro Focus Workbench are products of Micro Focus, Ltd. Copyright © 1993. Used by permission.

Micro Focus COBOL Workbench software suite is a product of Micro Focus, Ltd. Copyright © 1985-92. Used by permission.

## MS-DOS is a registered trademark and Windows is a trademark of Microsoft Corporation in the United States of America and other countries.

Copyright © 1995, 1996, 2018 by Wesley D. Sweetser, Jr. All rights reserved.

## Published electronically in the United States of America.

# Ephesians 2:10

# For we are His workmanship, created in Christ Jesus for good works, which God prepared beforehand, that we should walk in them.

# 2 Timothy 2:15

# Be diligent to present yourself approved to God as a workman who does not need to be ashamed, handling accurately the word of truth.

# Dedication

This work is dedicated first to the Lord from Whom I have receive my strength and Who has granted me so great a salvation, to my wife and children who have encouraged me greatly in this effort and tolerated me even more, to my students for whom this has been an act of love, and to my parents who gave me the desire to pursue a ministry of teaching.

Romans 10:9-10

"that if you confess with your mouth Jesus as Lord, and believe in your heart that God raised Him from the dead, you will be saved; for with the heart a person believes, resulting in righteousness, and with the mouth he confesses, resulting in salvation."
CONTENTS

Preface

Acknowledgments

# Style Note

Part 1 - Foundation

1. Introduction to COBOL

# 1.1 COBOL Overview

1.2 The Structure of COBOL

# 1.3 Functions in COBOL

Functions as Separate Files

# 1.4 Data Elements in COBOL

Character Data Type

Numeric Data Type

# 1.5 Software Development

# 1.6 Chapter Summary

# 1.7 Review Questions

# 1.8 Projects

2. Accessing Functions

# 2.1 Perform Command

Perform ... times

## Perform ... until

## Perform ... varying ... until

## Complete Program Example

# 2.2 Call Command

## Defining a COBOL Subprogram

## Using a COBOL Subprogram

## Example of a COBOL Caller-Called Pair

# 2.3 Chapter Summary

# 2.4 Review Questions

# 2.5 Projects

Part 2 - Tools

3. Interactive Programs

# 3.1 What are interactive programs?

Menu Component

Add component

Modify component

Delete component

## Display and Report components

# 3.2 Screen definition

Specifying lines and columns

Defining literals

Defining input/output fields

Defining display-only fields

Options: color, highlighting, auto, required

# 3.3 Screen handling

## Using Display to Clear the Screen

Positioning the Cursor

Displaying the Screen

Using Accept and Function Keys

# 3.4 Chapter Summary

# 3.5 Review Questions

# 3.6 Projects

4. File Input and Output

# 4.1 What are files?

# 4.2 Defining Indexed Files

Organization

Access Mode

Record Key

Alternate Record Key

Status

Assign

# 4.3 Using Indexed Files

Handling Errors

Read using a specific key

Start (preceding sequential Read)

Read sequentially

Write

Rewrite (preceded by Read)

Delete (preceded by Read)

# 4.4 Defining Sequential Files

# 4.5 Using Sequential Files

# 4.6 Defining Files for Network Use

Locking Files

Locking Records

Special Status Codes

# 4.7 Chapter Summary

# 4.8 Review Questions

# 4.9 Projects

5. Arithmetic

# 5.1 The Importance of Arithmetic

# 5.2 Arithmetic Objects

# 5.3 Arithmetic Operations

Add Command

Subtract Command

Multiply Command

Divide Command

Compute Command

# 5.4 Chapter Summary

# 5.5 Review Questions

# 5.6 Projects

6. Selection and Control

# 6.1 Introduction

# 6.2 Truth Tables

DeMorgan's Laws

# 6.3 Using if for Selection

Condition Names

if..else

Nested ifs

Evaluate

# 6.4 Using if for Control

Are numbers numbers

Are numbers zero

Are character fields blank

Checking specific values

Does a specific record key exist

# 6.5 Chapter Summary

# 6.6 Review Questions

# 6.7 Projects

7. Report Writer

# 7.1 What are Reports?

# 7.2 Report Data Elements

Headings

Detail Lines

## Decimal points

## Dollar signs and commas

## Negative numbers

## Subtotals and Totals

# 7.3 Report Processes

# 7.4 Complete Program Example

# 7.5 String

# 7.6 Chapter Summary

# 7.7 Review Questions

# 7.8 Projects

Part 3 - Special Topics

8. Tables

# 8.1 What are tables?

# 8.2 Why use tables?

# 8.3 Table definition

Defining the table as a data element

## Loading table data from an auxiliary file

# 8.4 Table handling

## Sorting a table

## Using if to find a table value

## Using Search to find a table value

## Binary search

## Sequential search

# 8.5 Indexed files table alternative

# 8.6 Chapter Summary

# 8.7 Review Questions

# 8.8 Projects

9. Sequential File Maintenance

# 9.1 Introduction

# 9.2 Process Overview

# 9.3 Edit Operation

# 9.4 Sorting Files

## Sorting Prior to Updating

## Sample Sort Program

## Sorting for Reporting

# 9.5 Merge Operation

Add Component

## Change Component

## Delete Component

# 9.6 Chapter Summary

# 9.7 Review Questions

# 9.8 Projects

Part 4 - Appendices

A. Using Workbench

B. Compiling and Linking

C. Workbench Screens Tool

# D. Workbench File Loader

About the Author
PREFACE

# Drawing from many years of professional software development and teaching experience, I prepared an innovative text that presents the COBOL language in a simple, yet powerful way, at the same time integrating Biblical perspective.

# Few textbooks address the simplicity of COBOL, many are unable to address the complexity of real-world systems, and few if any have attempted to integrate faith with content to prepare the students and new programmers for the workplace. This textbook has three goals. The first is to arm the Christian student with Scripture compatible with business-oriented programming, that they may be able witnesses for Christ. The second is to present COBOL in all its simplicity, that it may be a joy to use. The third is to present a realistic prototype system so students can be prepared for good works in their business endeavors.

# An overview of COBOL and the primary Christian emphasis are presented in the first chapter. Then using object-oriented methodology, functions and loops are presented in chapter 2 with only a few commands being needed to understand the program example given. Interactive programs are presented in chapter 3, with a menu which makes use of the mouse and a complete suite of software available on the student disk which can be tailored for use in any system.

Chapter 4 introduces files, with emphasis on indexed files. Chapter 5 and 6 cover arithmetic, along with selection and control. The Report Writer report generator available with many COBOL products is covered in chapter 7. Tables are presented in chapter 8 and the text concludes with coverage of sequential file maintenance in chapter 9. Appendices provide a pragmatic introduction to some Micro Focus Workbench tools, and compiling and linking in detail. Micro Focus has improved its products since this text was originally written so be sure to reference those aspects of the product currently available at https://www.microfocus.com/.

# The course was designed for a 10-week quarter system, where students have had one prior quarter of structured programming. The text can be adapted to a semester system by having students complete additional end-of-chapter projects and having them submit a term project. Language reference manuals may also be used in the semester system to present less popular additional features, as time allows, which may have been omitted from the text.

# End of chapter review questions are designed to help students highlight key points and in some cases go beyond the text to stretch their thinking. Projects in each chapter are geared to applying the tools presented, with various levels of difficulty. Some projects can be completed in a lab setting where students can receive assistance to become familiar with the basic concepts of the language and/or their development environment, while others require additional time and imagination.

# Software applications illustrating major chapter concepts are available electronically from

 https://drive.google.com/open?id=1ML7Y4Civl3PNv9Zzy496ZhsqeZrmmfx4.

# Any mention in the text of a student disk refers to this link.

The text was written primarily with the PC market in mind. However, since the essential elements of COBOL are standardized, the concepts, software and structures presented here can be used on mainframe computers as well with slight modifications. Having started using COBOL on mainframes in 1977, it has been my experience that COBOL is consistent on all varieties of computer platforms.

# I have found it a great joy to develop this text under the influence and leading of the Holy Spirit of God, and count it a privilege to present it to you.

# In Christ's service,

Wesley D. Sweetser, Jr.

# September 2018

# ACKNOWLEDGMENTS

# Giving thanks first to the Lord for His guidance, I next want to express my heartfelt thanks to my fall 1995 COBOL class who provided feedback to the first complete printing of this manuscript. Those I am especially grateful for include Erin Johns, David Moore, Andrew Woodman (who went all out for projects) and Jim Creswell.

# I am also grateful for input from the Coalition of Christian Colleges and Universities and especially Dr. Harold Heie who spurred me on in the area of integrating Christian faith with content.

STYLE NOTE

Mainframe COBOL code is typically all uppercase. I have chosen to present code mostly in lowercase since Micro Focus COBOL accepts that style. Each organization determines how COBOL code is represented.

# Part 1

Foundation

# 1 Corinthians 3:10-11

# According to the grace of God which was given to me, as a wise master builder I laid a foundation, and another is building upon it.

# But let each man be careful how he builds upon it. For no man can lay a foundation other than the one which is laid, which is Jesus Christ.
CHAPTER ONE

Return to contents

Introduction to

COBOL

# Isaiah 28:10

"For He says,

'Order on order, order on order,

Line on line, line on line,

A little here, a little there.' "

1.1 COBOL Overview

COBOL is a sophisticated, file-oriented language capable of creating and retrieving data on a massive scale with great flexibility and ease, both in a batch and interactive mode. COBOL stands for Common Business-Oriented Language and remains the mainstay of many businesses today.

COBOL is a symbolic language that brings order to business enterprises. Where there is disorder, we can use COBOL to create systems of programs to organize and rearrange data in meaningful ways. In a much more awesome manner, God created order from disorder and it was good:

Genesis 1:3-4

Then God said, "Let there be light"; and

there was light. And God saw that the

light was good; and God separated the

light from the darkness.

Colossians 1:16

For by Him all things were created, both

in the heavens and on earth, visible and

invisible, whether thrones or dominions

or rulers or authorities \-- all things

have been created by Him and for Him.

Throughout Scripture, we see how God has continued to order the world, particularly Israel in the Old Testament and the church in the New Testament. Each of the twelve tribes of Israel had a particular order in marching through the desert and in the setting up of the tabernacle, and there was order in constructing and rebuilding the Temple, to cite some Old Testament examples. With respect to the New Testament, the body of Christ is well ordered. It consists of many members, each with a particular function or purpose. We are admonished to do everything "decently and in order" (1 Corinthians 14:40) with regard to congregational worship.

Bringing order out of chaos is not only prized within the business enterprise, but order is also highly valued within a COBOL program itself. If bringing order out of chaos was good to God, then writing a well-ordered COBOL program is a good work. To accomplish orderliness, we will desire to have each component of our COBOL programs have a particular function or purpose, just as each member of the body of Christ has a particular function. We will accomplish this by making use of structured programming concepts that are based on using modules, process objects, or functions to carry out specific tasks.

The advantage to a business of having highly structured or well-ordered programs and systems of programs, built upon functional objects, lies in the reduced cost to develop the software initially and to maintain these programs and systems as changes need to be made over time. Our desire is to honor and to be like our God, who is a God of order, especially since we are His workmanship created in Him to perform good works (Eph. 2:10). For these reasons, the concept of functions is stressed throughout this text.

1.2 The Structure of COBOL

The structure of COBOL is somewhat precise. There are as many as four "divisions" that segregate programs into two minor regions and two major regions. The two minor regions identify the program and its operating environment, while the two major regions define the data elements and the processes or functions. We call these divisions

Identification Division.

Environment Division.

Data Division.

Procedure Division.

The following is a sample COBOL program showing two of these divisions:

identification division.

program-id. sample1.

* this is a comment line

procedure division.

display "Hello"

stop run.

The Program-ID entry should always correspond to the external file name, not including the file extension, which is used to identify the program. In Windows this limits the file name to 8 characters. Use the words stop run. to terminate a program. The period after the words stop run is recommended.

Columns have significance in the language in the ANSI 85 standard and earlier. Column 7 is reserved for asterisks to identify comment lines. You cannot go beyond column 72, except that columns 73-80 may be used for such things as a date or your initials to help provide an audit trail when changes are made.

When this program is executed, the word Hello is displayed on the screen. The lines display "Hello" and stop run. are referred to as statements. In addition to statements, COBOL uses functions and data elements.

1.3 Functions in COBOL

The Procedure Division has the capability of combining statements into functions or processes. These functions can be in line or they can be grouped at the end of the program. When grouped at the end of the program, it's good programming practice to include function headers and function exit points to facilitate testing and to make the programs easier to read and understand. For example, the program sample1 could be rewritten two ways as follows:

identification division.

program-id. sample1A.

* sample showing

* in line function

procedure division.

perform

display "Hello"

end-perform

stop run.

# OR

identification division.

program-id. sample1B.

* sample showing function

* at the end of the program

procedure division.

top-level.

perform display-routine thru dr-exit

stop run.

display-routine.

display "Hello".

dr-exit. exit.

A function generally carries out some specific task and is limited in size, say up to a page in length. The size of the function will often help determine whether you choose to have it at the end of a program, or as an in line function. A period is generally required at the end of the last statement in a function.

Regarding column positions, process headers and exit points should begin in column 8, while process statements (instructions or commands) historically have begun in column 12 with indentation used beyond that for nested instructions to enhance readability. You cannot go beyond column 72, except that columns 73-80 may be used for such things as a date or initials to help provide an audit trail when changes are made.

1.3.1 Functions as Separate Files

It's also possible and quite useful to store functions in separate files and have them automatically copied into your programs. This offers the advantage of reusing software already developed, thereby reducing development time and cost. This technique is used extensively throughout this text. Copying is accomplished using the COPY feature, as illustrated in the following example:

identification division.

program-id. sample1C.

* sample showing function at end of

* program copied from separate file

procedure division.

top-level.

perform display-routine thru dr-exit

stop run.

copy display1.pro.

For this example, a separate file must exist called display1.pro, which in this instance contains the following lines:

display-routine.

display "Hello"

display "Hello"

display "Hello"

display "Hello again".

dr-exit. exit.

Notice the period required at the end of the function's last statement before the exit point. Also notice the periods used to terminate the header itself, the exit point name and the word exit.

The starting column for function headers and exit points is column 8, function statements (instructions or commands) begin in column 12. Nesting of instructions is seen in later chapters where further indentation is used beyond column 12 to enhance readability and maintainability. If statements go beyond column 72, the program will never reach the stage where it can be run or executed. In these cases, simply move an entire word or words to the next line to resolve the problem. For instance,

display

"This is the day that the Lord has made"

display

"-- let us rejoice!"

# Another way to use functions is to have them as separately compiled programs. Discussion of this topic is delayed until the next chapter.

1.4 Data Elements in COBOL

# The following is a sample COBOL program showing three of the COBOL divisions plus one Data Division Section:

identification division.

program-id. sample2.

data division.

working-storage section.

1 my-object pic x(5) value "Hello".

procedure division.

display my-object

stop run.

The Data Division is used to declare data objects or define data elements. In this Division there are typically up to five sections (discussed in greater detail in later chapters):

Section Name Used to declare

File Section file data elements or objects

Working-Storage general purpose variable and constant objects

Report Section special report-writing object components

Screen Section screen object lines and columns

Linkage Section variables or objects to be transferred to external functions

# If all are used in a single program, it's advisable to include them in this order. Usually the Report Section and Screen Section would not reside in the same program.

The COPY feature is used to copy data descriptions as well as functions in order to reduce development effort and make programs easier to read and maintain. For instance,

identification division.

program-id. sample2B.

data division.

COPY "c:\projects\objects.ws".

procedure division.

display my-object

stop run.

Here, a separate file must exist on drive C:\ in sub directory projects called objects.ws, which in this instance could contain this code:

1 my-object pic x(5) value "Hello".

1 my-object-again pic x(5) value

"Hello".

Regarding columns and syntax, data elements generally are preceded starting with number 1 beginning in column 8. If a data element consists of several components, these would use numbers 2 through 49. Column 7 may be used for a hyphen to identify a continuation line in the Data Division, if needed, since code cannot extend beyond column 72. To avoid the use of the hyphen altogether, place your literal on a single line below the object name as illustrated above.

# If the literal is still too long, break it up into two or more literals, each of which will fit within the constraints as in this example

1 my-big-object pic x(100) value

"This is an example of a literal that does not fit This is an example of a literal that does not fit".

1 split-object.

3 my-object-part-1 pic x(50) value

"This is an example of a literal that fits".

3 my-object-part-2 pic x(50) value

"This is an example of a literal that fits".

The object split-object is referred to as a group and is assigned the number 1, while the number 3 was chosen for the group's two components. Periods are needed to terminate data declaration lines in the Data Division.

Notice that there is no period after the word value, since the literal on the line following actually completes the data declaration. Therefore the line with the literal requires the period.

# Consider the following:

1 in-date.

5 id-yy pic 99.

5 id-mm pic 99.

5 id-dd pic 99.

In the preceding code, in-date is a data element of length 6 consisting of three components, each of length 2. The object in-date is the group and assigned the number 1, while number 5 is chosen for the group's components. Names are assigned by the programmer. Pic stands for picture and establishes the length and type of an object. Nines (9's) are used to specify a numeric data type, while x's would be used to specify a character data type. Periods are needed at the end of each line.

Lower case and mixed case is acceptable for names. Data elements and commands are not case sensitive in COBOL. For instance, WAGE and Wage represent the same data element. Names may use up to 30 characters, which helps to make COBOL programs relatively self-documenting. Use letters, numbers and the hyphen in your names.

1.4.1 Character Data Type

Define character objects or data elements in a variety of ways. First we consider variable data elements -- those whose values may be altered during processing.

# Consider the following, which must appear in the Data Division:

1 my-object pic x(6).

# OR

1 my-object pic x(6) value "Hello".

# OR

1 my-object pic xxxxxx value "Hello".

In all the above, a character object of length 6 is being declared. Use an x to indicate the character data type. To specify a length of up to 255 characters or bytes, you may use that number of x's or include a number in parentheses immediately after a single x. Optionally, you may specify an initial value by using the word value followed by a literal contained in quotation marks. If the size of a character object is larger than the value of the literal assigned to it, the literal is aligned or justified on the left with spaces added onto the right to fill the field.

# Literals are case sensitive. For instance "Hello" is different from "HELLO".

# You can also specify constant character data elements -- those which you do not wish to alter or change. There is no protection against a constant being altered, however, as there is in some other languages. A typical example of a character constant is a report title or heading. For instance,

1 report-title-1.

7 pic x(43) value

"This is an example of a title 43 bytes long".

7 pic x(37) value spaces.

Notice the absence of a name between the number 7 and the word pic. When you do not plan on changing the value of an object, you need not assign a name to it. The group name report-title-1 is used to refer to the entire group, and it could be used to alter the group's state or value if needed. The word spaces is a COBOL reserved word which in this case initially fills the data element with all spaces.

It's also possible to assign new values to character data elements during processing. Use the move command in the Procedure Division to accomplish this activity. With character data, the following assignments are possible in the Procedure Division,

move spaces to my-object

move "Bye " to my-object

move "Bye" to my-object

1.4.2 Numeric Data Type

# Define numeric objects or data elements similarly. Consider this Data Division code:

1 my-object1 pic 9(2) value 75.

1 my-object2 pic 99 value zero.

1 my-object3 pic 9(3) value 365.

1 my-object4 pic 999 value 360.

In all the above, numeric objects of lengths 2 and 3 are being declared. Use a 9 to indicate the numeric data type. To specify a size of up to 18, you may use that number of 9's or include a number in parentheses immediately after a single 9. Optionally, you may specify an initial value by using the word value followed by a number. The word zero is a COBOL reserved word which in this case initially sets the value of the data element to zero.

# It's good programming practice to use names that provide you with as much information as possible about the data element. So instead of the above names it's better to use these:

1 size-of-table pic 9(2) value 75.

1 line-counter pic 99 value zero.

1 days-in-a-year pic 9(3) value 365.

1 degrees-in-circle pic 999 value 360.

New values can be assigned to numeric data elements during processing. Use the move command in the Procedure Division to accomplish this activity. Move only copies values. With numeric data, the following assignments are possible in the Procedure Division,

move zeros to line-counter

move 75 to size-of-table

move size-of-array to

degrees-in-a-circle

# In the last statement, we see that we can create a situation that will work correctly but which doesn't necessarily make any sense. Also, when moving a smaller numeric object to a larger numeric object the values are aligned by the implied decimal point.

# You can move numeric objects to character objects, since numbers are a subset of characters. It isn't advisable to move character objects to numeric objects as you may get unpredictable results or errors.

# 1.5 Software Development Process

# Every program or system of programs begins with a need. The need is documented and presented in the form of a request for services. If the need is genuine and the resources are available, the request is approved and the process of software development begins. This process consists of

Analysis

\- Developing specifications or objectives based on

user request and additional input from the requester/

user.

\- Developing a system plan using CASE tools and

including the inputs, outputs, and number and type of

programs to be written.

\- Developing test data along with controls to keep bad

data out.

Design

\- Designing program processes or functions using

CASE tools, pseudo code, etc.

\- Designing inputs and outputs.

Implementation

\- Writing the programs using C++, COBOL, Visual Basic,

etc.

\- Compiling, linking, testing and debugging all code.

\- Preparing documentation for the requester/user.

\- Converting files as needed.

\- Performing a system test, usually in parallel fashion

where the old and new systems are run side by side for

a period of time.

\- Turning the new system and documentation over to the

requester/user.

# As you can see, this development process is a good, well-ordered process. The better you perform analysis and design steps, the easier the implementation task becomes, resulting in lower software development costs.

# It is appropriate at this time to consider a system that may help us remember now the highlighted components listed above, and which will also help keep us focused later on God's transforming Word as we attempt to work in a business software environment as witnesses for Christ (underlines added):

The Christian walk as a system

Objectives:

## 1 Peter 1:4

to obtain an inheritance which is imperishable and undefiled and will not fade away, reserved in heaven for you,

Mark 16:15  
And He said to them, "Go into all the world and preach the gospel to all creation."

Input: the Word of God

Output: walking in the light

## Ephesians 5:8-9

for you were formerly darkness, but now you are light in the Lord; walk as children of light (for the fruit of the light consists in all goodness and righteousness and truth),

Controls, needed to minimize errors:

## Philippians 3:1

Finally, my brethren, rejoice in the Lord. To write the same things again is no trouble to me, and it is a safeguard for you.

## Matthew 26:41

"Keep watching and praying, that you may not enter into temptation; the spirit is willing, but the flesh is weak."

## John 14:15

"If you love Me, you will keep My commandments.

Process or Function:

Titus 3:5

He saved us, not on the basis of deeds which we have done in

righteousness, but according to His mercy, by the washing of

regeneration and renewing by the Holy Spirit,

Romans 12:2

And do not be conformed to this world, but be transformed by the

renewing of your mind, that you may prove what the will of God is, that which is good and acceptable and perfect.

## 2 Corinthians 3:18

But we all, with unveiled face beholding as in a mirror the glory of the Lord, are being transformed into the same image from glory to glory, just as from the Lord, the Spirit.

# Although our Christian walk is not an automated system, this provides us with a basis for understanding the different components required to produce an effective automated system: objectives, input, output, controls and processes or functions. (These verses are not intended to have direct applicability to computers, although some may be referenced in later chapters from a philosophical perspective.) The purpose of this illustration is to show the ordered components of our Christian life, which must also exist in our computer systems. Overall, without these components successfully interacting in our computer system, the system can become ineffective in the same way our Christian walk can become ineffective.

# Once the analysis and design are complete, the implementation begins. The implementation step, particularly writing programs using the COBOL language, will be the primary focus of the remainder of this text. However, this limited understanding of the analysis and design steps will prove useful as you strive to develop your programs in an orderly manner.

1.6 Chapter Summary

# We have seen in this chapter how God is a God of order. He created man in His image, and those who are believers in Jesus Christ are God's workmanship, created to do good works. We can use the COBOL language to give glory to God as we produce order from disorder in solving various business problems.

The structure of the language is precise. There are four divisions. You provide a Program-ID entry in a specific way and you include stop run. to terminate a program. Certain columns may not be used for other than comments. Functions are used to perform specific activities, functions consist of statements, and statements act on data elements.

Functions can be arranged in a variety of ways, depending on the size and reusability of the function or process. Functions can appear in line, they can appear at the end of a program, they can appear as separate files by using the COPY command, or they can be compiled as separate programs. Regardless of where the function appears, it must always be accessed in the proper order for the program to work correctly. Other stipulations may apply as well, such as the use of headers, exit points and periods in a correct manner.

A data element is defined in one of five sections of the Data Division, depending on how the data element is to be used. Data elements are defined using level numbers 1 through 49 (where 1 is for the group level) in addition to using the words pic and value. Pic determines the size and value specifies a starting value. Data elements may be character or numeric, they may be COPYed into a program from a separate file, and values may be moved to these data elements using the move command. The COBOL reserved word spaces is used to fill a character data element with spaces, while the word zero is used to set a numeric data element to zero.

The software development process helps us to proceed in an orderly manner as we are presented with requirements and needs of prospective system and program users and are requested to create software for these users. The analysis and design steps present us with the five basic components of every system: objectives, inputs, outputs, controls and processes or functions. We can best remember these components as we relate them to the system of our Christian walk. As we consider these daily in our own lives we can not only be more effective problem-solvers as we endeavor to complete the software implementation step, but we can be more effective witnesses for Christ as we strive to present ourselves "approved to God as a workman who does not need to be ashamed, handling accurately the word of truth." (2 Timothy 2:15)

1.7 Review Questions

1. Locate a Scripture not specified in the text that identifies God as a God of order.

2. What do we use in COBOL to accomplish orderliness?

3. How do you identify a comment line?

4. What statement is used to terminate a COBOL program?

5. Should a Program-ID entry be the same as the DOS file name?

6. Give one example of a process header.

7. Give one example of a process exit point.

8. Why is the statement exit. used as part of the process exit point?

9. Can you have more than one statement in a function?

# 10. What is the maximum allowable size for a function?

# 11. Is there any advantage to storing functions in separate files?

# 12. How are functions copied into your

# program from separate files?

# 13. In what column should process headers

begin and in what column should

# statements begin?

# 14. Why might you not see both a Report

# Section and Screen Section in the same

# program?

# 15. How many sections can there be in a

# COBOL Data Division?

# 16. What is the purpose of the File Section?

17. What is the maximum number of characters

# you can use to name an object?

18. What is the maximum size of a character

# data element?

# 19. What two COBOL words are used to assign

# values to data elements?

# 20. Is object HELLO the same as Hello? Is

# literal "HELLO" the same as "Hello"?

# 21. What are the three steps of the software

# development process?

# 22. What are the components of a system which

# we can relate to our Christian walk?

# 23. What Bible verse exhorts us to do quality

# software development?

# Answers to even-numbered review questions.

2. functions

4. stop run.

6. display-routine.

8. Using the statement exit. distinguishes the process exit

point from a new process header. For instance, in this

example there are just two process headers:

display-routine.

display "Hello".

dr-exit.

display "Hello".

10. The size of a function is determined by the programmer and may be

any size. A good rule of thumb is to keep functions about a page in

length.

12. By using the COPY feature

14. A Report Section would be part of a batch program, while a Screen

Section would be part of an interactive program. Although a batch

report can be generated from an interactive program there is not always

a need to have a screen associated with the program producing the

report.

16. To declare file data elements or objects such as student ID and student

name associated with a file of student information

18. 255 characters or bytes

20. yes; no

22. Objectives, input, output, controls, processes/functions

1.8 Projects

# 1. Compile, link and run the program sample1A in

# section 1.3 of the text.

# 2. Compile, link and run the program sample1B in

# section 1.3 of the text.

# 3. Compile, link and run the program sample1C in

# section 1.3.1 of the text.

# 4. Change the COPY file display1.pro to display a

# new message. Then compile, link and run the

# program sample1C using the new COPY file.

# 5. Create a COBOL program to display this

message using exactly one display command:

My name is (your name).

# What is your name?

# How are you today?

# 6. You have received a request to write a program

to print mailing labels. Describe the inputs,

outputs and processes to include.

# 7. You received a request to create a file containing

# names, addresses, hourly rate of pay and date of

hire. What sort of controls would you want to

include in the program that will create the file?
CHAPTER TWO

Return to contents

Accessing

Functions

# 1 Corinthians 12:18

# But now God has placed the members, each one of them, in the body, just as He desired.

2.1 Perform Command

There are several ways the perform command is used in COBOL. The most basic and the primary method is to access functions exactly once. This was illustrated in chapter 1 as follows:

* sample showing in line function

perform

display "Hello"

end-perform

# AND

main-routine.

perform display-routine thru dr-exit

...

display-routine.

display "Hello".

dr-exit. exit.

In the first case, the lines between the perform and end-perform are executed exactly once. In the second case, control is transferred to the function header, the function statements are executed exactly once, the function exit point is reached, and control is returned to the statement immediately following the perform. The use of the reserved word thru and the exit point name is optional. These options are helpful in longer programs and may be necessary in some older, poorly structured ones.

It is very important that you NEVER embed a perform as in this example:

main-routine.

perform display-routine thru dr-exit

...

stop run.

display-routine.

display "Hello"

perform main-routine.

dr-exit. exit.

Here control is transferred from the first perform to the display-routine function header, the first function statement is executed, then the second statement perform main-routine is executed. This causes control to be transferred back to main-routine's function header where the first perform is.

Control is then transferred to the display-routine function header again, the first function statement is executed, then the statement perform main-routine is executed again. This causes control to be transferred back to main-routine's function header where the first perform is.

# Control is transferred to the display-routine function header, the 1st function statement is executed, the 2nd function statement is executed. And so on.

It should be clear that the display-routine function exit point is NEVER reached in a normal fashion, so when is control returned to the statement immediately following the perform that started everything initially? Depending on which computer system you are using, at some point the system either a) becomes overloaded keeping track of all the performs that never complete and finally crashes, or b) you have an infinite loop - a loop that never ends.

# We are reminded of how our God of order has set each of us in His church. In 1 Corinthians 12:18 is written, "But now God has placed the members, each one of them, in the body, just as He desired." So we too should place our COBOL functions in a proper order just as we desire, and use them in a right manner.

Nesting of performs is okay, if such nesting meets the requirements of the particular design, as long as each perform completes in an orderly manner:

perform until all-done

perform routine-1

perform routine-2

perform routine-3

end-perform

Other ways perform is used is to execute statements more than once. The rest of this section will consider three different ways to create loops using the perform command:

perform ... times

perform ... until...

perform ... varying...until

2.1.1 Perform ... times

This option allows you to repeat a function a fixed number of times. This is good in situations where it is known exactly how many times you need to repeat a set of statements. The following example is part of a complete program labels.cbl available on the student disk and also referenced in the next few pages of this chapter:

perform setup-forms 5 times

stop run.

copy align.pro.

# The file align.pro contains the following statements,

setup-forms.

...

sf-exit. exit.

# You can see that a new routine has been presented, but the actual statements are left out for now. In this example,

1. control is transferred to the function header setup-forms

2. the function statements are executed once

3. the function exit point is reached

4. the entire process (1 through 3) repeats four more times

5. control is returned to the statement immediately following

the perform

# This particular routine is used to align special mailing labels in a printer. The user has five attempts to get it right. Is this a good idea? What if the user got it right after one attempt? What if it took longer than five attempts?

Can you think of other possible applications of perform ... times?

2.1.2 Perform ... until

This option allows you to repeat a function until some condition is met.

Data Division.

...

1 exit-flag pic 9 value zero.

Procedure Division.

perform main-process thru mp-exit until exit-flag = 1

stop run.

main-process.

...

mp-exit. Exit.

A new routine main-process has been presented, but the actual statements are left out for now. This allows us to focus on essentials, leaving details for later. We should also realize that any statements can go inside this function, depending on the particular application.

The numeric data element exit-flag must be defined in a section of the Data Division. This is what happens:

1. the condition is checked to see whether exit-flag has the

value of 1

Since exit-flag has been given an initial value of zero, the

function will be executed at least once in this case. Be

certain to know what the initial value of the data element is that's used for the until clause. If the initial value here was

1, the function would never execute.

2. control is transferred to the function header main-process

3. the function statements are executed

One of the statements inside the function must change the

value of exit-flag to 1, otherwise this becomes an infinite

loop - one that never ends.

4. the function exit point is reached

5. the condition is checked to see whether exit-flag

has the value of 1

if no, steps 2 through 5 are repeated,

if yes, control is returned to the statement immediately

following the perform.

It's important to note that the termination condition may be more elaborate by using NOT, AND and OR. For example:

perform main-process thru mp-exit

until exit-flag NOT = 0 OR

# error-code = "YES"

Using perform...until also gives us a better way of handling the label alignment discussed in the previous section, which offers the advantage of allowing the user to attempt aligning the forms as many or as few times as needed,

Data Division.

...

1 forms-set pic 9 value zero.

Procedure Division.

perform setup-forms until forms-set = 1

stop run.

copy align.pro.

The numeric data element forms-set must be defined in one of the sections of the Data Division. This is what happens:

1. the condition is checked to see whether forms-set

has the value of 1

Since forms-set has been given an initial value of

zero, the function will be executed at least once.

2. control is transferred to function header setup-forms

3. the function statements are executed, allowing the

user to align the forms

One of the statements inside the function must change the

value of forms-set to 1, otherwise this becomes an infinite

loop -- one which never ends.

4. the function exit point is reached

5. the condition is checked to see whether forms-set

has the value of 1

if no, steps 2 through 5 are repeated,

if yes, control is returned to the statement immediately

following the perform.

2.1.3 Perform ... varying ... until

This option is an enhancement to the perform...until which adds the use of a counter or index, similar to a for loop in BASIC or C++. The general form is this:

perform routine thru routine-exit

varying counter from 1 by 1

until counter > some-number

# OR

perform varying counter from 1 by 1

until counter > some-number

...

end-perform

Other increments are possible besides 1, and the starting value may be other than 1. As with perform...until, the condition may be a compound condition by using NOT, AND and OR. The data elements must be defined in the Data Division.

This structure can lend itself to a variety of situations, but is by no means required. However, it can be especially useful when dealing with tables, which are introduced in greater detail in chapter 8. Most tables consist of a specified number of rows, so by using perform...varying...until a table can be loaded from an external file, or a table can be output in an efficient manner. The following code illustrates the high-level structure for table loading in the labels.cbl program:

perform varying states-index from 1 by 1

# until loaded-flag = 1 OR

# end-of-states-file = 1

# ...

end-perform

# This in-line function is executed until the internal table is completely loaded from the external file, or the end of the external file has been reached. Since files are not elaborated upon until chapter 4 and tables until chapter 8, the precise details of the steps involved are reserved until that time. It is important to clearly understand the way functions are accessed in loops such as these before attempting to consider lower level processing commands.

2.1.4 Complete Program Example

Now that we have sufficient understanding of the different types of performs, it is time to see the entire labels.cbl program, with COPY files still hiding implementation details. This also serves to review the complete structure of a COBOL program, including the 4 Divisions and all the components in the proper order. I've capitalized the first letter of a few of the words below to show the variety available to you as program author.

Identification Division.

Program-ID. labels.

Environment Division.

File-control.

copy address.env.

copy labels.env.

copy states.env.

Data Division.

File Section.

copy address.fs.

copy labels.fs.

copy states.fs.

Working-Storage Section.

copy labels.ws.

copy states.ws.

1 exit-flag pic 9 value zero.

1 end-of-states-file pic 9 value 0.

Procedure Division.

perform prime-files

perform load-states

varying states-index from 1 by 1

until loaded-flag = 1 OR

end-of-states-file = 1

perform setup-forms 5 times

perform main-process thru mp-exit until exit-flag = 1

perform close-files

stop run.

copy load-sta.pro.

copy align.pro.

copy labels.pro.

{Notice the File-Control label in the Environment Division and how it is distinct from the File Section in the Data Division. This is discussed further in chapter 4.}

2.2 Call Command

The call command is used to access functions in COBOL when these functions are written as separately compiled programs or subprograms. The advantage of having functions as separately compiled programs is that they are more readily available to other programs. Some examples of general purpose subprograms include date conversion programs, database access programs and mouse-handling programs. Subprograms may be small and perform a single task or they may be large and carry out multiple tasks, even providing access to other subprograms. They may be written in COBOL or another high-level language such as C or C++. For information relating to accessing programs written in other languages, refer to the documentation for your specific system.

A separately compiled program must be linked to each main program that will be using it. Refer to your specific development environment for instructions on linking subprograms, or to Appendix B for the Micro Focus Workbench environment. If a routine is not intended to be used in a general way, you may choose to merely include it as part of the main program and perform it.

2.2.1 Defining a COBOL Subprogram

A COBOL subprogram is written as a complete COBOL program, therefore all valid COBOL commands can be used including perform and call. A subprogram may or may not receive data from the main program, depending on the design. If data is to be passed between a main program and a subprogram, then the Linkage Section is needed in the Data Division and a clause or "using list" is added to the Procedure Division line. A subprogram always terminates with the exit program. command:

Linkage Section.

1 Parameter-1 Pic 999.

1 Parameter-2 Pic X(20).

...

Procedure Division using Parameter-1, Parameter-2 ...

...

exit program.

You are not really limited to any number of parameters. If your system imposes a limit, combine the parameters in a group. Parameter values may be modified by either program. CAUTION: If a subprogram is called several times from a main program in a single session, the value of data elements in other than the Linkage Section remains the same as when the subprogram was last exited.

2.2.2 Using a COBOL Subprogram

Execute a COBOL subprogram by the call command:

Call "sub-pro-1" using Parameter-1

Parameter-2

...

This causes control to be transferred to the subprogram whose program-id is sub-pro-1. Processing continues in the subprogram until the exit program. command is reached, at which time control is returned to the main program. This concept is identical to the basic perform command and the same restriction applies as was mentioned earlier in section 2.1 regarding embedding.

The using list is optional and is only used if data is to be passed between the main program and the subprogram. This is similar in concept to parameter passing with functions in C++, Pascal and BASIC. The data type and size should correspond. If a smaller sized data element is passed to a larger data element, unexpected results may occur depending on the data type. If the data types are different, in most cases the process will not work correctly.

The order of data elements in the call using list and the procedure division using list must be the same. The actual names used in the separate programs can be different and the order of these data elements within the linkage section itself is not significant. It is helpful to keep the names in the linkage section in the same order as in the two using lists, however.

It is possible to specify a shorter using list in the calling program than in the called program if only several data elements need to be passed, as long the data type, size and order rules are adhered to.

2.2.3 Example of a COBOL Caller-

Called Pair

The following example is on the disk that came with the text and can be run as one of the end-of-chapter projects. REMINDER: The program-ID entry should always correspond to the external file name, not including the file extension, and is used to identify the program. In a DOS or Windows environment this limits the file name to 8 characters.

# In this example, some data elements in the using lists are listed on separate lines. This is for readability and to avoid going beyond column 72. The data elements may all remain on a single line, as long as they don't go beyond column 72.

2.3 Chapter Summary

# Just as God has placed the members, each believer, in the body of Christ, so too we must place functions in our COBOL programs and we must access them in an appropriate manner.

The perform command can be used to access a function exactly once or a multitude of times. We can use the word thru to highlight the entry and exit points of separate functions. We can perform a function until some condition is met, when a data element takes on a specified value or set of values. We must be careful to avoid infinite loops. We can make complex conditions by using NOT, AND and OR.

The call command can be used to access a function exactly once when the function is a separately compiled program or subprogram. The function entry point is the program-id entry of the subprogram. The called program substitutes exit program. in place of stop run. as the function exit point, so that control is returned to the calling program when the subprogram has completed processing. The Linkage Section and an optional Procedure Division using list are used in subprograms. The using list also appears with the call command itself whenever data is to be passed from the main program to the subprogram, or from the subprogram to the main program.

WARNING: If stop run. is used in a subprogram, control is returned to the operating system not the main program.

In this chapter there are two complete COBOL programs that incorporate functions, one using different varieties of perform and one using call. We now have the opportunity to work with these and make changes to these. Since there is nothing new under the sun (Ecclesiastes 1:9) it should be clear that most new programs are really enhancements to or modifications of existing programs, so it is important first to understand the programs presented in the text and work from those models to develop your own particular applications.

2.4 Review Questions

1. Is there a problem with the following code

# segment? If so, what is it?

main-routine.

perform display-routine

perform main-routine.

stop run.

display-routine.

display "Hello".

2. How many times will the mainstream

# function be executed?

Data Division.

Working-Storage Section.

1 field-w Pic 9(5) value 37.

Procedure Division.

perform mainstream field-w times

stop run.

mainstream.

...

m-exit. exit.

3. How many times will the function main-

proc be executed?

Data Division.

Working-Storage Section.

1 exit-flag pic 9 value zero.

Procedure Division.

perform main-proc thru mp-exit until exit-flag = 1

stop run.

main-proc.

move zero to exit-flag.

mp-exit. exit.

4. A truth table for AND is as follows, where

# 0 corresponds to false and 1 corresponds to

# true:

Develop truth tables for OR and NOT.

5. Describe two ways when

perform...varying...until can be especially

# useful.

6. When might call be preferred to perform?

7. What additional step is required to use call

versus perform?

8. What is the output from the following

# programs?

Identification Division.

Program-ID. Caller.

Data Division.

Working-Storage Section.

1 parameter-a Pic 9(5) Value 45314.

1 parameter-b Pic X(20) Value "Titusville".

1 parameter-c Pic 9 Value 0.

Procedure Division.

Calling-routine.

Call "Callee" using parameter-a parameter-b parameter-c

Display "Caller After a) " parameter-a

" b) " parameter-b

" c) " parameter-c

Stop run.

Identification Division.

Program-ID. Callee.

Data Division.

Linkage Section.

1 Parameter-1 Pic 9(5).

1 Parameter-2 Pic X(20).

1 Parameter-3 Pic 9.

1 Parameter-4 Pic X(5).

Procedure Division using parameter-1 parameter-2

parameter-3 parameter-4.

Receiving-routine.

Move 1 to parameter-3

Move "Hello" to parameter-4

exit program.

9. What is the value of exit-flag when the

subprogram is called the second time?

Identification Division.

Program-ID. Caller.

Procedure Division.

Calling-routine.

Call "Callee"

Call "Callee"

Stop run.

Identification Division.

Program-ID. Callee.

Data Division.

Working-Storage Section.

1 exit-flag pic 9 value zero.

Procedure Division.

move 1 to exit-flag.

exit program.

# Answers to even-numbered review questions.

2. 37

  4.

6. If a routine is intended to be used in a general way

8. Caller After a) 45314 b) Titusville c) 1

2.5 Projects

# 1. The following is the output data description

# for single labels:

1 label-line-1.

5 ll1-first-name pic x(10).

5 pic x value space.

5 ll1-last-name pic x(20).

1 label-line-2.

5 ll2-street-address pic x(25).

1 label-line-3.

5 ll3-city pic x(12).

5 pic xx value ", ".

5 ll3-state pic x(20).

5 pic x value space.

5 ll3-zip pic x(10).

Design a form and associated data

# description to handle 2-up labels, which are

labels that are side by side on the paper.

# 2. Create a sub directory for the labels program

that came with the text, copy labels.cbl and

# all required files to that sub directory, then

# compile, link and run the labels program.

# 3. Modify program sample1B on page 3 of the

text to display "Hello" exactly 13 times using a single perform.

# 4. Modify program sample1B on page 3 of the

# text to display "Hello" until the user enters

# the word "BYE". To do this you need to

# declare a 3-character data element in the

# Working-Storage Section of the Data

Division and you use the accept command

# in the Procedure Division, which is used to

# accept user input from the keyboard as in

# this example:

1 user-word pic xxx.

...

accept user-word

The accept command halts processing until

# the <Enter> key is pressed. The user can

# type any sequence of characters or none at

# all followed by the <Enter> key to resume

# processing. Where would you place this new command in your program?

# 5. Create a sub directory for the caller-callee

# pair of programs that came with the text,

copy caller.cbl and callee.cbl to that sub

# directory, then compile, link and run the

# programs. Ask your instructor for the

# information on correctly linking a

subprogram; or use the file calllink.bat on

# the text disk for the Micro Focus Workbench

# environment.

# 6. Create a caller-called pair of programs.

# Have the called program display the word

# "Hello".

# 7. Create a calling-called pair of programs.

# Have the called program display the word

"Hello" 13 times using a single perform.

You're only allowed to call the program

# once.

# 8. Create a calling-called pair of programs.

# Have the called program display

# information passed from the calling program.
Part 2

Tools

1 Corinthians 3:12-13

Now if any man builds upon the foundation

with gold, silver, precious stones, wood, hay, straw,

each man's work will become evident;

for the day will show it, because it is to be revealed with fire; and the fire itself will test the quality of each man's work.
CHAPTER THREE

Return to contents

Interactive

Programs

# Philippians 4:6

# Be anxious for nothing, but in everything by prayer

# and supplication with thanksgiving let your requests

# be made known to God.

3.1 What are interactive programs?

# As believers, we interact with God through prayer and the study of His Word. We are an interactive people serving an interactive God. We can also interact with the computer, although the information we get from the computer is by no means comparable to what God offers us. All the computer can offer us is what we or someone else has programmed or entered into it.

An interactive program is one where a user may enter information using a screen, then data is checked for validity and immediately updates a file or database or carries out some other task. This is in contrast to strictly batch programs, where a user enters or processes data in batches or bunches of records which are processed at a later time, often postponing checks for errors or validation checks. Historically, users would get errors back later that day or the next day and have to make corrections later as well. This meant report information was often out of date by the time it reached management. Today, menus provide an interface to interactive update functions and are also used to trigger reports which are generated immediately based on the latest information.

In the previous chapter we looked at accessing functions using perform and call. Useful programs are collections of functions, and interactive programs are the preferred method today for processing information. Now that we have the foundational knowledge of how to access a function, it is appropriate to consider and attempt to understand some useful programs or collections of functions where the perform and call commands are used. We will still be omitting some details until such time as our understanding increases. Even then some things we may have to accept sheerly by faith, others we can accept after rigorous testing.

# An interactive program or system of programs may consist of one or more of the following components, which may be executed as functions within one large program or as separate subprograms:

# Menu component

# Add component

# Modify component

# Delete component

# Display component

# Reporting component

These is presented in such a manner that an understanding of the perform and call commands from the previous chapter are all that are needed to grasp the top-level processing, while the lower level processing is considered throughout the rest of the text as new information is presented.

3.1.1 Menu Component

# The purpose of the menu is to have a starting point for other processes within the system. A menu is a list of available choices. Each company has its own standards for what menu screens should look like. The following example shows the date and time in the menu:

The following program, which makes use of the mouse, can be used to generate a menu and is also included on the disk which came with the text. This program can be tailored to be used to generate any menu with up to 36 options or choices. This program will be used as is, and with minor cosmetic changes for various projects, providing a simple yet sophisticated interface to allow maximum exposure to real-world technology given a limited amount of time available.

****************************************************************

* Menu.CBL

*

* This program is for use in the classroom to demonstrate

* and apply object-oriented concepts.

*

****************************************************************

* CHANGE LOG

* Date RI

* ------ ---

* New program Jan-95 WDS

*

****************************************************************

Identification Division.

Program-id. Menu.

Data Division.

working-storage section.

copy time.ws.

copy date.ws.

copy messages.ws.

copy mousparm.ws.

screen section.

copy menu.ss.

Procedure Division.

perform Set-Up

perform until escape-key-activated

perform Run-Application

perform Screen-IO

end-perform

perform Wrap-Up

Stop Run.

*****************************************************************

* functions

*****************************************************************

Set-Up. copy set-up.pro.

Run-Application. copy run-appl.pro.

Screen-IO. copy screenIO.pro.

Wrap-Up. copy wrap-up.pro.

The CHANGE LOG is a documentation tool used by many companies in various forms to keep track of changes along with the individual responsible for those changes (RI). Notice that the function headers have been separated from their COPY files to help you see more clearly the functional relationships. The screen section is discussed later in this chapter. Escape-key-activated is a condition name. Condition names are formally presented in chapter 6.

# The high-level processing for a menu program is fairly straightforward. There is some initial setup required, including turning on the mouse and priming the menu. Then a loop is started. The option selected by the user from the menu is used to run a specific application component. Once that completes, control is returned and the menu is re-displayed, awaiting another user response. When the user finally presses the escape key, the program finishes.

The add and display components will also be shown in order to provide sufficient meat for further discussion, while the other components will only be presented conceptually in order to prevent overload. The report component is presented in chapter 7. The complete system is available on the student disk and can be tailored to suit a variety of information processing applications in this or more advanced classes as time permits.

3.1.2 Add component

# This adds new records to a file or database. A screen to add one record at a time is illustrated by the following:

A complete, working program to add one record per screen (for a different screen than the one shown above) is listed below and included on the accompanying disk. This program begins to show the full capability of COBOL. For instance, four sections are included in the Data Division. Also, two sections are shown in the Environment Division. Discussion of the Input-output Section with File-Control will be deferred until the next chapter. The Configuration Section with Special-names assists us in the Micro Focus environment in the areas of screen handling and in the use of function keys, both of which are covered later in this chapter.

Identification Division.

Program-id. Parts-01.

* This program is called from the main menu to add records

Environment Division.

Configuration Section.

Special-names.

cursor cursor-position

crt status function-key-status

console crt.

Input-output Section.

File-control. copy parts.env.

Data Division.

File Section. copy parts.fs.

Working-Storage Section.

copy common1.ws.

copy messages.ws.

copy time.ws.

1 parts-status Pic XX.

1 hold-rec Pic x(46).

1 error-flag Pic 9 value zero.

Linkage Section.

1 menu-date Pic x(9).

Screen Section. copy "Add.SS".

Procedure Division using menu-date.

Perform Initial-Set-Up

* main processing loop

Perform until escape-key-pressed

Perform Edit-Record thru ER-exit

Perform Add-Record

Perform Add-Screen-IO

end-perform

Perform Wrap-up

Exit Program.

copy parts-01.pro.

It should be clear that the structure of the Procedure Division is similar to that of the menu program: there is some initial setup required, including priming the screen (but no mouse). Priming here means displaying the screen the first time and allowing the user to enter data before the loop condition is checked the first time. Then the loop is started and continues until the escape key is pressed, when the program finishes. Within the loop, instead of an option being selected, data is entered and checked for errors. A record is added, if there are no errors, and the screen is re-displayed ready for new data.

Design Note: Adding more than one record on a single screen involves the use of tables and careful checking to see that the same record is not entered twice on the one screen. This is useful in cases where no more than 80 characters of information are added for each record and it can save the data entry person time, but it is beyond the scope of this text.

3.1.3 Modify component

This component allows the user to change records added earlier. The process requires two steps. The first is to accept the key field. The second is to take a valid key field and locate the record in the file. (The process of using keys is discussed in more detail in Chapter 4.) Two separate screens may be involved. The second one might be similar to the add screen above, but with no entry allowed for the key field. The first screen could look like this:

# A complete modify program is included on the student disk, which may be tailored as needed to suit your particular needs. The algorithm is more complex than for the add function and will not be formally presented. Testing it is left as one of the end-of-chapter projects. The essence of the modify process is that a unique search key field must be correct on the first screen for the second screen to be displayed. Then any changes made on the second screen must be correct for the record to be permanently changed, although the user has the option of changing their mind and backing out of the entire process.

3.1.4 Delete component

# This allows the user to delete a record no longer needed. A delete function should always be used with caution, with file backups being made regularly. This should be a two step process. The user enters a key on one screen. The information is then displayed on a second screen. The user is prompted to confirm the deletion, with the option of keeping the record in case the wrong key was entered. It is somewhat similar at the top level to the modify function, although simpler. It too will not be formally presented.

# The first screen would resemble the one for the modify function. The second screen might look like this:

3.1.5 Display and Report components

# The display function lets the user view a record or records on the screen. For a single record, the screen would contain whatever information from the file or database the user needed to see to do their job, similar to previous detailed screen examples.

# The reporting function allows for hard-copy reports to be generated. These reports vary and are designed as needed for each user and each system. Depending on the design, the report may be sent to a file or sent directly to the printer. If sent to a file, users have the option of printing it and/or viewing it using an editor or word processor. The reporting function may display another menu of reports for a large system, or create a single report for a small system. A complete report program is shown in chapter 7, while the display program is below.

Identification Division.

Program-ID. Parts-02.

* This program is called from the Parts main menu

* to display records from the Parts file

Environment Division.

Configuration Section.

Special-names.

cursor cursor-position

crt status function-key-status

console crt.

File-control. copy parts.env.

Data Division.

File Section. copy parts.fs.

Working-Storage Section.

copy common1.ws.

copy messages.ws.

copy time.ws.

1 parts-status Pic XX.

1 Stored-Number Pic x(8).

Linkage Section.

1 menu-date Pic x(9).

Screen Section. copy "Disp.SS".

Procedure Division using menu-date.

Perform Initial-Set-up

* main processing loop

Perform until escape-key-pressed

Perform Find-Record

Perform Screen-IO

end-perform

Perform Wrap-Up.

Exit Program.

copy parts-02.pro.

This program lets the user view a single record at a time on the screen. Notice as in the add program, the current date stored in menu-date is passed from the menu program as a parameter. Why is the time not passed as well?

Design Note: If only a lineful of information is needed for each record (up to 80 characters) it is often better to display multiple records on a single screen. This requires slightly more sophisticated programming techniques, again beyond the scope of an introductory college text, but is useful for many applications.

3.2 Screen definition

Now that we've seen some interactive functions, it is time to examine the screen element. If you do not have the Micro Focus Workbench product, some of this information may not apply to you. If that is the case, refer to your specific system manuals for more information on defining screens. The screen element is what changes for each new application, while the basic structure of the interactive functions themselves need not change regardless of how you define screens in your system.

A good starting point for generating the code for your screen is the Screens facility (Alt-F2) within Micro Focus Workbench. For more information, please refer to the Micro Focus web site https://www.microfocus.com/, the Workbench interactive Help facility within Screens or Appendix C of this text. Actual COBOL code can be generated automatically, which can reduce your development effort.

A screen can be defined in the Screen Section of the Data Division. The key areas of interest related to defining a screen are:

# specifying lines and columns

# defining literals

# defining input/output fields

# defining display-only fields

# options: color, highlighting, auto, required

# The following sample will be referred to in discussing these topics:

1 Sample-Screen highlight foreground-color 3.

3 Line 1 background-color 4.

5 Col 1 Pic X(25) from out-date.

5 Col 26 Value "Sample Add Screen".

5 Col 76 Pic 99 from IT-HH.

5 Col 78 value ":".

5 Col 79 Pic 99 from IT-MM.

3 background-color 1.

5 Line 6 Col 26 Value "Name".

5 Line 8 Col 26 Value "E-mail address".

5 Line 10 Col 26 Value "Date".

5 Line 24 Col 1 Value "Press <Esc> to Quit".

5 Line 6 Col 50 Pic X(20) using OR-name auto required.

5 Line 8 Col 46 Pic X(8) using OR-address auto.

5 Line 10 Col 46 Pic 99/99/99 using OR-date auto.

3.2.1 Specifying lines and columns

You specify the line you want a literal or variable to appear on by using the word Line and specifying a number between 1 and 24. You specify a column by using the word Col and specifying a number between 1 and 80. A line number may be specified at a group level. For instance, in this example level 3 is used for the group or line, while level 5 is used for the columns on that line:

3 Line 1 background-color 4.

5 Col 1 Pic X(25) from out-date.

5 Col 26 Value "Sample Add Screen ".

5 Col 76 Pic 99 from IT-HH.

5 Col 78 value ":".

5 Col 79 Pic 99 from IT-MM.

3.2.2 Defining literals

You specify a literal, also known as a screen label, by identifying the line and column and using value with the label enclosed in quotes. No pic is used for literals in the Screen Section of the Data Division.

5 Line 6 Col 26 Value "Name".

3.2.3 Defining input/output fields

Fields which are to be used for input and output must first be defined elsewhere in the Data Division. Then you must specify the line and column and use both pic and using,

5 Line 10 Col 46 Pic 99/99/99 using OR-date auto.

The format of the OR-date field as it appears in another part of the Data Division could be 5 OR-date Pic 9(6). The data appears on the screen with slashes yet is actually stored without the slashes. The slash, period and dash are special editing characters representing a slash, decimal point and minus sign respectively.

Numeric data elements or fields can be defined with a decimal point and a sign in the Data Division. Input fields and temporary fields use implied decimal points (V) and implied signs (S), while output fields use real decimal points (.) and real signs (+ or -). When you move the input field to the output field, numbers are automatically aligned by the decimal points, and minus signs will appear for negative numbers. This is discussed more in chapter 7.

3.2.4 Defining display-only fields

Fields which are to be used for display only must first be defined elsewhere in the Data Division. Then you must specify the line and column and use both pic and from,

5 Col 1 Pic X(25) from out-date.

# In this example, the picture string of 25 is actually longer than the field from which it is being taken. This is done here to maintain the color across this line of the screen. The character field is left-justified and filled with spaces on the right for the extra characters, and the color fills the entire 25 character field.

3.2.5 Options: color, highlighting, auto,

required

A number of colors are available, both fore-ground and background. Colors are shown in detail in the Screens facility (Alt-F2). In this example there is a red background and white letters,

1 Sample-Screen highlight foreground-color 3.

3 Line 1 background-color 4.

# Highlighting makes characters high intensity or extra bright and can be used at the group level or individual field level,

1 Sample-Screen highlight foreground-color 3.

The auto option causes automatic continuation to the next field on the screen after the current field is filled. Without this option, the Tab key is used to manually go to the next field. The auto option is therefore a great time saver for the data entry person.

5 Line 8 Col 46 Pic X(8) using OR-address auto.

The required option is used to require the data entry person to enter information into the field. This is especially important when critical key fields are being entered,

5 Line 6 Col 50 Pic X(20) using OR-name auto required.

3.3 Screen handling

COBOL commands needed to handle screens are display and accept. The display command presents the screen to the user, while the accept command presents the information from the screen back to the program. The display command was first presented in chapter 1, where it was used to display literals and data elements.

# In addition to these standard commands, Micro Focus also provides functions to determine whether special keys (escape, F1, F2, etc.) have been pressed, which can be used to enhance screen processing.

Both of the standard screen handling commands can also be used to deal with individual fields in conjunction with specific parameters provided by ANSI-85 COBOL. They can be used in such a fashion that you define your screen as you process it. This is a more time-consuming process, but was used for early PC COBOL software development. One example of this is described in section 3.3.3 below, but please refer to your system's language reference manuals for a complete listing of options and parameters available.

3.3.1 Using Display to Clear the Screen

# Before displaying a menu or data entry screen, first clear the screen. This is when an entry in the Special-names part of the Environment Division becomes helpful:

Environment Division.

Configuration Section.

Special-names.

## cursor cursor-position

## crt status function-key-status

## console crt.

# The Procedure Division command to clear the screen is then simply

Display spaces upon crt

3.3.2 Positioning the Cursor

The cursor-position field is used to place the cursor in a particular field prior to displaying the screen. This is especially useful when you have a large screen requiring extensive data validation and you want to have the cursor appear on the field which has generated an error when you redisplay the screen, so the data entry person can correct the error without having to use the Tab key to move to the field in error.

# This also requires an entry in the Special-names part of the Environment Division:

Special-names.

## cursor cursor-position

## crt status function-key-status

## console crt.

# The Data Division entry would be

1 cursor-position Pic 9999 value 0650.

# where the value is the line and column position where you want the cursor to start.

# To position the cursor at line 8 and column 37, Procedure Division entries are

Move 0837 to cursor-position

Display Add-screen

3.3.3 Displaying the Screen

# Because the screen is defined in the Screen Section, it is displayed simply,

Display Add-screen

# If you do not have the capability of creating screens in the Screen Section and displaying them in this simple fashion, then you may have to essentially define your screen in the Procedure Division by using pairs of display and accept commands in this manner:

display "Please enter your user ID: " at 0210

with highlight

accept pr-user at 0238

display "Please enter your password:" at 0310

with highlight

accept pr-pwd at 0338 with no-echo

The with parameter lets you specify options such as highlight, which was mentioned earlier in this chapter. The at parameter lets you specify line and column positions. Although this is more time-consuming for large screens, it is still effective. The interactive components presented in this chapter and on the disk would need modifications to the Screen-IO functions, but should generally work even with this type of screen definition.

3.3.4 Using Accept

Accept is used to get data supplied by the user. If the last field on the screen is defined with the auto feature, then once the user has completely filled the last field with data, control is returned to the program along with all the screen's data. If the last field is not defined with the auto feature, then the user must press the Enter key or an assigned function key before control is returned to the program.

# Because the screen is defined in the Screen Section, it is accepted simply,

Accept Add-screen

Accept is also used to get the system date and system time. The preferred system dates for MS-DOS are defined as "year-month-day" and "year-julian day", while the system time is defined as "hours-minutes-seconds-etc.". If you're working in an environment other than MS-DOS, check your system manuals for date and time formats. The following code is included in COPY files used in the menu and add programs described earlier:

* "date.ws"

1 in-date.

5 id-yy pic 99.

5 id-mm pic 99.

5 id-dd pic 99.

1 out-date.

5 pic x(1) value space.

5 od-mm pic 99.

5 pic x value "/".

5 od-dd pic 99.

5 pic x value "/".

5 od-yy pic 99.

* "time.ws"

1 in-time.

5 it-hh pic 99.

5 it-mm pic 99.

5 pic x(4).

* "get-date.pro"

accept in-date from date

move id-mm to od-mm

move id-dd to od-dd

move id-yy to od-yy.

* "screenIO.pro"

accept in-time from time

3.3.5 Using Function Keys

To use the escape key or other function keys requires the following entry in the Environment Division to be used in determining which special key was pressed:

Special-names.

# cursor cursor-position

# crt status function-key-status

# console crt.

This function-key-status is described in the file common1.ws available on the student disk, and must be COPYed in the Data Division as is to use function keys:

1 function-key-status.

5 function-key-type Pic x.

88 enter-key-pressed value "0".

88 function-key-pressed value "1".

5 function-key-code Pic 9(2) comp-x.

88 escape-key-pressed value 0.

5 Pic x.

Whenever the escape key or a function key is pressed during screen processing, the value is returned in the function-key-code field. The usage type comp-x is a different way to represent numbers (covered in more detail at the end of the next chapter) and the number 88 is discussed in chapter 6. The system-assigned value for the escape key is 0, while the values for other function keys are 1-10. To use all available function keys (escape, F1 to F10) requires the following additional entries in the Data Division, already included in common1.ws:

1 function-key-handling-on Pic 9(2) comp-x value 1.

1 function-key-control.

5 function-keys-enabled pic 9(2) comp-x value 1.

5 pic x value "1".

5 first-key-to-enable pic 9(2) comp-x value 0.

5 number-of-keys-enabled pic 9(2) comp-x value 11.

# The Procedure Division entry to turn everything on is

call x"af" using function-key-handling-on

# function-key-control.

The function x"af" is part of ADIS, provided by Micro Focus, which is automatically linked with your program in order to use the function keys. The values you could adjust are first-key-to-enable and number-of-keys-enabled. The settings of 0 and 11, respectively, specify that the escape key is the first key to turn on and 11 keys altogether are enabled starting with the escape key. Your particular design with affect your choice of function keys. How could you make good use of function keys?

3.4 Chapter Summary

An interactive program can be a menu, serving as an interface to other programs. Or it can manipulate a database by adding, modifying or deleting records. There would be no value in updating a database if it could not be displayed or reported. Three of these programs have now been presented and can now be used throughout the remainder of the text, as is or with changes. The entire suite of these essential interactive programs is available on the student disk to be used as needed in more advanced courses.

The screen is the principal input/output medium for the interactive program. Screen design is an important task, yet one which can be performed quite easily with a screen painting tool. It is also possible to type the screen code in manually or to make changes to the screen code that is generated automatically. Some options that might be changed include color, highlighting, automatic tabbing and making a field a required entry.

Screen manipulation is accomplished by using display and accept commands. The screen can be cleared as needed and the cursor can be placed anywhere on the screen. The accept command is also used to obtain the system date and time. Function keys can be included to handle special processes to make the interactive programs more user-friendly. SPECIAL NOTE: The menu program included with the text is only designed to use the escape key and no other function keys. The other programs can be modified to incorporate all function keys.

# We can now create useful programs to create and display data. In the next chapter, we will see commands for manipulating files in order to be able to create new files to be used with our interactive programs.

3.5 Review Questions

# 1. Find a Bible verse that illustrates how God

# is an interactive God.

# 2. Provide a definition of a useful program.

# 3. What type of program should a student

# registration program be, batch or

interactive?

# 4. What's the purpose of a menu? What's a

# menu?

# 5. What's the matter with the following menu

# algorithm?

# perform Set-Up

# perform

# perform Run-Application

# perform Screen-IO

# end-perform

# perform Wrap-Up

# Stop Run.

6. Why would 36 options or choices be a good

# maximum number for a menu?

# 7. What's the matter with the following add

# routine?

Perform Initial-Set-Up

Perform until escape-key-pressed

# Perform Edit-Record thru ER-exit

Perform Add-Screen-IO

Perform Add-Record

end-perform

Perform Wrap-up

Exit Program.

8. In what Division is Special-names placed?

# What Section?

# 9. What is the matter with the following add

# routine?

Perform Initial-Set-Up

Perform until escape-key-pressed

# Perform Edit-Record thru ER-exit

Perform Add-Record

Perform Add-Screen-IO

end-perform

Perform Wrap-up

Stop Run.

# 10. Why might the user not want to follow

# through with a change or delete operation?

# 11. What is the matter with the following

# display routine?

Perform Initial-Set-up

Perform until escape-key-pressed

Perform Find-Record

Perform Screen-IO

Perform Wrap-Up

end-perform

Exit Program.

# 12. Why isn't the current system time passed as

# a parameter when the menu program calls

# another program?

# 13. What is the matter with the following

# Screen Section line?

5 Line 6 Col 26 Pic x(4) Value "Name".

# 14. What is the matter with the following

# Screen Section line?

5 Col 1 Pic X(25) from out-date value 0.

# 15. Write a pair of COBOL statements to

position the cursor at line 17, row 8 when

# displaying Modify-Screen.

16. I want to use the escape key in my program.

# What do I need to fix in the following code

to make certain the escape key will work?

1 function-key-control.

5 function-keys-enabled pic 9(2) comp-x value 1.

5 pic x value "1".

5 first-key-to-enable pic 9(2) comp-x value 1.

5 number-of-keys-enabled pic 9(2) comp-x value 10.

# Answers to even-numbered review questions.

2. A useful program is a collection of functions.

4. The purpose of a menu is to serve as the starting point for other

processes. A menu is a list of available choices.

6. For a single character, there are 26 letters of the alphabet and 10 digits.

8. Environment; Configuration

10. The user may have the wrong employee or student and need to start over.

12. Once the menu calls another program, that program may have control for the rest of the day. Passing the current time doesn't make sense under those conditions. The called program will have to fetch the current time for it to be accurate.

14. pic and value are not used together in the Screen Section

16. first-key-to-enable should have the value 0 to specify the escape key as the first key to turn on, and number-of-keys-enabled should be 11

3.6 Projects

1. Create a sub directory and copy all files from the sub directory interact on the student disk. Compile, link and run the menu and related programs for the parts inventory system included on the student disk. Use the parts.bat file to accomplish this. Rename the .exe file as dosmenu.exe.

# 2. After completing project 1, download the

# Microfocus Visual COBOL trial and use Visual Studio to see how the COBOL files

# look.

3. Develop a test plan to test the modify component of the parts inventory system from the previous problem. To accomplish this, examine the screen and consider what you would expect should be tested, making a check list to record your observations. (Since you did not participate in the design of the original system, there is no way you could know what was supposed to be included in a test plan.) Add some records using the add component, then rigorously test the modify program and record any deviations from your test plan.

4. Design a HELP screen. Then automatically generate COBOL code and save it. Compile, link and run the automatically generated program within Workbench.

# 5. Change the menu screen description (menu.ss) to include a new label. (This new label might be used to provide the user with information on how to select a help function.) Use the letter H as the trigger mechanism.

6. Compile, link and run the program fct.cbl using the functions.bat file found on the

student disk. This program makes use of function keys. Change the COPY file which displays the messages and make different

messages be displayed for each function key.

7. Integrate a HELP screen with the menu. In the HELP screen, include information on which selections can be made from the menu and what operations can be per- formed. Allow the user to press the letter H to display the HELP screen. Assign the program-ID HELP01 to the Help function.

The solution also requires making minor changes to five items in menu.cbl COPY files. Carefully change:

# 1) menu.ss to show the extra choice on the menu,

# 2) messages.ws to show the new choice,

# 3) mousparm.ws to handle the additional selection,

# 4) run-appl.pro to execute the new program, and

# 5) parts.bat to include the new program.

In menu.ss, this line could be added (where?):

## 3 Line 23 Col 60 Highlight value "[Help - Press H]".

In messages.ws, change this line:

1 Message1 pic X(38) value

"Valid Menu options are 1 thru 5, and H".

In mousparm.ws, change the following:

88 valid-option values "1" thru "5".

==> "1" thru "5" "H".

1 number-of-options Pic 99 value 5.

==> value 6.

5 option-table occurs 5 times.

==> 6 times.

and add the 6th entry (by copying the 5th

entry and changing six characters):

# 5 sixth-entry.

10 pic x(6) comp-x value h"0017003D004A".

# 10 pic x value "H".

The value here is represented in hexadecimal

or base 16. The number 0017 in base 16 is

23 in base 10. The number 3D in

hexadecimal is 61 in decimal. The number

4A in hex is 74 in base 10. There is a

relationship between these hexadecimal

numbers and the line and col of the screen

definition. Keep them consistent for the

mouse to work.

In run-appl.pro, add another WHEN clause

(by copying and modifying a line):

# when "H" Call "Help01"

In parts.bat, add HELP01 to the list:

parts-01+parts-02+parts-03+parts-04+parts-05+HELP01+
CHAPTER FOUR

Return to contents

File Input and

Output

# Ephesians 5:8-9

# for you were formerly darkness, but now you are

# light in the Lord; walk as children of light (for the

# fruit of the light consists in all goodness and

# righteousness and truth),

# Matthew 15:11

# "Not what enters into the mouth defiles the man, but what proceeds out of the mouth, this defiles the man."

4.1 What are files?

Files are the output from some process or system. They are input to other processes or systems. We are to output God's light in our lives, so that God's Word and His Spirit might be input into someone else's life. The fruit of the Spirit is to be output from our lives, that others might be blessed. Our output can only change when God's Spirit is input and takes control of our lives, by His marvelous grace.

Files are also how and where data is stored. Both good and bad data can exist in a file, depending on the controls used. For man, that which is stored up in the heart is bad because of the sinful condition of the heart. Born-again believers, however, are repositories of God's good Spirit.

The first files were stored sequentially on paper tape and cards. Files are made up of records, while records consist of fields. Examples of records might be an employee payroll record or a student record. Examples of fields would include last name field, student ID field and expiration date field.

Today, files are stored on hard disks or CDs or DVDs so data can be accessed quickly and efficiently using indexes. These indexed files have two components. One is the data component and the other is the index component or search key. The most popular form of storage for indexed files is as relational database tables, where records are viewed as rows in tables (aka relations).

# Sequential files can be viewed as MS-DOS text files. These are useful for storing report files, and are still in existence on some mainframe systems for storing primary data.

A concern today is using and maintaining files on networks. This often involves having exclusive control of a record or file during an update operation (such as changing address information) and we accomplish this by record or file locking.

4.2 Defining Indexed Files with COBOL

To define an indexed file requires a Select entry in the Input-Output Section, an FD entry in the File Section and a special status field defined in the Working-Storage Section. This shows the general form, with different options available:

Environment Division.

Input-Output Section.

File-Control.

Select FD-name assign external-name

organization indexed

access {one of random, dynamic, sequential}

record key primary-key-name

alternate record key key-name2 [optional]

{with duplicates} [optional]

status file-status.

Data Division.

File Section.

FD FD-name.

1 FD-record.

5 primary-key-name ....

5 key-name2 ...

...

Working-Storage Section.

1 file-status Pic XX.

Now we can see the difference between File-Control and the File Section. File-Control is in the Input-Output Section of the Environment Division and is where internal file names (FD-names) are associated with external file names. The File Section is in the Data Division and is where a typical record is specified for each file previously listed in a Select entry of the Input-Output Section. Usually each field is also listed, with some exceptions.

The file is defined to the MS-DOS operating system when a COBOL add program is run and the file is opened in an appropriate manner. On many systems, utilities can also be used to define a file. One of these is included in Appendix D. Some systems require that you use a utility to define a file before you can use it in any application program. Consult your system documentation if an add program does not create the file for you.

The following example (parts.env) from the parts inventory system is referred to in the next sections:

SELECT Parts-File ASSIGN "parts.dat"

organization indexed

access dynamic

record key PD-Item-Number

alternate key PD-Item-Description

status parts-status.

4.2.1 Organization

The organization of a file is the way we define the file to the operating system and determines which range of COBOL commands we can use with the file. You must specify organization indexed for indexed files. The other common organization is sequential, discussed in section 4.4. Don't confuse organization sequential with access sequential, covered next.

4.2.2 Access Mode

Access refers to mode of access for indexed files, and the mode determines which commands we can use in a COBOL program to access an indexed file. There are three possible ways to access indexed files in COBOL. If you only desire to read through the entire file from beginning to end, access sequential is sufficient. If you want to read individual records based on the index or search key, access random is needed. If you want to have the option of doing both sequential and random accesses in the same program, choose dynamic \-- this allows for both methods. In parts.env, I chose access dynamic which allows all file processing commands to be used with the parts.dat indexed file.

4.2.3 Record Key

A record key is a unique field or group associated with each record of the indexed file. There is only one record key, often referred to as the primary key, associated with each record in a file (although there may be several alternate record keys). Because the record key entry is unique, it serves as a search key to locate records in the file. The primary-key-name need not be placed at the beginning of the record description, although this is usually the case. The primary key must be specified when the file is defined to the operating system.

# Examples of primary keys include employee number, social security number and part number.

This is the complete FD entry for parts.dat, including the record description parts.fs, which is referenced in each of the parts inventory programs.

*********************************************************

* Parts Record Description

* (parts.fs)

* Record Length: 46 bytes

* Record Key : PD-Item-Number

*********************************************************

FD Parts-File.

1 Parts-Description.

5 PD-Item-Number Pic x(8).

5 PD-Item-Description Pic x(26).

5 PD-Unit-of-Measure Pic xx.

88 Valid-UOM values "EA" "BX".

5 PD-Unit-Cost Pic 9(4)v99.

5 PD-Location Pic x(4).

In this example, the primary record key PD-Item-Number is listed as the first field in the record. Notice the comment lines used to clearly identify this code as being the parts record description and to identify the record length and record key name. Also notice that the v used to describe PD-Unit-Cost is an implied decimal point which does not figure into the record length. (The 88 is covered in chapter 6.)

4.2.4 Alternate Record Key

An optional alternate record key, key-name2 in the general case above, can also be used to search the file. An alternate key may or may not have duplicates, depending on the system design. You must specify the alternate key(s) when the file is first defined to the operating system. Your select entry must always specify every alternate key in each program where the file is referenced, regardless of whether the alternate key is used in that program. This provides one incentive for keeping the select entry as a separate file and copying it to each program in the system.

In parts.fs, the alternate record key is PD-Item-Description and no duplicates are allowed. An example of an alternate key with duplicates allowed, would be last name. For instance,

SELECT Student-File ASSIGN "student.dat"

organization indexed

access dynamic

record key SF-Student-Number

alternate key SF-Student-Last-Name

with duplicates

status student-status.

4.2.5 Status

The file-status parameter must be defined in the Working-Storage Section as two characters or bytes. Its purpose is to inform the program user of any problems that may occur with the indexed file during processing. The following values are automatically generated by some systems and placed in the file-status field under the proper conditions:

Status Code Meaning

00 Status Okay, Operation Successful

10 End of File

22 Record Key Already Exists (write failed)

23 Record Key Not Found (read failed)

# {Different systems also provide special error messages when the first byte is a nine. Refer to your system's documentation for more information on system-specific error messages.}

4.2.6 Assign

Assign is used to associate the external file name with an internal name, which is in turn referenced in an FD entry in the File Section. The external name will also have an entry in the MS-DOS File Allocation Table (FAT). An indexed file actually has two files associated with it. One file contains the data itself, usually given the extension .dat. The other file is the index, which is automatically given the extension .idx.

The external name can be defined statically or dynamically. This applies to both sequential and indexed files. To define the external file name statically, simply have the MS-DOS drive, directory and file name in quotation marks,

Select Personnel-File Assign "c:\patha\persfile.dat"

# If the file resides or will reside on the current drive and in the current directory, then it is not necessary to specify the drive or directory. This is how the parts system is handled and it offers the greatest flexibility because the user can define their own directory and run the program off any drive.

SELECT Parts-File ASSIGN "parts.dat"

The advantage of dynamically naming a file is that the user can assign names each time the program is run. This is useful in situations where a program creates files on a regular basis and the user would like to control the names so as not to erase files still needed from previous runs. To define an external file name dynamically, the first part of the select entry looks like this:

SELECT FILE-in ASSIGN input-file-name

# OR

SELECT FILE-out ASSIGN output-file-name

In this example, input-file-name and output-file-name must be declared in the Working-Storage Section and the accept statement must be used in the Procedure Division to make the connection. The index component (.idx) is referenced automatically as you work with the indexed file.

data division.

file section.

FD File-in.

1 in-rec pic x(80).

FD File-out.

1 out-rec.

3 filler pic x(7).

3 rest-rec pic x(80).

working-storage section.

1 input-file-name pic x(8).

1 output-file-name pic x(8).

1 end-flag pic 9 value 0.

procedure division.

Display "Please enter the input file name: "

accept input-file-name

Display "Please enter the output file name: "

accept output-file-name

4.3 Using Indexed Files with COBOL

To use an indexed file, you first open it as input, i-o or output. An existing file is opened as input if you only want to read from it, while a file to be created is opened as output if you only want to write to it. If you want to read from and write to a file, it must be opened as i-o.

Open i-o FD-name1 input FD-name2 output FD-name3

# OR

Open input input-file-name

output output-file-name

OR

Open i-o Parts-File

When you are done with the file, you should close it.

Close FD-name1 FD-name2 FD-name3

# OR

Close input-file-name output-file-name

# OR

Close Parts-File

There are seven other operations you can perform on an indexed file. These are all done with regard to individual records in the file. Some have to be done in unison with others and in a particular order to work properly,

# Handling Errors

# Read using a specific key

# Start (preceding sequential read)

# Read sequentially

# Write

# Rewrite (preceded by read)

# Delete (preceded by read)

4.3.1 Handling Errors

Handling errors is one aspect of controls in a system. Error handling for indexed files is done in one of three ways in COBOL. One is by using an invalid key clause which will be illustrated as each command is discussed. Another only applies to the sequential read -- an end clause triggered when the end of the file is reached. This is discussed with the sequential read command. The third method involves using a generic error routine called the Declaratives at the beginning of the Procedure Division, described here, which would apply to each command in place of numerous invalid key clauses.

Procedure Division.

Declaratives.

For-I-O-Error Section.

Use after error procedure on FD-Name1.

Error-handler.

Display "Error in data file"

Display "File status = " file-status

Display "Data record = " FD-record1.

End Declaratives.

Standard-Processing Section.

This generic error routine is not required, merely an available option. Since this must be the first routine in the Procedure Division (if used), using a header name followed by the reserved word section is required right after the word Declaratives, and also after the words End Declaratives. The words Use after error procedure on are COBOL reserved words which let you inform the system which file or files are to be associated with the Declaratives. The contents and specific processing of the error-handling routine itself is up to each individual programmer and the particular needs of the program or system. You could still use an invalid key clause with any command to override this error section as desired.

4.3.2 Read using a specific key

Given a particular valid key value, this keyed read will retrieve a single record in preparation for extracting information, modifying or deleting the record. The KEY clause may reference a primary key or an alternate key, depending on the situation:

Check-search-key.

Move 0 to process-flag

READ Parts-File

KEY PD-Item-Number

invalid key

Move 0837 to Cursor-position

Move 2 to process-flag

end-read.

In the preceding example, the invalid key clause is also shown. If the read is unsuccessful, then the processing commands after the words invalid key will take place. Indentation is used to highlight the fact that the two statements are only executed if and when the key is invalid.

If you wanted the Declaratives to handle error processing instead, the keyed read could be simplified as follows,

Check-search-key.

# Move 0 to process-flag

READ Parts-File

KEY PD-Item-Number

# end-read.

Another possibility is when the expectation is that a record does not exist, and therefore the error condition is when the record does exist. This could occur in an add program when you want to ensure that a record key does not exist as part of a validation routine. You simply use NOT before invalid key:

Edit-Record.

## Move 0 to error-flag

## ...

* save the data while you read

Move Parts-Description to hold-rec

READ Parts-File

KEY PD-Item-Number

## NOT invalid key

* if record already on file, say so

Move 0837 to cursor-position

Move 2 to error-flag

Move 'Record rejected, duplicate record' to

Status-Message

* restore if data was retrieved

## Move hold-rec to Parts-Description

## end-read

## ...

ER-exit. exit.

4.3.3 Start (preceding sequential read)

The start command is used to position the file at a particular record key prior to commencing a sequential read of an indexed file when you specify access dynamic, when you want to start at other than the beginning of the file, or when you want to use an alternate key for your processing.

Start Parts-File

KEY not < PD-Item-Number

end-start.

The result of this operation is to position an internal pointer just before the record whose key value is contained in PD-Item-Number, which must be a record key name (primary or alternate). Be certain the key value being used has an appropriate value in it. In this case the value comes from the screen. The sequential read, usually inside a loop, would then begin reading the file in order beginning with the record whose key value equalled PD-Item-Number.

If your requirement is solely to read from the beginning to the end of an indexed file using the primary key, you can avoid the use of start by specifying access sequential for the indexed file and using the read command as if the file were a sequential file.

4.3.4 Read sequentially

After a start has been done, the following sequential read would be used:

* read the next record in sequence

Read Parts-File next

* after last record has been processed, signal end of file

end Move eof-message to screen-message

## Move spaces to parts-description

## Move high-values to PD-Item-Number

## end-read.

The end clause could contain any appropriate COBOL command or set of commands, and specifies what should occur after the last record has been processed.

If you specify access sequential for the indexed file, and want to read based on the primary key sequence, the following command can be used without any start operation:

* read the next record in sequence

Read Parts-File

* after last record has been processed, signal end of file

end Move eof-message to screen-message

## Move spaces to parts-description

## Move high-values to PD-Item-Number

## end-read.

The only difference is the absence of the word next. This is the same as using the read command for a sequential file. (high-values is discussed in chapter 9.)

4.3.5 Write

Use the write command to add a new record to an indexed file. You provide the key and all the new data, the record is added to the data component, and the key is automatically inserted in the indexed component (.idx file) in the proper sequence.

* Note \- Write always refers to the FD's record name

Write parts-description

invalid key

move 0837 to Cursor-position

move 2 to Error-flag

move "File Error" to SM-Information

move parts-status to SM-Status-Code

move Status-Message to Screen-Message

NOT invalid key

perform set-up-new-display thru sund-exit

move Message2 to Screen-Message

end-write

Here, both invalid key and NOT invalid key are used. The invalid key part is accessed when there is a problem writing the record to the file and an appropriate error message is prepared. The NOT invalid key part is accessed when there is no problem.

4.3.6 Rewrite (preceded by Read)

Rewrite is used to change records in indexed files. You first read the record (usually a keyed read) to retrieve the original information, then specify what the new data is. The changes along with the original information are placed into the existing record. The file must be opened as i-o.

* Note \- Rewrite always refers to the FD's record name

Modify-Record.

Rewrite parts-description

INVALID KEY

Move 0101 to Cursor-position

Move 6 to process-flag

Move "File Error" to SM-Information

Move parts-status to SM-Status-Code

Move Status-Message to Screen-Message

end-rewrite.

CAUTION: It is not a good idea to attempt to change key fields using rewrite. If you must change key fields, first delete the original record (see below) then add a new record with the original data but a different key field.

4.3.7 Delete (preceded by read)

Use delete to remove an indexed record. You generally first read the record to verify its existence and to show the data to the user so they can confirm the operation. The key is removed from the indexed component (.idx file), while the data remains intact but unreachable. The following command will remove the reference to the key for the current record:

Delete Parts-File

# At some point, indexed files must be reorganized or rebuilt in order to remove the unreachable records. There are various utilities to handle this, and the subject is beyond the scope of this text.

NOTE: The FD name is always used with the read, start and delete commands, while the FD's record name is always used with the write and rewrite commands.

4.4 Defining Sequential Files with

COBOL

To define a sequential file requires a simple select entry in the Environment Division,

select address-file assign "address.dat" organization line sequential.

* "PRN" refers to the printer

select labels-file assign "PRN" organization line sequential.

select states-file assign "states.dat" organization line sequential.

and a standard FD entry in the Data Division,

FD address-file.

1 address-record.

5 ar-last-name pic x(20).

5 ar-first-name pic x(10).

5 ar-street-address pic x(25).

5 ar-city pic x(12).

5 ar-state pic xx.

5 ar-zip pic x(10).

FD labels-file.

1 a-line pic x(80).

FD states-file.

1 states-record.

5 sr-state-id pic xx.

5 sr-state-desc pic x(20).

Assign works the same as for indexed files, and is used to associate the external file name with an internal name. The preferred sequential file organization for the Micro Focus environment is line sequential, which is the same as ordinary text. If another type of sequential file organization is required, please refer to your system's manuals for further information. (The external file name can be defined statically or dynamically, as was discussed in section 4.2.6.)

4.5 Using Sequential Files with

COBOL

To use a sequential file, first open it as input or output. An existing file is opened as input, while a file to be created is opened as output. Opening a file as output erases or destroys any previously existing file with the same name.

open input address-file

states-file

output labels-file.

When you are done with the file, close it.

close address-file states-file labels-file.

Other commands available to sequential files are read and write. You can also use end-read instead of a period. An end clause is available that may contain any appropriate COBOL command or set of commands, and specifies what should occur after the last record has been processed. (The invalid key clause does not apply to sequential files.)

read address-file

end move 1 to exit-flag

end-read

read states-file

end move 1 to end-of-file.

write a-line from label-line-1 after 5

write a-line from label-line-2 after 1

write a-line from label-line-3 after 1

Writing to a sequential file sometimes means creating a report. The write command itself adds a record to the sequential file. When creating a report, there are a few options available. The option from is similar to move. With from, however, the contents of the data element to the right of the word from are copied to the data element to the left of the word from. The option after number causes blank lines to appear, depending on the number used. Specifying after 5 would cause 4 blank lines to appear. Using after 1 would cause no blank lines to appear, but does prevent the next line from being printed on top of the previous one. After page is another option which causes a page break character to be inserted in the file. If after is omitted completely, records are added one after another, as if single-spaced.

Another and oftentimes better way of creating reports is by using the Report Section. This topic is covered in chapter 7.

There is no index component for sequential files, as there is for indexed files. To do any updating with sequential files, the inputs must first be sorted and a new file created containing all the new and changed records. This topic of sequential file maintenance is covered in detail in chapter 9.

4.6 Defining Files for Network Use

When a file is to be stored on a shared drive and accessed by many users in a network environment, it may be appropriate to provide exclusive use of either particular records or the entire file to users, especially when records are to be modified by a program. This is accomplished in the Micro Focus environment by locking records or files. Other environments provide for locking, but the mechanics may differ from the discussion here. If you're using a system other than Micro Focus, refer to your system's manuals for further information related to record and file locking.

Every COBOL program accessing a shared file resource should examine the status field to determine if a record is locked or if the file is locked, even if that program is not doing any locking itself. A locked record in Micro Focus would return a 9 as the first byte and 68 as the second byte of the status field. A locked file in Micro Focus would return a 9 as the first byte and 65 as the second byte of the status field. (See the discussion of special status codes in Section 4.6.3.)

4.6.1 Locking Files

For a file stored on a shared drive in a network environment, if you do not specify any lock mode in the select entry then the entire file is locked and no other programs can access it when the file is opened as i-o or output. When a file is opened as input, you must include a lock mode exclusive clause to prevent any other programs from accessing it:

Select FD-name Assign "c:\patha\persfile.dat"

# Organization indexed

# Access dynamic

# Record Key PR-key

# Status file-status

lock mode exclusive.

Rarely would you want to lock an entire file. Situations where it would be appropriate to lock the entire file are when the file is strictly an output file, or it is being converted to a new format, or it is being provided a new set of values for a particular field or fields all at one time.

# The alternative to locking the entire file is to lock individual records.

4.6.2 Locking Records

The advantage of locking individual records is that other users can access the file while you are using it. There is no problem as long as they don't want to see the particular record your program is making changes to at that same exact point in time. This is the preferred method for providing exclusive control, unless there is a special reason for locking the entire file as mentioned above. The discussion here is limited to locking single records. Locking multiple records is also possible, and a discussion of that is covered in the Micro Focus PC Programmer's Guide.

There are two methods of locking single records, manually and automatically. Consider the following select entry:

Select FD-name Assign "c:\patha\persfile.dat"

# Organization indexed

# Access dynamic

# Record Key PR-key

# Status file-status

lock mode {one of automatic, manual }.

In the Procedure Division, we must open the file as i-o in order for record locking to work.

With automatic record locking, every time we read a record, the record becomes unavailable to other users in the system. The record becomes available again when a rewrite, write or delete is performed on the record or another read is executed in the program.

With manual record locking, a with lock clause must be included with the read command in order to make the record unavailable to other users,

Move SSN-input to PR-key

Read FD-Name with lock

key PR-key

# end-read

The record becomes available again when a rewrite, write or delete is performed on the record or another read is executed in the program. The advantage of manual locking is that one section of the program can read records without using a lock, perhaps to display data, while another section may read the record just prior to making a change and impose the lock only in that situation.

4.6.3 Special Status Codes

Micro Focus provides special error codes when the first character is a 9 and for other values as well, using a binary field (comp-x) to redefine the second character as capable of representing a special numeric field. (These codes are further described in the Micro Focus PC Programmer's Guide and COBOL System Reference.) For example, a locked record in Micro Focus would return 9 as the first byte and 68 as the second byte. The status field could be defined and then checked in the following manner in order to display an appropriate message for the user,

Working-Storage Section

1 file-status Pic XX.

1 MF-file-status redefines file-status.

3 MF-file-status-byte-1 Pic X.

3 MF-file-status-binary Pic 99 comp-x.

Procedure Division

If MF-file-status-byte-1 = "9"

## perform check-second-status-byte

end-if

{In COBOL, redefines allows you to use the same memory area while assigning different names and data types to it.}

The comp-x field is a special way of defining a number. It takes an 8-bit byte and divides it into two 4-bit parts. With 4 bits in binary you can specify the numbers 0 through 15, so you represent a number such as 68 quite easily using 8 bits. The number 6 in binary is 0110 and the number 8 in binary is 1000.

The if statement is covered in detail in chapter 6. Here, it is saying that if the first character is a 9, perform the named routine.

4.7 Chapter Summary

In this chapter we've considered both indexed and sequential files. The indexed file concept is the basis for most databases today, while sequential files provide us a means of storing reports or backups of data for archive purposes.

External file names must be provided. These can be defined statically or dynamically. Dynamic file naming offers some flexibility in where an input or output file can be, or what name the file can have for new files being created. Static file naming requires a specific name at compile time, which may include a specific path. (The select entry may have different requirements for the external file name for different systems. Please consult your system's manuals if you need specific information only applicable to your system.)

COBOL indexed files are identified by providing the external file name, stating that the organization is indexed and specifying the record key(s), the file status variable name and the access mode. Random access mode allows for access by specific keys, while sequential access mode allows for sequential access only. Dynamic access mode is the most comprehensive, allowing both keyed and sequential access. If an indexed file is to be stored on a shared network drive, it should also have a lock mode specified, either manual or automatic. If no lock mode is specified, then the entire file is locked when the file is opened as i-o or output.

Commands available to indexed files opened as input are start and read. Commands available to indexed files opened as i-o are start, read, write, rewrite and delete. The command available to indexed files opened as output is write.

Sequential files are identified by providing the external file name and stating the organization to be line sequential. Read and write are the commands available to sequential files.

Error-handling can be accomplished with a Declaratives routine, by using invalid key clauses, by using end clauses, or by combinations of the three.

4.8 Review Questions

1. What is to be input and output in our lives as born-again Christians?

2. Give an example of a record. Give an

example of a field.

3. Which Division must the status field be

# defined in?

4. What is the difference between File-

Control and File Section?

5. Identify two ways of creating an indexed

# file.

6. What is the difference between organiza-

tion sequential and access sequential?

7. List the three available access modes for

# an indexed file. Which mode is most

# comprehensive?

8. What is the difference between a primary

# key and an alternate key?

9. How many primary keys can you have for

# a file?

# 10. What is the meaning of status codes 22 and

# 23?

# 11. List two ways of assigning external file

# names with internal names.

# 12. List three ways of handling errors for

# indexed files.

13. What is the difference between the keyed

read and the sequential read?

14. What does the start command do? What

# command must it precede?

15. What is the purpose of the write, rewrite

and delete commands?

16. Can you use rewrite and delete with a

# sequential file?

17. Write a select entry that will cause output

# to go directly to the printer.

18. What does the after page option accomplish?

# 19. Write a complete select entry for a

# sequential file that will be opened as

input which will prevent any other

# programs from accessing the file when

the program is being run.

20. Write a keyed read statement for a file

# using manual record locking.

# Answers to even-numbered review questions.

2. employee record; employee ID

4. The File-Control is in the Input-Output Section of the Environment Division

and is where internal file names (FD-names) are associated with external file

names. The File Section in the Data Division is where a typical record is

specified for each file previously listed in a Select entry of the Environment

Division.

6. Organization sequential refers to a file defined as a sequential file. Access

sequential is one of three modes of access for indexed files.

8. An alternate key can have duplicates and is optional. A primary key must be

unique and is required.

10. A status code of 22 means a write has been attempted to create a new record

key, but the record key already exists. A status code of 23 means that a read

has been attempted, but the record key does not exist.

12. Error-handling can be accomplished with a Declaratives routine, by using

invalid key clauses, by using end clauses, or by combinations of the three.

14. The start command is a positioning command, to enable you to start processing

at a particular record key. It must precede a sequential read for an indexed file

when access is specified as dynamic.

### 16. No.

18. After page inserts a page break character in the output file.

### 20. Move SSN-input to PR-key

Read FD-Name with lock

key PR-key

### end-read

4.9 Projects

# 1. Design an algorithm to create 2-up labels.

# (See project 1 of chapter 2)

# 2. Write a program to create 2-up labels using

sequential files. Do not reference the

states.dat file, but use the state abbreviation in the labels output. This involves ignoring any reference to tables, including set and

search in labels.pro, the COPY files states.ws, load-sta.pro and any references to these in other parts of the program.

# 3. Write a complete program which dynamical- ly names a sequential output file on drive B: or C: based on the user's choice. Have the program write a single record to the file containing the current date along with the message

"This is the day which the Lord has made".

# 4. Write a very simple program which inserts a page break character in a sequential output file. Write a verse of Scripture to the file as you are inserting the page break character. Using a text editor, examine the file you

created and draw the symbol used for the page break character.

5. Write a simple program to create an indexed file using the address.dat file as input. Use a Declaratives routine to handle errors.

6. Write a program to read the states.dat file and create an indexed version of this file. Do not use a Declaratives routine to handle errors.

# 7. Write an interactive program to display the state name whenever the state abbreviation is entered, where the states are contained in an indexed file.

Do not include a menu. HINT: Start with parts-02.cbl and make changes as needed. Either write a program to create the indexed file from states.dat or use a utility available on your system.

# 8. Write a program to create 2-up labels. Reference an indexed version of the

states.dat file. This involves ignoring any reference to tables, including set and search in labels.pro, the COPY files states.ws, load-sta.pro and any references to these in other parts of the program.

CHAPTER FIVE

Return to contents

Arithmetic

# Leviticus 27:23

# "then the priest shall calculate for him the amount of

your valuation up to the year of jubilee; and he shall

# on that day give your valuation as holy to the LORD."

# Luke 14:28

# "For which one of you, when he wants to build a

tower, does not first sit down and calculate the cost,

to see if he has enough to complete it?"

5.1 The Importance of Arithmetic

# In ancient times, a slave was worth 30 pieces of silver. This was the price Judas received for betraying our Lord and Savior Jesus Christ. But Judas failed to count the cost, and in so doing (unless he repented) is doomed to an eternity in a burning lake of fire. He failed to recognize the importance of arithmetic. He did not calculate the sum of his mistakes, his sins became multiplied, his inheritance may be divided among all those who turn their backs on God, and he has been subtracted from the number of the apostles (Acts 1:17).

# Since the beginning of commerce, calculation has been an integral part of our very existence. Businesses use electronic accounting systems routinely today. As Christians we are to count the cost, be good stewards, etc. A lot of contemporary fiction has highlighted the idea of the computer at work to assist Satan in economically controlling the world. Revelation 13:17-18 states that no one will be able to buy or sell without a special mark which is "the name of the beast or the number of his name." Revelation 13:18 states "Let him who has understanding calculate the number of the beast, for the number is that of a man; and his number is six hundred and sixty-six." This lends itself to the idea that computers will somehow be used to force everyone into an accounting system controlled by Satan and his cohorts.

# It is possible, though not likely, that something we do for good in our programming of calculations into the computer will be used for evil purposes. That should certainly not be our goal however, but our goal should be to honor God in all that we say and do. As long as we are faithful witnesses for Christ He will be faithful to us.

5.2 Arithmetic Objects

There are a number of entities which can be considered as arithmetic objects, each with a defined purpose or function. The counter is one of the simplest arithmetic objects, used even in Bible times with manual systems. COBOL examples might be

1 Check-count pic 9(5) value zeros.

1 Input-count pic 9(5) value zeros.

The purpose of the counter is to keep track of the number of records in order to provide a reference to check for errors at various points in the system. Counters should be set to zero before being used. In a payroll system, the employee list can provide a count of all the employees. When the payroll check register is printed, another count can be calculated. If these two numbers differ, it may indicate a problem in the system. This example shows how feedback from different components of the same system can provide visible controls to help check for errors.

Calculated objects are those which are based on a calculation involving two or more numeric data elements. Examples include gross pay, net pay, due dates and grade point averages.

1 Payroll-Record....

5 PR-gross-pay pic 9(8)v99.

5 PR-net-pay pic S9(7)v99.

1 julian-due-date.

3 jdd-due-year pic 99.

3 jdd-total-days pic 9(3).

1 WS-GPA pic 9v99 value zeros.

# A calculated object is produced by inputs provided by the user and possibly data existing in other files in conjunction with arithmetic operators. The new object may or may not be stored in a file.

The v symbol in a COBOL data declaration is an implied decimal point. It marks the position of the decimal point to a program, but does not take any space in the file. If an implied decimal point is not specified correctly or is left off when it should be included, the program will consider the decimal point to be the rightmost position of the numeric field and many informational errors can occur as a result. A field with an implied decimal point is used in calculations and must be moved to a field with a physical decimal point if it is to be presented to the user.

Extended figures are also calculated figures based on two or more numeric data elements defined within a system, such as

5 extended-cost pic 9(9)v99 value 0.

5 extended-sales pic S9(9)v99 value 0.

# Extended cost is the cost per unit of an item multiplied by the number of units manufactured or purchased. Extended sales is the retail price per unit multiplied by the number of units sold. Units might be measured in terms of a single item, a box of items, or some other quantity appropriate for the item. The advantage of an extended figure is that it doesn't take up space in a file, it's merely calculated each time for a report, display or some other program.

The S symbol in a data declaration stands for sign and means that the number can be negative. When could sales be negative? The S doesn't take up space in the file, but shares space with the rightmost digit. When printed, the last digit appears as a letter. A signed field must be moved to a field described with a physical sign to be easily interpreted. This is discussed in more detail in chapter 7.

The accumulator keeps track of running totals of fields or calculated objects. Accumulators should be set to zero before being used. There is accumulated cost, accumulated net sales, accumulated payroll medicare deductions, etc.

Related to the accumulator are the subtotal, total and grand total. The subtotal is an accumulated figure for a particular group such as store, salesperson or branch. A total is the sum of subtotals. A grand total is a collection of totals. In many instances the grand total and total are equivalent. One specific example where all three are used is a payroll system where each employee has a subtotal representing their labor hours by cost center, each cost center has a total, and the cost center totals are part of the grand total for the organization. Totals also provide a mechanism for feedback and control within a system.

5.3 Arithmetic Operations

# The operations available in COBOL are addition, subtraction, multiplication, division and exponentiation. The commands used to carry out these operations are

# add

# subtract

# multiply

# divide

# compute

5.3.1 The Add Command

There are three ways to accomplish 2 + 2 in COBOL. One is with the compute command discussed later in this chapter. One is with the set command discussed in chapter 8. The other is with the add command. There are two forms of the add command available. One is this:

add cd-Number-Credits to accum-credits

add 1 to line-counter

This form adds the value of the first data element to the second. The first remains unchanged and may even be a numeric constant. The second is increased by the value of the first, not replaced, so be sure to properly initialize all result fields. If the result field is not started at zero, you will get unpredictable results.

# It is possible to have more than one result field, if needed, as in this example,

add PR-current-employee-FICA to WS-Quarter-to-Date-employee-FICA

## WS-Year-to-Date-FICA

# The other form of the add command is this:

add work-day days-in-year-to-date

giving total-days.

add 1 days-in-year-to-date

giving tomorrow.

# This form adds the value of the first and second data element resulting in the third. The first and second remain unchanged. There is no need to initialize the result field since it is calculated each time. There may be more than two operands as shown here:

add PR-employee-taxes PR-employee-life PR-employee-pension

giving WS-employee-deductions

# The add command has an option to allow for rounding of results, if called for in the system design:

add PR-employee-taxes PR-employee-life PR-employee-pension

giving WS-employee-deductions rounded

# It is important that you define result fields to be large enough to handle the largest sum of numbers, and to test the sizes adequately. For instance, if you are accumulating all accounts payable figures into a total accounts payable figure, consider the size of the field being added, and multiply by the expected maximum number of accounts payable records. If the accounts payable amount were defined as 9(5)v99 and no more than 3,000 records were expected per month, then the total field should be defined as 99,999 times 3,000 = 299,997,000 or 9(9)v99. For a year, there would be 36,000 records expected requiring a size for the total field of 9(10)v99. To ensure more than enough digits for the year, multiply 99,999 times 99,999, yielding the same size field in this case.

# There is a COBOL option to check for overflow with arithmetic commands, which is especially suitable for the software testing phase. However, by carefully analyzing each situation and applying the appropriate rule for setting the result field size, overflow cannot occur, and the overflow option may become unnecessary.

5.3.2 The Subtract Command

There are three ways to accomplish 2 - 2 in COBOL. One is with the compute command discussed later in this chapter. One is with the set command discussed in chapter 8. The other is with the subtract command. There are two forms of the command available. One is this:

subtract cd-Number-Credits from accum-credits

subtract 1 from days-left

# This form subtracts the value of the first data element from the second. The first remains unchanged and may even be a numeric constant. The second is decreased by the value of the first, not replaced.

# The other form of the subtract command is this:

subtract PR-time-off-without-pay from PR-hours-worked

giving WS-hours-worked

# This subtracts the value of the first from the second data element resulting in the third. The first and second remain unchanged in this example.

# It is possible to have more complex statements, if needed:

subtract PR-employee-taxes PR-employee-life PR-employee-pension

from PR-gross-pay

giving PR-net-pay

# The subtract command has an option to allow for rounding of results, if called for in the system design:

subtract PR-time-off-without-pay from PR-hours-worked

giving WS-hours-worked rounded

# It is important to define subtraction result fields with a sign in order to handle the possibility of a negative number. The size of the result field should at least match the larger of the operands.

5.3.3 The Multiply Command

There are two ways to accomplish 2 * 2 in COBOL. One is with the compute command discussed later in this chapter. The other is with the multiply command. There are two forms of the multiply command available. One is this:

multiply cd-Number-Credits by number-grade

giving course-points

# This multiplies the value of the first data element by the second resulting in the third. The first and second remain unchanged. There is no need to initialize the result field since it is calculated each time. Result fields should have a sign if one of the operands has a sign.

# The other form of the multiply command is this

multiply bonus-factor by weekly-salary

multiply 2 by weekly-salary

The first data element remains unchanged and may even be a numeric constant. The second is used in the calculation and also stores the result. This form is opposite to the way we are used to thinking and operating.

# The multiply command has an option to allow for rounding of results, if called for in the system design:

multiply cd-Number-Credits by number-grade

giving course-points rounded

multiply PR-hourly-rate by PR-hours-worked

giving PR-gross-pay rounded

# It's important to define result fields to be large enough to handle the largest result, and to test the sizes adequately. For instance,

1 Course-Description-Record.

# ...

5 CD-Number-Credits pic 9.

1 number-grade pic 9 value 0.

1 course-points pic 99 value 0.

# Here the two operands are each one digit. The largest result would be 9 times 9 or 81 which is pic 99. As another example,

1 Payroll-Record.

# ...

5 PR-hourly-rate pic 99v99.

5 PR-hours-worked pic 9(4)v9.

5 PR-gross-pay pic 9(8)v99.

# The largest result to the left of the decimal would be 99 times 9,999 or pic 9(6), so 9(8) is more than adequate. The decimal portion would be v99 times v9 or pic v999. Since rounding is being used and we are dealing with dollars and cents here, v99 is sufficient.

5.3.4 The Divide Command

There are two ways to accomplish division in COBOL. One is with the compute command discussed in the next section. The other is with the divide command. There is one good way to use the divide command,

divide class-total by class-size giving class-average

divide yearly-total by 12 giving monthly-total

This form divides the value of the first data element by the second resulting in the third. The first and second remain unchanged and the second may even be a numeric constant. It is important to define division result fields with a sign if one of the operands has a sign. The size of the result field should at least match the larger of the operands.

# There is a remainder option which proves useful in certain applications,

divide work-year by 4 giving quotient

remainder leap-year-indicator.

# The divide command has an option to allow for rounding of results, if called for in the system design:

divide class-total by class-size

giving class-average rounded

5.3.5 The Compute Command

As has been mentioned in the previous sections, the compute command can be used to perform all of the other arithmetic operations plus exponentiation. It is not generally used in simple cases because of potential extra processing time involved. The operators used with the compute command include

operator function

# \+ addition

# \- subtraction

# * multiplication

# / division

# ** exponentiation

# The basic form of the compute command is

Compute WS-GPA rounded = accum-course-points / accum-credits

The word rounded is optional. Parentheses may be used as needed according to standard rules of arithmetic. The advantage of the compute command is that it allows very complex formulas to be represented. The need for a complex formula rarely occurs in COBOL, but the compute command is available to meet that need.

# The compute command can be used routinely in place of any of the other commands, as in these examples:

compute WS-employee-deductions rounded = PR-employee-taxes +

PR-employee-life +

## PR-employee-pension

compute PR-net-pay = PR-gross-pay -

## (PR-employee-taxes + PR-employee-life + PR-employee-pension)

compute course-points rounded = CD-Number-Credits * number-grade

5.4 Chapter Summary

The counter is one of the simplest arithmetic objects, having been used since ancient times with manual systems. Accumulators keep track of running totals. Both should be set to zero before being used and both provide a mechanism for feedback and control within a system. Calculated objects are those which are based on a calculation involving two or more numeric data elements.

Two syntactical characters used in a COBOL data declaration and introduced in this chapter were the implied decimal point symbol v, and the symbol S which represents a sign that shares room with the rightmost digit. Both of these are important in order to represent numbers correctly, yet neither can be easily interpreted without having the associated fields moved to output fields with physical decimal points and signs, as we shall see in chapter 7.

There are five basic arithmetic commands used in COBOL: add, subtract, multiply, divide and compute. The syntax of these commands is quite precise, yet straightforward. It is critical to provide the correct size for result fields. The compute command can be used in place of all the other commands, if you prefer, as long as the system response time does not degrade substantially.

# Today electronic spreadsheets and personal computer database management systems can perform calculations with lower development cost in certain cases than a COBOL program. As God's stewards, we must be able to discern which processing method is going to be more efficient for any given enterprise by counting the cost as part of our analysis. If large volumes of data and a good deal of complicated processing are involved, a spreadsheet or personal computer DBMS generally may not work as well as a COBOL program.

5.5 Review Questions

1. Discover a Bible verse not referred to in

# the text that is related to arithmetic,

actually or philosophically.

2. How might totals provide a mechanism for

feedback and control within a system?

3. Why would sales ever be negative?

4. Provide an example of a counter you

# encounter routinely.

5. Provide an example of a calculated object

not mentioned in the text.

6. Give an example of an accumulator from

# everyday life.

7. What sorts of errors could occur if fields

with the implied decimal point were

# displayed or printed?

8. How does the S sign share room with a

# digit?

9. What is potentially wrong with these code

# segments?

5 PR-hourly-rate pic 99v99 value 65.25.

5 PR-hours-worked pic 9(4)v9 value 165.5.

5 PR-gross-pay pic 9(4)v99.

multiply PR-hourly-rate by PR-hours-worked

giving PR-gross-pay rounded

# 10. What is potentially wrong with these code segments?

1 CD-Number-Credits pic 9 value 5.

1 number-grade pic 9 value 4.

1 course-points pic 9.

compute course-points rounded =

# CD-Number-Credits * number-grade

# 11. What is wrong with this code segment?

add work-day to days-in-year-to-date

giving total-days.

# 12. What is wrong with this code segment?

multiply cd-Number-Credits number-grade

giving course-points

# 13. What is wrong with this code segment?

divide yearly-total by 12 = monthly-total

# Answers to even-numbered review questions.

2. Totals are used to verify that data has not been lost from point A to point B,

similar to the use of counters. Totals also help indicate to management whether

an activity is profitable and what the areas of weakness might be. They can be

used to highlight excesses and inefficiencies as well.

4. odometer; clock; answers may vary

6. bank account balance; student expenses balance; answers may vary

8. Since a digit only needs 4 bits to be represented (from chapter 4), the other 4

bits can store the sign. The entire 8 bits print as a letter of the alphabet for

negative numbers. Since it is correctly stored in a numeric field, the computer

will perform all arithmetic correctly.

### 10. The size of course-points is too small. In this case, the result would be 0 instead

of 20.

12. The word by is missing.

5.6 Projects

# 1. Design and implement a useful program

# which uses the compute statement.

# 2. Design a timer program which counts off

# until at least five minutes have elapsed, then

# displays the message "You have an

# appointment now!".

# 3. Implement a timer program which counts off

until at least five minutes have elapsed, then

# displays the message "You have an

# appointment now!".

4. Locate the sequential file cookies.seq and

create an indexed file cookies.dat, which

# contains the names of four types of cookies

and their prices in cents (v99). Write an

# interactive program which first displays the

contents of the file then lets the user type in

# the search key (one of either raisin, sugar,

# butter or oatmeal) and an amount. The

# program will then calculate how many

# cookies can be purchased for that amount

# and how much change is left over. Assume

# the user will always type in an amount

greater than the price.

# 5. Write a program to create and display the

# multiplication table from 5 x 5 through 10 x

# 10. Have it displayed on a single screen.

# 6. Write an interactive program to accept two

# numbers and create a third negative number.

# Store all three numbers in a sequential file.

# Run the program until you have created all

# the negative digits and zero, then use the

escape key to exit. Display the file. From

# your results, write the table of the letters

# which correspond to all negative digits for

# your system.

7. Locate the sequential file due-date.dat on

# the student disk. This file contains names

# and the number of days until a payment is

# due. Make a record description for this file.

# Write a program to read this file, compute

the due date, which is the number of days a

# payment is due plus the present date, and

# output a new file with names and due dates.

Use the following statement to obtain the

present date, where julian-date is defined in

date.ws and day is the system date stored in

# yyddd format:

accept julian-date from day

CHAPTER SIX

Return to contents

Selection and

Control

# Joshua 24:15

## And if it is disagreeable in your sight to serve the LORD, choose for yourselves today whom you will serve: whether the gods which your fathers served which were beyond the River, or the gods of the Amorites in whose land you are living; but as for me and my house, we will serve the LORD.

# Philippians 3:1 (NIV)

## Finally, my brethren, rejoice in the Lord. To write the same things again is no trouble to me, and it is a safeguard for you.

6.1 Introduction

# The most basic form of data processing selection consists of choosing between two options, such as regular pay versus special pay or an error situation versus not an error situation. This type of selection is especially important for humans, who must choose between good and evil. Sometimes the distinction is not as clear as we would hope for, where evil appears quite good in our eyes. For we know that Satan himself masquerades as an angel of light. But the choice must be made, and unlike data processing our choice between good and evil has eternal consequences. Have you made that choice?

# In data processing, we provide controls in our programs that prevent our software systems from falling into error. If inadequate controls exist, bad data can get into a file making any informational output reports suspect. For man it is similar. In the absence of controls, that which is output from the heart of man is bad because of the sinful condition of the heart. Our output can only change when God's Spirit is input and takes control of our lives, by His marvelous grace. Scripture is given to us to lead us to Christ and as a safeguard or a control against temptation and falling into sin, once we become His.

1 Peter 2:9

# But you are a chosen people, a royal priesthood, a holy nation, a people belonging to God, that you may declare the praises of Him who called you out of

darkness into His wonderful light. (NIV)

6.2 Truth Tables

Conditional expressions can be either true or false. We have already seen conditional expressions with the until clause for loops, with the end clause, and with the invalid key clause for indexed file commands. The statements following a conditional expression are executed only if the conditional expression evaluates to true.

Truth tables are used to help us evaluate the results of using the operators NOT, AND and OR. The truth table for AND is below, where 0 corresponds to false and 1 corresponds to true:

Essentially, false and anything else is always false, while true and true is always true. The truth table for OR is:

# True or anything else is always true, while false or false is always false.

The truth table for NOT is:

# Not true is false, and not false is true.

6.2.1 DeMorgan's Laws

When you combine the NOT operator with AND or OR, the evaluation becomes slightly more difficult. DeMorgan's Laws allow us to easily simplify certain complex expressions in the following manner:

Law 1 \-- NOT (a AND b ) = NOT a OR NOT b

Law 2 \-- NOT (a OR b) = NOT a AND NOT b

Let's prove Law number 1 so we can make use of it with confidence as the need arises. Consider first the case when a is true and b is true. Using truth tables from section 6.2,

## NOT (a AND b) = NOT (true) [left hand side of Law 1]

## = false

## NOT a OR NOT b = false OR false [right hand side of Law 1]

## = false

# Since false equals false, the two sides of the equation are equivalent.

# Consider next the case when a is true and b is false. Using truth tables again,

## NOT (a AND b) = NOT (false) [left hand side of Law 1]

## = true

## NOT a OR NOT b = false OR true [right hand side of Law 1]

## = true

# Since true equals true, the two sides of the equation are equivalent.

# Finally, consider the case when a is false and b is false. Using truth tables one last time,

## NOT (a AND b) = NOT (false) [left hand side of Law 1]

## = true

## NOT a OR NOT b = true OR true [right hand side of Law 1]

## = true

# Since true equals true, the two sides of the equation are equivalent.

# Having proven all 3 cases, we can accept Law 1 as being true. Showing that Law 2 is always true is left as a question at the end of the chapter. We can now use DeMorgan's Laws to help understand, and perhaps avoid, certain complex expressions. Consider this pseudocode:

# if NOT overtime-worked AND NOT holiday-worked

# compute regular pay

# Applying DeMorgan's Law 2, this is the same as

# if NOT (overtime-worked OR holiday-worked)

# compute regular pay

# Decide for yourself which one is easier to understand.

# These laws also help us avoid pitfalls when attempting to modify code. Suppose this pseudocode represents a statement in a program:

## if clean-driving-record AND zero-claims-filed

## compute 10% insurance discount

If we decided to apply NOT to this statement in order to carry out a different function this would be incorrect:

if NOT clean-driving-record AND NOT zero-claims-filed

compute additional 10% premium

# because, by DeMorgan's Laws that's equivalent to

if NOT (clean-driving-record OR zero-claims-filed)

compute additional 10% premium

which is negating a different statement altogether. The correct way to negate the initial statement would be this

## if NOT clean-driving-record OR NOT zero-claims-filed

compute additional 10% premium

Keep these rules in mind if you ever have occasion to use NOT with either AND or OR in any of your software development.

6.3 Using if for Selection

In COBOL, there are two commands available for selection - if and evaluate. The if command is considered here and is used to select from among different alternatives.

# Consider this block of code,

Find-Record.

* if new search key entered, execute new START command

If PD-Item-Number NOT = Stored-number

## Move Message5 to screen-message

## Start Parts-File

## KEY not < PD-Item-Number

## end-start

end-if

# In this example,

==> when the condition specified in the if statement is true, then the

## indented block of code will be executed

==> when the condition specified in the if statement is false, then the

## indented block of code will not be executed

The indentation is optional but helps to identify the code to be executed with its corresponding if statement. The end-if is required and marks the end of the block. The first choice is made when the condition is true. The second choice, an unstated one here, is when the condition is false and the blocked code is not executed.

Consider this block from load-sta.pro,

if states-index = 50

move 1 to loaded-flag

end-if

# In this simpler condition, when states-index has the value of 50 then 1 is moved to the data element loaded-flag. The statement move 1 to loaded-flag is executed when the statement is true. The second choice, unstated here, is when the condition is false and 1 is not moved to the data element loaded-flag.

# This illustrates a case where more than two choices exist:

if option = 1

perform add-routine

end-if

if option = 2

perform display-routine

end-if

if option = 3

perform modify-routine

end-if

When more than two choices exist, the evaluate command is generally superior and is discussed in section 6.3.4.

6.3.1 Condition Names

COBOL has a distinct feature which can be used to simplify the selection process. This feature involves the use of condition names or level 88's. Condition names are defined in this manner,

1 File-Status pic xx.

88 status-ok value "00".

88 end-of-file value "10".

88 key-already-exists value "22".

88 key-not-found value "23".

The condition name is associated with a data element defined with level number 1 through 49. It must be defined immediately after the data element to which it refers. In this example file-status is the data element defined to be a two-character field. This is the field used with an indexed file. The condition name is assigned the number 88 and given a value. Its size and data type correspond to the data element which precedes it, therefore no pic is associated with the 88 definition line.

# In the Procedure Division, the condition name is used as an alternative to a condition. So instead of writing

if file-status = "10"

# Display "End of file reached"

# end-if

# we can write

If end-of-file

# Display "End of file reached"

# end-if

In the preceding example, the condition name end-of-file is substituted for and equivalent to file-status = "10".

# Consider this example. Instead of writing

if option = 1

perform add-routine

end-if

if option = 2

perform display-routine

end-if

if option = 3

perform modify-routine

end-if

# we can define these condition names as follows,

1 option pic 9 value 0.

# 88 add-option value 1.

# 88 display-option value 2.

# 88 modify-option value 3.

# and our Procedure Division code becomes

if add-option

perform add-routine

end-if

if display-option

perform display-routine

end-if

if modify-option

perform modify-routine

end-if

The evaluate command is still superior even to the use of condition names in this instance and is discussed in section 6.3.4.

Condition names provide an excellent opportunity to enhance the declaratives routine from chapter 4:

Declaratives.

For-I-O-Error Section.

Use after error procedure on FD-Name1.

Error-handler.

# Display "Error in data file"

# Display "File status = " file-status

# Display "Data record = " FD-record1.

If end-of-file

# Display "End of file reached"

# end-if

If key-already-exists

# Display "Record already on file"

# end-if

If key-not-found

# Display "Record not on file"

# end-if

End Declaratives.

Condition names can be used to help provide controls in our programs. This is presented in section 6.4.

6.3.2 if..else

The if..else command is a variation of the if command and is used to select from among different alternatives. The else acts as another if for the second choice, that which is executed when the actual if statement is false.

Here's an example of the use of if..else from parts-01.pro:

Add-Record.

If error-flag NOT = 0

move Status-Message to Screen-Message

else

write parts-description

invalid key

# move 0837 to Cursor-position

# move 2 to Error-flag

# move "File Error - Contact Programming - "

to SM-Information

# move parts-status to SM-Status-Code

# move Status-Message to Screen-Message

NOT invalid key

# perform set-up-new-display thru sund-exit

# move Message2 to Screen-Message

end-write

end-if.

When the error-flag is not zero, the move command is selected. Otherwise, the write command is selected. The else saves us the trouble of coding the statement if error-flag = zero, which helps reduce the possibility of coding error. One end-if marks the end of the entire block. The period after end-if is needed whenever it is the last statement in a function. You may also notice that invalid key and not invalid key represent a form of if..else when used with an indexed file command.

Here's an example showing if..else from parts-03.pro:

If process-flag = 2

# perform Screen-2-IO

else

# perform Modify-Record

end-if.

When the process-flag is 2, the first perform is selected and executed. Otherwise, the second perform is selected and executed. The else saves us the trouble of coding the statement if process-flag not = 2, which helps reduce the possibility of coding error. One end-if marks the end of the entire block. The period after end-if is needed whenever it is the last statement in a function.

6.3.3 Nested ifs

Nested ifs occur when one if statement is a command within another if statement. The second if is treated as an ordinary COBOL command. Recognize that the inner command is only executed when the outer condition is true. The first end-if corresponds to the inner if and the second end-if corresponds to the outer if. Nesting can occur for many levels, but more than one or two levels of nesting can make software testing quite difficult.

From parts-04.cbl,

# 1 delete-key Pic X.

# 88 delete-key-yes values "Y" "y".

# ...

If process-flag = 0

Move SPACE TO DELETE-KEY

Move 9 TO PROCESS-FLAG

Move 2459 TO CURSOR-POSITION

# perform Screen-2-IO

# until escape-key-pressed OR delete-key-yes

# If delete-key-yes

# Delete Parts-File

# move 0 to process-flag

end-if

end-if

6.3.4 Evaluate

The evaluate command is an efficient means of handling multiple choices. It makes software testing clean and reliable. Use it whenever possible in place of if. Menu control is handled quite well with the evaluate command:

*******************************************

* "run-appl.pro"

* Code for executing applications

*******************************************

evaluate rp-option

when "1" Call "Parts-01" using out-date

# when "2" Call "Parts-02" using out-date

# when "3" Call "Parts-03" using out-date

# when "4" Call "Parts-04" using out-date

# when "5" Call "Parts-05" using out-date

# when other Move Message1 to Screen-message

end-evaluate.

In this example, when rp-option is 1 the first call command is selected and executed. When rp-option is 2 the second call is executed. And so on. When rp-option is other than 1, 2, 3, 4 and 5 the move command is selected and executed.

The program fct.cbl uses this COPY file to move messages based on which function key is pressed,

evaluate function-key-code

when 0

when 1 Move mesgF1 to Mesg

when 2 Move mesgF2 to Mesg

when 3 Move mesgF3 to Mesg

when 4 Move mesgF4 to Mesg

when 5 Move mesgF5 to Mesg

when 6 Move mesgF6 to Mesg

when 7 Move mesgF7 to Mesg

when 8 Move mesgF8 to Mesg

when 9 Move mesgF9 to Mesg

when 10 Move mesgF10 to Mesg

when other continue

end-evaluate.

# When the function-key-code is 0, nothing happens. When the function-key-code is 1 through 10, an appropriate message is moved. When the function-key-code is anything else, nothing happens - but since it is the last when in the block the word continue is used. What happens in your system when the word continue is omitted? What happens if the entire line when other continue is omitted?

The declaratives routine can be modified further by using evaluate,

Declaratives.

For-I-O-Error Section.

Use after error procedure on FD-Name1.

Error-handler.

# Display "Error in data file"

# Display "File status = " file-status

# Display "Data record = " FD-record1.

evaluate file-status

# when "10" Display "End of file reached"

# when "22" Display "Record already on file"

# when "23" Display "Record not on file"

# end-evaluate.

End Declaratives.

The period after end-evaluate is needed whenever it is the last statement in a function.

6.4 Using if for Control

We need controls in our programs to prevent our software systems from accepting bad data. There once were batch programs whose sole purpose was data validation and printing errors in a report for correction in a later run. Interactive programs can and should provide data validation and feedback immediately for each field which can be checked against a given set of criteria. Some of the things to check for include

# are numbers numbers

# are numbers zero

# are character fields blank

# do fields take on a specific values

# does a specific record key already exist

The Micro Focus Screens Facility can provide the first three of these data checks automatically for interactive programs, before data actually reaches the program. If you don't have Micro Focus or if you are developing a batch data validation program, COBOL if will work. For checking specific values, condition names prove helpful for both batch and interactive software. The keyed read from chapter 4 can be used to see if a specific record key exists.

6.4.1 Are numbers numbers

COBOL has special means for handling checking that numbers are numbers, by using the reserved word numeric. For example,

if employee-SSN not numeric

# Move 2 to error-flag

# end-if

If anything other than numbers make up the employee-SSN field, then this condition would be not false = true, and 2 would be moved to error-flag.

6.4.2 Are numbers zero

# To ensure that numbers are non-zero, we can mimic the following:

if due-date = 0

# Move 2 to error-flag

# end-if

# If the due-date field is zero, then this condition is true and 2 is moved to error-flag.

6.4.3 Are character fields blank

# To ensure that character fields are not blank, we can mimic the following:

if employee-name = spaces

# Move 2 to error-flag

# end-if

# If the employee-name field contains only spaces, then this condition is true and 2 is moved to error-flag.

6.4.4 Checking specific values

Condition names are especially helpful when you need to check if a field contains an appropriate value. From parts.fs,

5 PD-Unit-of-Measure Pic xx.

88 Valid-UOM values "EA" "BX".

and from parts-03.pro:

Process-screen-2.

# Move 0 to process-flag

If not valid-UOM

# Move 1243 to Cursor-position

# Move 2 to process-flag

# Move "Unit of measure must be EA or BX"

# to Status-Message

# end-if

The condition name valid-UOM is defined in the Data Division. In the Procedure Division, the if statement above is equivalent to

If not (PD-Unit-of-Measure = "EA" or "BX")

# which by DeMorgan's Law is the same as

# If not PD-Unit-of-Measure = "EA" and

# not PD-Unit-of-Measure = "BX"

# which by rearranging is the same as

# If PD-Unit-of-Measure not = "EA" and

# PD-Unit-of-Measure not = "BX"

# If the unit of measure is neither of these two acceptable values the condition becomes true, and the statements are executed to prevent the bad data from getting into the system. If more than two values are specified, not using condition names can become quite messy.

Condition names can also specify the word thru for a range of values. For instance,

# 5 rp-option Pic x value space.

88 valid-option values "1" thru "5".

# 88 invalid-option value space.

6.4.5 Does a specific record key exist

We conclude this chapter by revisiting the keyed read from chapter 4 as a control method. The question is this: does the record exist? If a file-status of zero is returned on a keyed read, the NOT invalid key clause can be triggered, which is a form of the if command. The error condition here is when the record does exist. In the add program parts-01.cbl, this code is included in the edit routine:

Edit-Record.

# Move 0 to error-flag

# ...

* save the data while you read

Move Parts-Description to hold-rec

READ Parts-File

# KEY PD-Item-Number

# NOT invalid key

* if record already on file, say so

# Move 0837 to cursor-position

# Move 2 to error-flag

# Move 'Record rejected, duplicate record' to

Status-Message

* restore if data was retrieved

# Move hold-rec to Parts-Description

# end-read

# ...

ER-exit. exit.

6.5 Chapter Summary

This chapter has dealt with the concepts of selection and control. Selection has to do with choosing between a number of possible alternatives, much as we do in our Christian experience on a daily basis. We must choose to take up our cross daily to follow Christ. In COBOL, the if command is available. Different variations of the if command exist, including if..else and evaluate. Condition names can be defined in the Data Division and used in the Procedure Division to simplify code in the Procedure Division. Condition names can specify single values, multiple values by listing each value individually, or a range of values by using thru. It is acceptable to have nested ifs, but too many levels of nesting can complicate the software testing process.

Control in a COBOL program involves keeping bad data out. Some of the things to check for include whether numbers are numeric or non-zero, whether character fields are spaces, whether fields take on specific valid values and whether a specific record key already exists. The Micro Focus Screens Facility can provide the first three of these data checks automatically for interactive programs, before data actually reaches the program. Condition names are especially helpful in determining whether fields take on specific valid values. The NOT invalid key clause of the keyed read can provide assistance in flagging an existing record key error.

Truth tables and DeMorgan's Laws were introduced to assist with understanding how conditions are evaluated. AND, OR and NOT are operators that can be used to make complex conditions in COBOL programs.

With the coverage of selection, most of the COPY files and programs included on the student disk can be fully understood at this time. The remaining chapters cover additional points related to specific applications. Report Writer in the next chapter is a tool for generating reports, which has a number of automatic features that simplify the programming process and reduce the development effort. Tables are useful for special applications and can also be used in place of indexed files in certain instances. And sequential file maintenance relates to the process of merging data into a permanent sequential file.

6.6 Review Questions

1. What choices have you made recently,

# where you had to select between two or

# more reasonably good alternatives? What

# Biblical point of reference did you use in

# arriving at a decision?

2. List the three clauses seen in other chapters

# that deal with conditions.

3. Show the equivalence of the two sides of

the equation for DeMorgan's Law 2

# NOT (a OR b) = NOT a AND NOT b

# when a and b are both true, both false and

# both different.

4. What do truth tables do and what are they

# used for?

5. Which two commands are available for

selection?

6. What's wrong with this block of code?

# If PD-Item-Number NOT = Stored-number

# Move Message5 to screen-message

# Start Parts-File

# KEY not < PD-Item-Number

# end-if

# end-start

7. What's wrong with this code?

1 File-Status pic xx value spaces.

88 status-ok pic xx value "00".

88 end-of-file pic xx value "10".

8. Change this code to replace the else with

another if.

If process-flag = 2

# perform Screen-2-IO

else

# perform Modify-Record

end-if.

9. True or False: Nesting of ifs can occur for

# only two levels.

10. This line is copied from parts-03.pro. Is it

# correct?

# If escape-key-pressed move 9 to process-flag.

11. True or False: The evaluate command is an

inefficient means of handling multiple

# choices.

# 12. What's the matter with this code?

evaluate rp-option

when "1" Call "Parts-01" using out-date

# when "2" Call "Parts-02" using out-date

end-if.

13. What COBOL reserved word can be used

# to make sure a number is valid?

# 14. Give an example of some numeric field not

# mentioned in the text which you would not

# usually want to be zero.

15. Create an appropriate and specific Error-

Message for this code:

5 menu-option Pic 9.

88 Valid-option values 1 thru 5.

## ...

Process-screen-2.

## Move 0 to process-flag

If not valid-option

## Move 2 to process-flag

Move Error-Message to Status-Message

## end-if

# Answers to even-numbered review questions.

2. until; end; invalid key

4. They show us the different possibilities for AND, OR and NOT operators. They

help us to evaluate complex conditions.

6. end-if and end-start are reversed

8. If process-flag = 2

### perform Screen-2-IO

### end-if

if process-flag not = 2

### perform Modify-Record

end-if.

10. Yes. The end-if. can be replaced by just the period in some instances, such as at

the end of a function which is the case here.

12. end-if should be end-evaluate

### 14. hourly pay rate, salary, date of hire, birth date; answers may vary

6.7 Projects

# 1. Design a simple yet realistic data file you

would like to input to a batch data validation

# program. Create the raw data, including possible data errors, using any available text editor and save the data in ASCII format. Develop guidelines concerning what would constitute valid versus invalid data and prepare a set of specifications detailing these guidelines.

# 2. Design a batch data validation program that meets the specifications from the previous problem. List any records with data errors in one file along with an appropriate mes- sage, and list valid records in another file.

3. Write a program to simulate a cash register. It will accept an amount until the escape key is pressed. If the F1 key is pressed, it will accept a quantity to multiply the amount by. (HINT: Design two screens for this.)

4. Experiment with fct.pro in fct.cbl:

evaluate function-key-code

when 0

when 1 Move mesgF1 to Mesg

## ...

when other continue

end-evaluate.

What happens in your system when the word continue is omitted? What happens if the entire line when other continue is omitted? What value is there to including the when other continue line?

5. You have received a request to create a file containing names, addresses, hourly rate of pay and date of hire. Design a screen and write an interactive program, including controls, that will create the file.

6. Create a calling-called pair of programs. Have the calling program pass three para- meters to the called program. The first parameter will come from the keyboard and can be a zero or a one. Have appropriate controls to verify this. Display the second parameter in the called program if the first

parameter is a zero. Display the third para- meter in the called program if the first parameter is a one.

7. Locate the sequential file cookies.seq, which contains the names of four types of cookies and their prices in cents (v99). Write an interactive program which does not read this file but which first displays the contents of

# the file, then lets the user type in the name of

the cookie (one of either raisin, sugar, butter

# or oatmeal) and an amount. The program

will then use a selection process, without

reading the file, calculate how many

# cookies can be purchased for that amount

# and how much change is left over.

Provide controls in the event the user types

# in an amount less than the price.

# 8. Write a date conversion program. That is, a program which accepts the standard month- day-year format for a date and translates it to the 5-digit Julian date. For example, if the month is January and the day is the third the

# Julian date would be 95003.
CHAPTER SEVEN

Return to contents

Report

Writer

# Joshua 18:4

Appoint three men from each tribe. I will send them out to make a survey of the land and to write a description of it, according to the inheritance of each. Then they will return to me. (NIV)

# 1 John 5:13

# These things I have written to you who believe in the name of the Son of God, in order that you may know that you have eternal life.

7.1 What are Reports?

# Reports are produced to convey information. Reports are often selective. There are book reports, reports written to summarize scientific research, reports written to detail survey results as in the time of Joshua, sales reports, inventory reports, payroll reports and accounting reports. Some business reports show the names of those who have failed to make their payments on time. God's book of life contains the names of those who will be in the presence of God for eternity:

Revelation 20:15

And if anyone's name was not found written in the

# book of life, he was thrown into the lake of fire.

# The Bible itself, as a collection of historical reports with God Himself as the Author/Editor-in-Chief, was written to lead us to God and to provide the assurance that we will be with God if we personally receive Jesus Christ as Lord and Savior.

# Business reports are written to lead us to profits. Computer-generated reports generally fall into one of three categories. They are:

# transaction

# exception

# summary

A transaction report would list individual transactions such as sales, payments or employee wage information. An exception report lists information that requires immediate attention, such as too much overtime, too little inventory, or material that is excess and/or obsolete. Summary reports would lump all the detailed transactions together to give a bigger picture in terms of totals by store, totals by department, totals by branch or division, etc. Computers are capable of being used to produce reports efficiently and quickly.

7.2 Report Data Elements

Reports are information in an easy-to-read format. The Report Writer is an extension of COBOL available with most systems which provides for relatively easy report generating capabilities. Reports in general consist of a beginning, middle and end, also referred to as a heading, body and summary. In computer jargon these components are referred to as

# headings

# detail lines

# subtotals and totals

which must be identified first in the Data Division. To use Report Writer, define report lines in the Report Section of the Data Division. The first entry is an RD entry:

RD grades Page limit 62

## Heading 1

## First detail 5

## Last detail 51.

The RD is similar to an FD, although more information is provided for an RD. The page limit clause informs the system of the maximum number of lines per page. The Heading clause informs the system where to place the first heading line on each page. The First detail clause informs the system where to place the first data line on each page. The Last detail clause informs the system where to place the last data line for each page. Be careful that numbers follow a consistent pattern, and that the heading isn't specified after the detail, or the last detail before the first.

# It's also possible to specify whether totals are to appear at the end of each page, at specified controlled intervals, or at the end of the report. For instance, producing subtotals by store and a final report total requires the following,

RD Sales Controls are Final, Input-Store-Number

Page limit 62

## Heading 1

First detail 5

## Last detail 51.

7.2.1 Headings

# The heading provides information at the top of each report page, which clearly identifies the title of the report, page number, date, subheadings (if needed) and column headings for detailed record data. Here is a very simple example of a report,

The heading contains the date 06/26/95, the title GPA Report and the page label and number Page 1. There is no subheading in this example. The column headings are Student and GPA, which are neatly arranged over the corresponding detailed data.

# Defining these headings in the program is accomplished with the following code,

1 Type page heading.

3 Line 1.

5 Column 3 Pic x(8) Source current-date.

5 Column 18 Pic x(20) value "GPA Report".

5 Column 35 Pic x(4) value "Page".

5 Column 40 Pic z9 Source page-counter.

3 Line 3.

5 Column 16 Pic x(7) Value "Student".

5 Column 27 Pic x(3) Value "GPA".

Type page heading is a set of COBOL reserved words which specify to the Report Writer that you are defining a page heading type. This will have special significance to the Procedure Division commands discussed later. Line is also a COBOL reserved word specifying the line of the report on which the corresponding fields will be displayed. The first one corresponds to the Heading clause in the RD entry. The others should occur after that but before the number specified in the First detail clause of the RD entry. You'll recall that Line is also used in the Screen Section. The Column entry lets you specify the column where you want the heading information or data to begin. In the Screen Section Col is used for the same purpose, but the full spelling of column must be used in the Report Section.

Data elements current-date and page-counter are available to Report Writer only, and provide the current system date and current page respectively when used with the Procedure Division commands. Source is used to specify that a data element will be the source of the information to be placed in a particular column.

5 Column 40 Pic z9 Source page-counter.

The z character is the COBOL zero-suppress character, providing for zero suppression of leading zeroes in any output field where it appears, even in detail lines. In this example no more that 99 pages are expected (is this reasonable?) and for pages 01 through 09 the page number would appear as 1 through 9 with no leading zero.

7.2.2 Detail Lines

The detail line provides information from each transaction, or summary of transactions in the case of a summary report, in the input file or files. Unlike headings, a detail line template is representative of all detailed data for a given transaction or summary of transactions, such as a student, employee or account, to be viewed on the report. There might be one input record for each detail line generated on the report. Or, as in the following example of a summary report, there may be information from a number of input records combined into a single detail line.

It's also possible to have multiple detail lines, especially for input transactions that will exceed the standard line length for the paper and printer the application is using. In this example there is one detail line template and exactly two detail lines generated in this summary report from an unknown number of input records:

# Defining the detail line used to create this report is accomplished with this:

1 Detail-line Type detail

# Line plus 2.

5 Column 16 pic 9(6) Source previous-student.

5 Column 27 pic 9.99 Source ws-gpa.

Type detail is a set of COBOL reserved words which specify to the Report Writer that you are defining a detail line type. This will have special significance to the Procedure Division commands discussed later. Line plus is also a set of COBOL reserved words used to specify the relative line spacing for the report where the detail lines will be displayed. Recall from the RD entry in this example that the first detail line appears on line 5. By specifying line plus 2, every detail line after the first one will appear on every other line. This results in double-spacing. How would you accomplish triple-spacing? The last detail line as specified in the RD entry will be on line 51 as long as there are enough records in the file to get that far down on the page. Since there are only two detail lines generated from this particular set of data, the last detail line appears on line 7.

The Column entry lets you specify the column where you want the data to begin. You will want to choose column numbers for the detail line entries so that the data is approximately centered, left-justified or right-justified under the column headings, depending on what the user wants. As mentioned in section 7.2.1, in the Screen Section Col is used for a similar purpose for screens, but the full spelling of column must be used in the Report Section.

Source is used to specify which data element is the source of the information to be placed in a particular column.

7.2.2.1 Decimal points

The data element ws-gpa is defined in the Working-Storage Section in this example, although data elements referenced in the Report Section may also be defined in the Linkage Section or File Section of the Data Division depending on the design.

1 ws-gpa pic 9v99 value zeros.

This turns out to be a calculated field and uses the implied decimal point in its definition. Recall from earlier chapters that numeric data elements or fields can be defined with a decimal point in the Data Division. Input fields and intermediate fields use implied decimal points (v) which take no space at all, while output fields use real decimal points (.) which take up one character all their own. The output field is defined in the Screen Section like this

5 Column 27 pic 9.99 Source ws-gpa.

The . character is the COBOL physical decimal point, providing for a dot to appear on the report for output fields. When you move an input field to an output field, the numbers are automatically aligned by the decimal points. By using source in the Report Section, the Report Writer commands correctly used in the Procedure Division cause the source field to be automatically copied to the output field, also performing the decimal alignment as a natural result of the implied move operation.

# In this example GPA is expected to be in the range from 0.00 to 4.00, although it could go as high as 9.99 if a bad value were input. No validation controls are needed in the report program to verify raw grades fall into the correct range, since data is just being output.

In a properly designed system the validation controls are in the program which inputs the raw grades into the grade1.dat file, eventually to be used by this Rpt-gpas report program. What validation controls might you want to have in the subsystem used to enter raw grades?

7.2.2.2 Dollar signs and commas

In other cases, you may want to have a dollar sign and a comma appear on a report. COBOL has the $ and , characters, which can be used in your output fields whenever needed merely to enhance readability and understandability on the part of the user or the person receiving the report. The comma can be placed anywhere in the numeric output field, so be careful to place it correctly depending on the particular currency the report is dealing with. Always specify at least one more dollar sign than the number of digits you expect when you define an output field using the dollar sign.

There are two ways to use the dollar sign. The first is a fixed format, where the dollar sign always appears in the same position in the output field:

5 Column 39 pic $z,zz9.99 Source pr-wage.

The other is a floating format, where the dollar sign floats to the right as needed to eliminate spaces between the number and the sign:

5 Column 39 pic $$,$$$.99 Source pr-wage.

# Your company and/or the user will let you know which is to be used in any specific application. The comma in both these examples will not appear if the dollars are less than $1,000.

7.2.2.3 Negative numbers

Recall from earlier chapters that numeric data can be defined with a sign in the Data Division. Input fields and intermediate fields use implied signs (s), which actually share space with the rightmost digit. When such an input field is printed, the last digit appears as a letter. Output fields use real signs (-) which take up a character all their own.

An output field might be referenced in the Report Section in this manner,

5 Column 35 pic 99.9- Source ws-temperature.

The - character is the COBOL physical sign, providing for a dash to appear on the report for output fields. The physical sign is placed last in the data definition. When an input is moved to an output field, the minus sign appears for negative numbers.

# The source data element might be described like this

1 ws-temperature pic s99v9 value zeros.

since both Fahrenheit and Centigrade temperatures can go below zero. The s character is always placed first in the data description, even though the sign indicator is stored with the last digit. By using source in the Report Section, the Report Writer commands used correctly in the Procedure Division cause the source field to be automatically copied to the output field, also performing the decimal alignment and having the minus sign appear for negative numbers as a natural result of the implied move operation. For positive numbers, no sign will appear.

For negative numbers, define the output field with the physical minus sign -. The program which originally creates the data file must specify the sign character in the record description for the file. The s in a data declaration stands for sign and means that the number can be negative, but it doesn't have to be. The s doesn't take up space in the file, but shares space with the rightmost digit. Since a digit only needs 4 bits to be represented (from chapter 4), the other 4 bits can store the sign indicator. The entire 8 bits print as a letter of the alphabet for negative numbers. Since it is correctly stored in a numeric field, the computer will handle it correctly. A signed field must be moved to a field described with a physical sign to be easily interpreted.

To use a negative number as a numeric literal in the Procedure Division place the sign in front of the number as shown here:

# move -25 to ws-temperature

7.2.3 Subtotals and Totals

Totals provide the user with controls to verify that figures from the beginning of a process make it through to the end. Some numbers may kick out as errors, and there will be totals for that part of the system. Other numbers may show up on a primary report, and there are totals for that. As long as the totals add up to what is expected, there is confidence that the entire system is working properly and that the data entry people are doing their job flawlessly. Accountants are especially concerned with this.

The chapter dealing with arithmetic showed how to make totals. The chapter dealing with the if statement showed how to implement controls in our programs. The Report Writer feature automatically combines these two operations in a way that hides what otherwise might appear complex. The following code segment may be used as a model for any program which makes use of subtotals and totals (note the RD on page 107 in section 7.2 also needed for this code to work):

1 Subtotal-line Type control footing Input-Store-Number

## Next group next page.

3 Line plus 4.

5 Column 20 PIC X(16) value "Store Totals".

5 Column 43 PIC Z(6).99- Sum ws-Sales-Amount.

5 Column 53 PIC Z(4).99- Sum ws-Sales-Tax.

5 Column 63 PIC Z(9).99- Sum ws-Sales-Total.

1 Total-Line Type control footing Final.

3 Line plus 2.

5 Column 20 PIC X(16) value "Grand Totals".

5 Column 43 PIC Z(6).99- Sum ws-Sales-Amount.

5 Column 53 PIC Z(4).99- Sum ws-Sales-Tax.

5 Column 63 PIC Z(9).99- Sum ws-Sales-Total.

Type control footing is a set of COBOL reserved words which specify to the Report Writer that you are defining a total line to appear at the end of each group. This will have special significance to the Procedure Division commands discussed below. Input-Store-number in this case is simply a field in a typical record of the input file. The file must be arranged by store number. Each store number represents a group which the user wants to have a total for. The store manager may get a copy of only that section of a report which lists his or her store information, with the subtotal for the store also included. Final is a special word used to specify a grand total for the entire report, to appear on the very last page. Line plus 2 and Line plus 4 specify the relative line spacing for these total lines. Next group next page is a set of COBOL reserved words to automatically start a new set of headings at the top of a new page for the next store. The word Sum is used to trigger an accumulation operation, adding the values from the ws-fields into unnamed accumulators to be output according to the specified format.

7.3 Report Processes

The Procedure Division of a Report Writer pro-gram can contain all other COBOL commands, but usually not the write command. In general, the Procedure Division for a Report Writer program is substantially smaller in size than a comparable program not using Report Writer, with correspondingly less development cost.

# After code for opening files, include this statement referring to the RD name:

Initiate grades

This activates the Report Writer. It should be noted here that in the Data Division the FD for a report is slightly different from other FD's -- there is no level number 1 associated with it but instead the word Report and the RD name, also listed in the Report Section,

FD Report-out Report grades.

# Just prior to commands closing the file, include the following statement

Terminate grades

# In the middle of the program, at an appropriate point, the following statement is used to conduct ordinary processing:

Generate detail-line

This statement always names the detail line identified in the Report Section. Before this takes place the first time, the first set of headings is written. As a result of this operation, a detail line is output. In addition, if a control clause has been triggered a total is printed. If the bottom of the page has been reached, a new set of headings is generated. All this takes place automatically. What would you need to do to handle all these operations manually?

7.4 Complete Program Example

The following is a complete program example of a summary report available on the student disk. Please note that since one of the input files is a sequential file (as seen in rpt-gpas. env), it has to be in ascending sequence for this particular program to work unless it's converted to an indexed file. Placing records in sequence or sorting may be accomplished with an operating system sort utility or with a COBOL sort program. COBOL sort programs are very simple programs and are discussed in chapter 9, where they are needed especially for sequential file maintenance.

Identification division.

Program-id. Rpt-gpas.

* report writer program - summary report

Environment division.

Input-output section.

File-control.

copy rpt-gpas.env.

Data division.

File section.

Fd courses. copy "course.ws".

Fd Report-out Report grades.

Fd sorted-grades.

1 Filler.

5 Gr-student-id Pic 9(6).

5 Gr-course-id Pic x(6).

5 Gr-letter-grade Pic x.

Working-storage section.

copy rpt-gpas.ws.

Report section.

copy rpt-gpas.rs.

Procedure division.

Go-for-it.

Open input sorted-grades Output report-out i-o courses.

Initiate grades

Read sorted-grades end move 1 to end-flag.

Move gr-student-id to previous-student.

Perform until time-to-quit

Perform grade-conversion

perform read-course-file

Perform check-student

Read sorted-grades end move 1 to end-flag end-read

end-perform

* handle last student's gpa

Perform GPA-output

Terminate grades

Close sorted-grades report-out courses.

Stop run.

***** Subroutines

Grade-conversion.

Evaluate gr-letter-grade

when "A" move 4 to number-grade

when "B" move 3 to number-grade

when "C" move 2 to number-grade

end-evaluate.

Read-course-file.

move gr-course-id to cd-course-id-key

Read courses

key cd-course-id-key

invalid key

display cd-course-id-key

" course not found."

end-read.

Check-student.

If gr-student-id not = previous-student

Perform GPA-output

Perform GPA-arithmetic

else

Perform GPA-arithmetic

end-if.

GPA-arithmetic.

add cd-number-credits to accum-credits

multiply cd-number-credits by number-grade

giving course-points

add course-points to accum-course-points.

GPA-output.

* calculate GPA and output

Compute WS-gpa = accum-course-points / accum-credits

Generate detail-line

* set up for next student

Move gr-student-id to previous-student

Move zero to accum-credits accum-course-points.

7.5 String

It is sometimes helpful in reports to combine two or more fields, eliminating spaces in the process. This can be accomplished with the string command in COBOL,

# string first-name delimited by space

# " " delimited by size

# last-name delimited by space

# into output-name-field

# end-string

This takes the contents of the first field and copies it to the into field until a space is encountered in the first field; then it takes the literal and copies all of it to the output field; lastly it takes the second field and copies it to the output field until a space is encountered. The end result here is a field with the first name and last name separated by a single space. The advantage of this is that oftentimes there are excess spaces which present an annoyance to the user, which this command eliminates.

7.6 Chapter Summary

Reports are produced to convey information and are often selective. The Bible, as a collection of historical reports inspired by God, was written to lead us away from sin toward God and to provide the assurance that we will be with God if we personally receive Jesus Christ as Lord and Savior. Business reports are written to lead to profits. Computer-generated reports may be transaction, exception or summary reports. A transaction report lists individual transactions, an exception report lists information that requires immediate attention, and summary reports lump detailed trans-actions together in an organized way.

The Data Division FD entry for a report is slightly different from other FD's. There's no level number 1 but instead the word Report and RD name, also listed in the Report Section, are provided.

Report data elements consist of headings, detail lines, subtotals and totals. All these must be identified first in the Data Division. To use Report Writer, define all report lines in the Report Section of the Data Division. The first entry in this section is an RD entry. The control clauses specify subtotals and totals for the report. The page limit clause informs the system of the maximum number lines per page. The heading clause informs the system where to place the first heading line on each page. The first detail clause says where to place the first data line on each page. The last detail clause informs the system where to place the last data line for each page. Be careful that numbers follow a consistent pattern.

Type page heading is a set of COBOL reserved words which specify to the Report Writer that you are defining a page heading type. Line is a COBOL reserved word specifying the line of the report on which the corresponding fields will be displayed. The Column entry specifies the column where heading information or data begins.

Data elements current-date and page-counter are only available to Report Writer, and provide the current system date and current page respectively when used with the Procedure Division commands. Source is used to specify which data element will be the source of the information to be placed in a column.

A detail line template is representative of all detailed data for a given transaction or summary of transactions to be viewed on the report. It is possible to have multiple detail lines, especially for large input transactions. Type detail is a set of COBOL reserved words which specify to the Report Writer that you are defining a detail line type. Line plus is a set of COBOL reserved words used to specify relative line spacing for detail and total lines.

The implied decimal point v (which takes no space at all) may be used for input fields and intermediate fields, while output fields use real decimal points (.) which take up one character all their own. When you move the input field to the output field, numbers are automatically aligned by decimal points. By using source in the Report Section, the Report Writer commands correctly used in the Procedure Division cause the source field to be automatically copied to the output field, performing the decimal alignment as well.

The z character is the COBOL zero-suppress character, providing for zero suppression of leading zeroes in any output field where it appears. The dollar sign ($) and comma (,) characters can be used in output fields whenever needed to enhance readability and understandability on the part of the user. The comma can be placed anywhere in the numeric output field. Always specify at least one more dollar sign than the number of digits you expect when you define an output field using the dollar sign. The dollar sign may be fixed format, where the dollar sign always appears in the same position in the output field or floating format, where the dollar sign floats to the right as needed to eliminate spaces between the number and the sign. Negative numbers are represented using the s (which shares space with the rightmost digit) for input fields and intermediate fields, while output fields use real signs (-) which each take up one character all their own.

Subtotals and totals provide the user with controls to verify that the figures they start with at the beginning of a process all make it through the process. The Report Writer feature can automatically generate totals. The word Sum is used to trigger an accumulation operation, adding values from specified fields into unnamed accumulators which are output automatically at the proper time. Type control footing is a set of COBOL reserved words which specify to the Report Writer that you are defining a total line to appear at the end of each group. You specify the group which the user wants to have a total for. Final is a special word used to specify a grand total for the entire report, to appear on the very last page. Next group next page is a set of COBOL reserved words to automatically start a new set of headings at the top of a new page for each new group.

The essential report processes used by Report Writer include initiate to activate the Report Writer, terminate to conclude, and generate to do all other report-specific processing. A complete program example of a Report Writer program is available on the student disk.

The string command was also presented in this chapter. It can be helpful in reports and display programs to combine two or more fields and eliminate extra spaces in the process.

7.7 Review Questions

1. What response have you made to the

reports presented by God in the Bible?

2. List the three types of business reports and

give examples of each.

3. What's the matter with the following code

segment?

RD grades Page limit 51

# Heading 1

First detail 5

# Last detail 62.

4. What's the matter with the following code

segment?

RD grades Page limit 62

# Heading 6

First detail 5

# Last detail 51.

5. What's the matter with the following code

# segment?

RD Sales Controls are Final,

Input-Store-Number.

Page limit 62

# Heading 1

First detail 5

Last detail 51.

6. The special system name current-date is

# received into a pic x(8) field, yet prints

# with slashes. How would you set up a

detail line field to receive a date, where the

# source field was defined as 9(6) or month

# day year?

7. What do you think may be wrong with the

# following code? Why?

5 Column 40 Pic 9z9 Source page-counter.

8. What is the matter with the following

# Report Section code segment?

3 Line 3.

5 Col 16 Pic x(7) Value "Student".

5 Col 27 Pic x(3) Value "GPA".

9. Write a Report Section entry to triple space

# a detail line.

# 10. What's the matter with the following code

# segment?

1 Detail-line Type detail

# Line plus 2.

5 Column 16 pic 9(6) Source "previous-student".

5 Column 27 pic 9.99 Source ws-gpa.

# 11. What's the matter with the following code

# segment?

1 Detail-line Type detail

# Line plus 2.

5 Column 16 pic 9(6) Source previous-student.

5 Column 27 pic 9v99 Source ws-gpa.

# 12. What controls might you want to have in

# the subsystem used to enter raw grades?

# 13. Create a simple diagram showing the

# interrelationships between the grades

subsystem used to create and maintain

grade1.dat, the course subsystem used to create and maintain courses.new, and the Rpt-gpas report program.

# 14. What's wrong with the following code

# segment?

5 Column 39 pic $$,$$,$.99 Source pr-wage.

# 15. What's wrong with the following code

# segment?

5 Column 39 pic $9,$$$.99 Source pr-wage.

16. List one disadvantage of using the floating

# dollar sign.

# 17. What's wrong with the following code

# segment?

5 Column 35 pic -99.9 Source ws-temperature.

# 18. What's wrong with the following code segment?

# move 25- to ws-temperature

# 19. Write an RD entry for a report which has

# only a final total.

# 20. In this example, what is the name of the

# calculated field used to store the sum of all

# the ws-Sales-Tax transaction values?

5 Column 53 pic Z(4).99- Sum ws-Sales-Tax.

# 21. List the three essential Report Writer

# Procedure Division commands.

# 22. What's the purpose of the string command?

# Answers to even-numbered review questions.

2. transaction (student grade reports), summary (grade averages by class) and

exception (report of students below a certain GPA) (examples may vary)

4. Inconsistency - heading line after first detail line

6. Use slashes - pic 99/99/99

8. Column must be spelled out in the Report Section

10. There should be no quotes around previous-student

### 12. verify that the grades are one of A, B, C, D, F or I, etc.; make sure the course

ID exists in the course file; and make sure the student ID is valid

### 14. Nothing - the extra comma does not generate a syntax error.

### 16. The $'s would not all line up on the report

### 18. The dash should precede the numeric literal in the Procedure Division

### 20. It has no name

### 22. To combine two or more fields and eliminate extra spaces

7.8 Projects

1. Compile, link and run the Rpt-gpas report program on the student disk.

2. Change the numbers in the RD for the Rpt- gpas program and see what errors you can generate. Also try leaving out one or more lines in the RD and attempt to create com- piler errors. Write down at least 5 different errors and the messages generated.

3. Add more data to the input file for the GPA program, enough to generate 16 detail

# lines, and test it. Change the last detail line placement to be 15. Run the GPA program and see the results using your new data.

4. Use a text editor to create a file consisting of at least 10 employee numbers, employee names and weekly paycheck amounts

which should include an implied decimal point. Write a report program to print each transaction, including a grand total.

5. Write a simple batch program to create all the negative digits. Display the file. From your results, write the table of the letters which correspond to all negative digits for the system you are working with.

6. Use a text editor to create a file of at least 10 dates and temperatures. The date

# should be in month (MM), day (DD) and year (YY) format. The temperature should allow for negative numbers (see previous project). Create a report to list all the information. Use the slash character for the output date and the physical sign for any negative temperatures. Be sure your data includes some negative numbers.

7. Implement a system to create, maintain and report the courses.new file.

8. Convert grade1.dat to an indexed file

called grades.dat and make all necessary changes to Rpt-gpas.cbl.

9. Implement a system to create, maintain and

report the grades.dat indexed file

# mentioned in project 8.

10. Change the Rpt-gpas program so it doesn't use Report Writer. Have the output be

# identical for both versions of the program when run on any given day.

# 11. The report program for the Parts system

first presented in chapter 3 is an example of a transaction report program:

Identification Division.

Program-ID. Parts-05.

* This program is called from the Parts main menu

* The report is sequenced by alternate key Item Description

Environment Division.

Input-Output Section.

File-control.

## copy parts-05.env.

## Select output-report assign to "parts.prn"

## organization line sequential.

Data Division.

File Section.

FD output-report Report parts.

copy parts.fs.

Working-Storage Section.

1 parts-status Pic xx.

1 parts-counter Pic 9(6) value 0.

1 end-flag Pic 9 value 0.

## 88 time-to-rest value 1.

Report Section.

## copy parts-05.rs.

Procedure Division.

## Open input Parts-File

## output output-report

## initiate Parts

* Position before first item description

## Move low-values to PD-Item-Description

## Start Parts-File

## key not < PD-Item-Description

## end-start

## Read Parts-File next

## end move 1 to end-flag

## end-read

## Perform until time-to-rest

## Add 1 to parts-counter

## generate detail-line

## read Parts-File next

## end move 1 to end-flag

## end-read

## end-perform

## terminate Parts

## close Parts-File output-report

## Exit Program.

This program has the interesting feature

that it reads the file based on the alternate record key. (Also note that low-values is a special COBOL word which represents a value less than zero. Why would this be useful?)

Copy this program and modify the copy to create a report program which reads the

primary record key. Then modify the

# menu program to handle the extra option. Compile, link and test the resulting system.

# 12. Rewrite the report program from the

previous project so it doesn't use Report Writer.
Part 3

Return to contents

Special

Topics

1 Corinthians 3:14-15

If any man's work which he has built upon it remains,

he shall receive a reward.

If any man's work is burned up, he shall suffer loss;

but he himself shall be saved, yet so as through fire.
CHAPTER EIGHT

Return to contents

Tables

# Ecclesiastes 12:9

# In addition to being a wise man, the Preacher also taught the people knowledge; and he pondered, searched out and arranged many proverbs.

8.1 What are tables?

# Tables provide a means of arranging and accessing data within a program (while files are generally used to arrange and store data outside a program.) There are three types of tables:

# internal tables

# internal tables loaded from external files

# external files which are tables

A table can exist solely within a program as an internal table. These are usually small. A table can also be an internal table loaded with data from an existing file at runtime. Tables can be completely external to a program and as such are referred to as relations. This chapter will deal primarily with the first two types of tables.

Choosing whether to use an internal table or one loaded with data from a file may depend to a large degree on expected changes to the tabular data. When the table exists solely in the program, it is hard-coded and becomes more difficult to maintain. If changes are to occur frequently, it would be unwise to hard-code the data because of the high cost associated with software development. Every time table data changed, the program would have to be changed, recompiled and retested.

# When table data exists outside the program, say as an indexed file, it can be loaded into the program when needed. An indexed file has greater flexibility in terms of maintaining the data versus storing the table as a literal data element within the program. But if the data is already in an indexed file, what possible advantage can there be in taking the extra step of loading it into a program table? (See section 8.2 for the answer)

The third type of table, the relational database table, is a natural extension of the first two types where the table has now been completely removed from the program and is stored as an external file. Relational databases are viewed as collections of tables or relations. Each relation in a relational database is represented as a table, where rows represent records and columns represent fields. Setting up and accessing relational databases involves using a special language to operate on the tables, called Structured Query Language or SQL. The SQL language statements can be called from a COBOL program, but this topic is currently beyond the scope of this text. Several excellent stand-alone relational database packages are also available for both mainframes and PCs.

Operating systems make regular use of tables to store a variety of information, such as the return point for a perform command. The most notable business application of tables today is spreadsheet software, where tabular data is created or retrieved, manipulated, and stored. This is a simple example of a partial table using Scripture:

Reference Proverb

# 20:03:05 Trust in the LORD with all your heart,

# And do not lean on your own under- standing.

# 20:16:03 Commit your works to the LORD,

# And your plans will be established.

# 20:22:06 Train up a child in the way he should go,

# Even when he is old he will not depart from it.

# 20:22:29 Do you see a man skilled in his work?

# He will stand before kings;

# He will not stand before obscure men.

# {Proverbs offer us wisdom as we strive to complete the work God has given us.}

8.2 Why use tables?

There are many unique situations which come up that call for the use of an internal table in a COBOL program. For instance, internal tables provide the opportunity to sort intermediate results before outputting data. You have to assess any design problem that arises and determine whether a table would meet the solution requirements. In addition, with regard to a table loaded from a file, faster processing can often occur using the table if the data is to be accessed numerous times. The offsetting consideration is the amount of time needed to load the file into the table compared with the time to just read the file. Given modern processing speed, such factors become insignificant given a small to moderately sized auxiliary file. If the file is very large, you ought to consider whether the number of accesses to the data will make the table a worthwhile option.

# The most convincing argument for the use of tables relates to memory or storage considerations. Consider this illustration. Cost account codes consisting of 3 digits could be part of each primary record, while cost account codes and corresponding account names of 30 characters could be stored in an internal table or auxiliary file. For a primary file consisting of 40,000 records, how many bytes are saved by using an internal table? How many are saved by loading the table from an auxiliary file?

Case 1 - internal table

## Size of account name 30

Size of account code \- 3

## Savings per record 27

Number of records x 40,000

Total savings 1,080,000 bytes

Case 2- auxiliary file

## We need to know exactly how many different cost accounts there are.

## Suppose there are 500.

## Size of account name 30

Size of account code +3

## Size of auxiliary record 33

Number of records x 500

## Total auxiliary file size 16,500 bytes

## Original savings 1,080,000 bytes

Size of auxiliary file \- 16,500 bytes

New total savings 1,063,500 bytes

It's evident from these examples that there are some savings to be had by using tables, perhaps not significant by today's standards. In the past, in order to optimize storage on disks, it became a useful practice to use codes or IDs as part of each record in the primary input file, instead of names such as department names, account names or course names. The names themselves, oftentimes lengthy descriptions, would be associated with codes by means of tables. The name is substituted for the code after a successful search, discussed in section 8.4.

8.3 Table definition

# In COBOL, as mentioned earlier, there are two ways to define an internal table program -

# internal tables

# internal tables loaded from external files

The first method is to define the table as a data element within the program using the redefines clause. The second method is to define it as a data element within the program and load the table data from an auxiliary file.

8.3.1 Defining the table as a data element within the program

# In the Working-Storage Section, a table is defined first as a set of constants then redefined as data elements which can be referenced by an index. Consider the following:

Specification

Course ID Description Credits

## CIS220 Computer Info Sys 3

## CIS224 COBOL 4

## ...

## CIS421 Software Development 4

COBOL Code

1 Course-constants.

## 5 pic x(37) value

## "CIS220Computer Information Systems 3".

## ...

## 5 pic x(37) value

## "CIS421Software Development 3".

1 Course-table redefines Course-constants.

5 course-elements occurs 15 times

indexed by course-index.

## 10 course-ID pic x(6).

## 10 course-description pic x(30).

## 10 course-credits pic 9.

The second group level course-table redefines the first group level course-constants, which means it uses the same locations or area of memory assigned to the program but assigns new data element names to those locations. In this case, course-elements occurs or repeats 15 times, corresponding to the 15 entries (not all listed here) in Course-constants. Within course-elements, course-ID refers to the first 6 bytes in each line of Course-constants, while course-description refers to the next 30 bytes and course-credits refers to the last byte. Notice that the number of credits is defined as a character, then redefined as a number. This is one of the advantages of COBOL, and has other applications besides tables. The indexed by clause automatically creates a special numeric data element which is used as the index or pointer to the elements of the table, so a separate data declaration is not needed to define course-index.

# Within the Procedure Division, the table's elements could be referenced with code like this:

# display course-element(3)

# display course-ID (5)

# display course-description (8)

# set course-index to 12

# display course-element (course-index)

The set command is used to set (instead of using move), add to or subtract from (instead of using add or subtract) a table index value defined with the indexed by clause. For instance, you may need to set the index value to 1 before beginning a search operation. Or you may want to increment or decrement the index value as part of a special algorithm you are using to operate on a table.

To increment (add to) the index value defined with the indexed by clause use this format:

set course-index up by 1

To decrement (subtract from) the index value defined with the indexed by clause, use this format:

set course-index down by 1

Some COBOL table operations do not require the use of set at all. It's also possible to define a table index as a regular numeric data object, in which case move would be used to set it to a specific number, and add and subtract would be used to increase or decrease the value.

8.3.2 Loading table data from an

auxiliary file

When loading tables from auxiliary files, tables are defined differently in the Data Division. There is also the need to define the file in the typical fashion using Select/FD entries, and an additional routine is required in the Procedure Division to read and store the information as part of the program's initialization step. Consider this illustration of a course table:

1 Course-table.

# 5 course-elements occurs 15 times

# indexed by course-index.

# 10 course-ID pic x(6).

# 10 course-description pic x(30).

# 10 course-credits pic 9.

# To read and store the data in this table:

## set course-index to 1

## read auxiliary-file

## end move 1 to eof-flag

## end-read

## perform until eof-flag = 1

## move auxiliary-file-course-info to course-elements (course-index)

## set course-index up by 1

## read auxiliary-file

## end move 1 to eof-flag

## end-read

## end-perform.

This example uses the set command to specify the initial value of the index, so the first spot in the table is filled first. Then set is used to increment the index value, so the table is filled in one line or row at a time.

# Here is a very useful example involving States:

1 loaded-flag pic 9 value 0.

1 states-table.

5 list-of-states occurs 50 times

# indexed by states-index.

9 los-state-id pic xx.

9 los-state-desc pic x(20).

# To read and store the data in this table:

perform load-States

## varying states-index from 1 by 1

## until loaded-flag = 1 OR

end-of-states-file = 1

****************************************************

* load-sta.pro - function to copy data from States file to a table

****************************************************

load-States.

move sr-state-id to los-state-id (states-index)

move sr-state-desc to los-state-desc (states-index)

if states-index = 50

move 1 to loaded-flag

end-if

read states-file

end move 1 to end-of-states-file.

ls-exit. exit.

Notice that in this second example, the set command is avoided completely by the use of the perform...varying...until option first mentioned in chapter 2. Also, what is the purpose of loaded-flag? Once the end of the States file is reached, the end-of-states-file object is set, so isn't loaded-flag redundant or unnecessary? If it is necessary, should something comparable be used with the course file and table in the first example?

8.4 Table handling

There are four main methods of accessing the elements of a table: using a specific index value, or the commands sort, if and search.

Using a specific index value to access a table element has already been illustrated. For example, this statement will access the third element or row of the table and cause it to be displayed: display course-element(3)

8.4.1 Sorting a table

The COBOL sort command sorts tables as well as files. Chapter 9 covers sorting files. For sort to work with a table, the table definition must use the ascending key or descending key clause in the Data Division:

## 5 course-elements occurs 15 times

## indexed by course-index

descending key course-ID.

# In the Procedure Division, this simple statement will now arrange the rows in order from highest to lowest according to the course-ID field -

Sort course-elements

8.4.2 Using if to find a table value

Suppose an input value has been provided from some part of the program - for instance, Input-course-ID. At the top level, perform...varying ...until can be used to effectively access a basic search procedure to locate the course name associated with the code:

Perform Table-Look-Up thru tlu-exit

varying course-index from 1 by 1

until course-index > 5 or exit-code = "YES"

* thru specifies the exit point for the procedure

* varying starts the course-index at 1 and adds 1

# each time through the loop

* until specifies the conditions for terminating the

perform

At the function or subroutine level, the if is used in the following manner to conduct a basic sequential search:

Table-Look-Up.

If input-course-ID = course-ID (course-index)

Display course-name (course-index)

Move "YES" to exit-code.

tlu-exit. exit.

# As long as input-course-ID doesn't match course-ID (course-index), nothing happens in this function. When a match is finally found, the course-name (course-index) is displayed and exit-code is set to "YES".

8.4.3 Using Search to find a table value

The COBOL search command is a built-in function which automatically does the basic sequential search described above. The search all option is a built-in binary search function, which is somewhat faster or more efficient. These search methods are discussed in greater detail in introductory structured programming texts. The essence of them both is that a code or search key is used to locate a search target or name within a table. The difference in the application of these is that for binary search to work properly, the table values must first be sorted in ascending order (from lowest to highest). Both searches yield the same result, quickly locating the name associated with a specific code.

8.4.3.1 Binary search

In the COBOL table definition in the Data Division, binary search requires the ascending key clause:

5 course-elements occurs 15 times

indexed by course-index

ascending key course-ID.

# The Procedure Division entry would be this

Search all course-elements

end perform error-routine

when input-course-ID = course-ID (course-index)

Display course-name (course-index)

end-search

* search all performs a binary search (set is not needed)

* end refers to the end of the search being reached and no match being found - a potential error

situation

* when refers to when a match is found in the table

8.4.3.2 Sequential search

The Procedure Division entry for a sequential search operation does involve the use of the set command, to start the search at the beginning of the table

Set course-index to 1

Search course-elements

end perform error-routine

when input-course-ID = course-ID (course-index)

Display course-name (course-index)

end-search

* the set command is required by sequential search but not by binary search

* end refers to the end of the table being reached and no match being found - a potential error situation

* when refers to when a match is found in the table

8.5 Indexed files as alternative to

tables

# Indexed files are a good alternative to tables in many cases. To continue with the course table example, let's see how the table would be represented as an indexed file. The select entry for the indexed file might be:

Select course-file assign "course.dat"

organization indexed

access dynamic

record key course-ID

status course-status.

* assign specifies the external file name

* organization indexed states it is an indexed file

* access dynamic allows program to access data

# either sequentially or by using a specific key value

* record key specifies which field in each record of the file is designated as the key field - this must be set up when the file is designed

* status specifies a data element in Working-Storage to be used for storing the file's system status after each file operation

In the Procedure Division, the file would be searched by first opening it as input, then reading directly by providing the specific course-ID (key value) and executing a keyed read. If the read is successful a match has been found and a course description is immediately available as part of the record read. If the read is unsuccessful, perform an error routine:

Move input-course-ID to course-ID

Read course-file

key course-ID

invalid key perform error-routine

end-read

An advantage of using an indexed course file versus a table is that course ID's and descriptions can be part of a subsystem which allows for adding, modifying and deleting courses as needed using an interactive set of programs, and COBOL code needed for tables is eliminated from the program.

8.6 Chapter Summary

# Tables provide a means of arranging and accessing data within a program. Historically, in order to optimize storage on disks, it became a useful practice to use codes or IDs as part of each record in the primary input file, instead of names. The names themselves, oftentimes lengthy descriptions, would be associated with the codes by means of tables. There are many unique situations today that can make use of a table in a COBOL program.

There are three types of tables: a table can exist solely within a program as a relatively small internal table; a table can also be an internal table loaded with data from an existing file at runtime; and tables can be completely external to a program and as such may be referred to as relations. Relational databases are viewed as collections of tables or relations and are quite popular, including those that require set up and access using special structured query language (SQL) commands which can be called from a COBOL program, as well as stand-alone relational database packages.

Internal tables are hard-coded and difficult to maintain. When the table data exists outside the program, such as in a file, it can be loaded into the program when needed. An indexed file has greater flexibility in terms of maintaining the data using interactive software versus hard-coding the table. Faster processing can often occur for tables versus files in situations where data is to be accessed numerous times, assuming the amount of time needed to load the file initially is not prohibitive. It's also possible to just use indexed files and avoid the use of tables altogether.

If the table is not loaded from a file, it must be defined as a data element within the program. Immediately after this definition, redefines is used to assign new names to the same area, which can then be referenced by an index. There is no redefinition for tables loaded from files. For both methods occurs is used to identify the number of elements or rows and indexed by is used to declare an index to be associated with the table. Nested occurs may be used if the design merits it. An ascending or descending key clause is needed for the sort function, while ascending key is needed for search all to work.

The set command is used to set, add to or subtract from a table index value defined with the indexed by clause. It is also possible to define a table index as a regular numeric data object, in which case move would be used to set it to a specific number, and add and subtract would be used to increase or decrease the value. The set command can also be avoided completely by the use of the perform...varying...until option.

Table handling consists primarily of sorting and searching. COBOL's sort provides a straight-forward automatic sort and is used to sort tables as well as files. For sort to work with a table, the table definition must use the ascending or descending key clause in the Data Division. Searching can be accomplished by using if in conjunction with your own algorithms, search to conduct an automatic sequential search (which also requires the use of the set command in the Procedure Division), and search all for an automatic binary search (which requires the ascending key clause in the Data Division). The end clause for the search command refers to the end of the table being reached and no match being found (a potential error situation) and when refers to when a match is found in the table.

8.7 Review Questions

1. Write a table definition for a table to store

# all the Proverbs.

2. What is the purpose of loaded-flag in the

# example in section 8.3.2?

3. True or False: If a table index is defined as

a regular numeric data object, the indexed

by clause is still required.

4. What advantage is there in loading an

# indexed file into a program table?

5. Give an example of a relational database package you are aware of or listed in

# current literature.

6. List the two most significant table

# operations.

7. Design a table not mentioned in the text

# which might be used in a program.

8. How many ways are there to define a table

# in a COBOL program?

9. Assume course IDs are 6 characters while

# course descriptions are 30 characters.

# Calculate the total savings for a primary

# file consisting of 20,000 records, given a

# course file of 200 courses. How many

# bytes are saved by loading a table from an

# auxiliary file versus storing course names in the primary file?

10. What is the purpose of occurs?

11. What is the purpose of indexed by?

# 12. Write a suitable data declaration for table-

# index used in this example:

# move 1 to table-index

# display table-entry(table-index)

# 13. Write a suitable data declaration for table-

# index used in this example:

# set table-index down by 2

# display table-entry(table-index)

# 14. Write a table declaration for a table to be

# sorted from highest to lowest.

# 15. Write a table declaration for a table that

will use an automatic binary search.

16. What is one difference between binary

search and sequential search?

# Answers to even-numbered review questions.

2. In the event that the file has more than 50 elements, and the table definition has

not changed to reflect the additional States, an overflow error is avoided by

using loaded-flag.

4. Tables are stored in main memory, while files are stored on disk. Disk input/

output is slower than main memory access. Therefore, if a file must be accessed

more than once, having it stored as a table in main memory might be

advantageous.

6. Sorting and searching.

8. 2

10. Occurs specifies how many elements can be stored in the table.

### 12. 1 table-index pic 99.

14. answers may vary - must include descending key

16. answers may vary - binary search table must be in ascending sequence, binary

search is faster, sequential search starts the search at the beginning of the table

8.8 Projects

1. What happens when you use move, add and subtract with an object defined using the indexed by clause? Write a simple program to define and manipulate a table. Use move, add and subtract instead of set and write

down any resulting compiler errors. Complete the program correctly using the set command.

# 2. Write a simple program to sort a table. First display the unsorted table, then sort the table. Finally, display the sorted table.

# 3. Write a program to create 2-up labels.

Reference a table loaded from the states. dat file to get the state name. This involves

# using references to tables contained in the

COPY files labels.pro, states.ws, and load- sta.pro.

# 4. Design a program to create and store 2-up

labels in a table, sort them from highest to

# lowest, then print them.

# 5. Code and test a program to create and store

2-up labels in a table, sort them from highest

# to lowest, then print them.

6. Locate the sequential file cookies.seq and

# create a table definition for it. The file

# contains the names of four types of cookies

and their prices in cents (v99). Write an interactive program which first loads the file data into a table, displays the contents of the table, then lets the user type in the search

# key (one of either raisin, sugar, butter or oatmeal) and an amount. The program will

# then calculate how many cookies can be

# purchased for that amount and how much

change is left over. Provide controls in the

# event the user types in an amount less than

# the price.

# 7. Write a date conversion program using a

table, with the added capability of being

# called from another program. The program

# should accept the standard month-day-year

# format for a date and translate it to the 5-

# digit Julian date. For example, if the month is January and the day is the third the Julian

date would be 95003. Use the binary

search method with the table.

# 8. Write an interactive program to accept a

# negative number as input, check a table in

# the program and display the letter which

corresponds to the negative number. (HINT: Create the table of the letters which

# correspond to all negative digits for the

# system you are working with as an internal

table and use redefines.)

9. Change the Rpt-gpas program available on

# the student disk to use a table loaded from

the courses.new file. This will involve

# loading the course file once and using search

# to locate the required course informational each time. Create two versions of your

program, one using sequential search and the other version using binary search.

# 10. Write an interactive program to accept a

# User-ID and password, where the password

# is not seen when typed by the user (no-

# echo). Create an indexed file consisting of

# 5 User IDs and passwords, which must be

# loaded into a table in the program. Display

# the message "Invalid User-ID/Password"

# whenever either the User-ID or password

# are not found in the table.
CHAPTER NINE

Return to contents

Sequential File

Maintenance

1 John 2:17

And the world is passing away, and

also its lusts; but the one who does

the will of God abides forever.

9.1 Introduction

Files, where data is stored, are output from one process or system of processes and input to another process or system. Both good and bad data can exist in a file, so effective controls must be used to ensure that only good data is included. The first files were stored as a sequence of records on paper tape and cards, the records consisting of fields. These sequential files were maintained by using a procedure similar to the one described in this chapter, the process of merging transactions with an original master file to create a new master file.

Files today are commonly stored on hard disks or CDs/DVDs where data can be accessed quickly and efficiently using indexes. Indexed files were discussed in chapter 4 and have two components - the data component and the index component or search key. Sequential files can be viewed as MS-DOS text files and are just the data component of an indexed file, but with no index. Lacking a separate index file, the order of data is determined by the order in which the data is originally written to the file, or by a sort utility rearranging the records. For data to be sorted however, a field must be specified as a unique key field in each record.

Sequential file maintenance can be done either with sequential files; or with an indexed file being used as the transaction file in sequential access mode, and a sequential file being used as the master file. There are some older sequential file systems in use, which may have a significant cost to convert to a new file format compared to just continuing to use them in their present state. These older systems will remain until a need arises and/or they receive priority to be converted to a more contemporary format.

For indexed master files, whenever there are an extremely large number of transactions which need to be processed, such as insurance claims, payroll transactions, etc., then maintaining these files sequentially may be more effective than using direct access. When an indexed file is being updated in a sequential access mode, the sequential read from chapter 4 can be used in conjunction with other indexed file commands. In this case, only sorting may be applicable from this chapter if a) the transaction file is sequential, or b) a different sequence is needed than what the indexed files automatically provide.

We know that one day the world as we now know it will pass away, including indexed files, sequential files, even COBOL itself. The Bible teaches that knowledge will pass away,

1 Corinthians 13:8b (NIV)

...where there are tongues, they will be stilled;

where there is knowledge, it will pass away.

There will be a new heaven and a new earth,

Revelation 21:1 (NIV)

Then I saw a new heaven and a new earth, for the first heaven

and the first earth had passed away, and there was no longer any sea.

It is therefore doubtful that computers will be a part of God's plan for eternity. The sun will not even be needed because the light of our Lord will shine bright

Revelation 21:23

The city does not need the sun or the moon to shine on it,

for the glory of God gives it light, and the Lamb is its lamp.

In spite of what we know will transpire at some future point in time, we don't know when these events will occur. Therefore, we must be prepared to continue to do a good work in this present age, working not only with the more contemporary indexed files and relational databases, but also doing sequential file maintenance, that we might be lights for Christ in this dark world in order that others might be led to the cross. And of equal or greater importance, we must be prepared to meet the Lord face to face. Are you ready?

9.2 Process Overview

The main components of a complete system to update or merge sequential files include these functions, which are generally separately compiled programs:

edit

sort

merge

The edit operation involves using control processes, which were introduced in chapter 6, to make sure only valid transaction data enters the system. The sort operation, introduced in chapter 8 for use with tables, may use the COBOL sort command or an operating system sort utility and is also useful for generating reports in different sequences. The merge operation requires that a sorted transaction file be matched against a sorted master file to produce a new sorted master file.

Records may be added, changed or deleted in the maintenance process. Records to be added are actually merged in the proper location in the new master file. Records to be changed are merged from the transaction file, replacing the original master file records in the proper location. Records to be deleted are simply not written to the new master file, so technically there is no merge involved for the delete operation, but rather an inverse merge.

For the three distinct merge transactions, add, change and delete, the transaction file must include a code to represent each one of these transactions. The prototype maintenance program presented in section 9.5 uses "A", "C" and "D" to make the program easier to understand, although numeric codes such as 1, 2 and 3 may be used in some systems instead.

For the entire process to work, each record must consist of a unique key field similar in concept to the primary key field of an indexed file or the search key of a table. This field is used for the sorting process as well as the merge process. Examples of key fields might be employee number, social security number and part number.

9.3 Edit Operation

Interactive programs to perform data validation were presented in chapter 6. These may be used to create indexed transaction files for the sequential update process, and this method is to be preferred whenever possible. The concept of a batch data validation program was also briefly presented in chapter 6. It is essential that controls be provided in both interactive and batch edit programs to ensure that invalid input data is rejected.

As a review of the controls from chapter 6, the things to check for in any edit program include

numeric checking

checking numbers for zeros

checking character fields for spaces

checking for specific values, including valid transaction codes

checking for duplicate or missing key fields

Recall that for interactive programs the Screens Facility may be used to filter out certain errors, while batch programs generally need to check for all of these potential errors.

The editing process to create a sequential transaction file in batch mode will accept transaction data, check each field using specified ranges of acceptable values, perform other required validation and verification, then create an error-free file. An error list should also be provided so the user may make needed corrections to any erroneous transaction data.

Diagram of batch editing process

9.4 Sorting Files

We are reminded from chapter 1 that our God is a God of order, and order is highly valued within a COBOL program itself. Writing a well-ordered COBOL program is good. This has been illustrated within each program code segment and program example presented throughout this text. When dealing with the process of updating sequential files, order is of supreme importance. Without the transaction and primary files being in the same sequence, the update process will not even work.

It is also often valuable to sort a file in a variety of sequences prior to generating a series of reports. For example, an inventory system may require reports produced in different sequences such as item number sequence, department sequence and quantity sequence.

Sorting tables was presented in the last chapter. Sorting files is slightly more complicated, depending on the method selected. You can choose to use an operating system utility to perform a sort. Both mainframe and PC systems offer sorting capabilities with varying degrees of complexity involved. Consult your system's manuals for details on using sorting utilities in your particular environment.

9.4.1 Sorting Prior to Updating

If a batch or interactive program is used to perform data validation to create an indexed transaction file for the sequential update process, where the primary file is also an indexed file being processed in sequential access mode, then sorting is usually not required unless a different sequence is desired than what the primary and alternate record keys automatically provide in the indexed files.

If a batch program is used to perform data validation to create a sequential transaction file for the sequential update process, where the primary file is strictly sequential, then sorting is required to get the transaction file into the same sequence as the master file. Generally, a sequential master file is always in the correct sequence and does not require sorting.

Diagram of sorting process for a transaction file

Please note that if the files are not in the same sequence, the merge operation described in section 9.5 will not be completely successful. If a problem with sequencing occurs during the merge operation and the problem is discovered after the new master file has replaced the previous one, the original master file will need to be restored from the most recent backup copy. Retaining copies of all files for a prescribed period of time is essential to avoid the possibility of costly manual data recovery.

Implementing the sorting process is fairly simple in COBOL. You need to specify the sequence and use correct syntax. The sort command will then automatically rearrange the data according to the sequence you desire. For sorting prior to a merge operation, some typical sort fields might be employee number, inventory item code and student ID, depending on what key field is used in the merge.
9.4.2 Sample Sort Program

Identification Division.

Program-ID. SortData.

* A program to sort an inventory file by item number.

Environment Division.

Input-Output Section.

File-Control.

Select SD-File assign "sortwork".

Select Input-File assign "inventry.dat"

organization line sequential.

Select Output-File assign "sorted.dat"

organization line sequential.

Data Division.

File Section.

SD SD-File.

1 Sort-Record.

5 SR-item-number pic 9(7).

5 pic x(155).

FD Input-File.

1 pic x(162).

FD Output-File.

1 pic x(162).

Procedure Division.

Sort SD-File

ascending SR-item-number

using input-file

giving output-file.

Stop Run.

The SD entry specifies a work area for the COBOL sort to use in the sorting process. This area must be specified when sorting files. The size of the corresponding record must correspond to the size of the input file record, which is the same as the output file record size. The select entry for the SD does not require an organization clause.

The only field or fields needed to be named in the sort program are those directly involved in the sort process. These named fields are part of the SD record description and appear in the Procedure Division as shown above. The placement of the key field within the record must correspond to its actual location in the data. It is best to use the COPY file for the record description as part of the SD entry. More than one field may be used for the sort, which is described in the next section. In this example, the file is sorted by inventory item number in ascending sequence.

Special Note: In some instances your sort program may also need to include the statement $SET CALLSORT"EXTSM" in line 1 column 7 at the beginning of the program. In certain cases, this may be needed for sorting files when running your program as an executable file outside of the Workbench environment.

9.4.3 Sorting for Reporting

Sorting prior to generating a report may be done to either a sequential or an indexed file. Although not directly related to sequential file maintenance, it is mentioned here since it is no different in form than sorting prior to a merge.

A separate sort program is required for each sequence that is desired. Referring to the inventory example mentioned at the beginning of the sorting section, having all the item numbers in ascending sequence is desirable. In the event the computer is off for any period of time the inventory information is readily available. Having a report arranged by department could be useful for a retail application, so each department head could have information related to their specific products. Another report might be arranged by cost codes for the people in accounting. Exception reports could be produced sorted by "quantity on hand" showing overstocked items, or sorted by "date last used" showing obsolete items.

The sequence for reporting may be ascending or descending, depending on the desired outcome. Each field may be ordered as either ascending or descending as illustrated here

Sort SD-File

ascending store-number

descending salesperson-dollars

using input-file

giving output-file.

In this example the final sequence would have all stores grouped together, with the sales-persons ordered within each store from the highest sellers to the lowest sellers. Such a report is especially useful for employee of the month selection.

9.5 Merge Operation

A merge may consist of adding new records, changing existing records and deleting records no longer needed. A new primary file is created, containing all the additions and changes, which replaces the previous master file via an operating system COPY command. The transaction file is unchanged. The transaction file and a copy of the original master file may be used to rerun the merge process in the event of unexpected results or disasters occurring.

The merge operation acts on the two sorted input files to produce a sorted output file and an error report or listing. The merge works by comparing a key field in the transaction file with a corresponding key field in the master file.

Diagram of merge process

The following is the high level component of a prototype merge program, which can be tailored to suit most systems requiring a sequential update process:

Identification Division.

Program-ID. BatchMrg.

* prototype software to merge

* sequential transaction and old master files

* into a new sequential master file

Environment Division.

Input-Output Section.

File-Control.

copy trans.env.

copy oldmast.env.

copy newmast.env.

Select error-report assign to "errors.mrg"

organization line sequential.

Data Division.

File Section.

copy trans.fs.

copy oldmast.fs.

copy newmast.fs.

FD Error-Report.

* print on PC printer in condensed font

1 A-line pic x(124).

Working-Storage Section.

1 Transaction-end-of-file pic 9 value 0.

88 eof-transaction-file value 1.

1 Old-master-end-of-file pic 9 value 0.

88 eof-master-file value 1.

copy errormsg.ws.

Procedure Division.

perform set-up

Perform until OMR-Unique-Identifier = high-values AND

TR-Unique-Identifier = high-values

perform getNextMasterRecord

Evaluate TR-Transaction-Code

When "A" perform addRoutine

When "C" perform changeRoutine

When "D" perform deleteRoutine

When other perform transaction-error-routine

end-evaluate

perform ReadTransactionFile

end-perform

perform wrap-up

stop run.

copy update.pro.

copy merge-io.pro.

The Procedure Division consists of the top-level module and two process objects all available on the student disk. The top-level module gets records to be merged, along with the transaction code to trigger one of the three update processes. It has a selection routine for choosing one of the add, change or delete functions. The end of the top-level process is triggered when the end of both files has been reached. Notice that high-values are used in the end condition. High-values is a special COBOL name representing the largest or highest character values on the computer system (hexadecimal F's) just as low-values represent the lowest possible character values on the computer system (hexadecimal 0's), which are less than zero.

One of the two process objects is used to carry out inputting data, along with some outputting, and is contained in merge-io.pro. The other is used to handle updating and is contained in update.pro. The first process object contains the functions which actually read the transaction and master files, along with a routine getNextMasterRecord which also copies unchanged master records.

The getNextMasterRecord routine continues until the key field for the master record is equal to or greater than that of the transaction record. If the end of the transaction file is reached first, high-values are placed into the transaction key field for the duration of the processing. Since high-values represent the highest character values on the computer system (hexadecimal F's), the possibility of inadvertently comparing this false value with a real value within the data file is virtually eliminated and the remaining master files records are correctly copied to the new master file. If the end of the master file is reached first, high-values are placed in the original master file key field and any remaining transactions can be processed.

Further review of the input/output object merge-io.pro is left to the interested reader, with investigation of one part left as a project at the end of the chapter. The second process object is covered in more detail in the following paragraphs in terms of its three components to add, change and delete records.

9.5.1 Add Component

The following add process is contained in the process object called update.pro:

addRoutine.

If OMR-Unique-Identifier = TR-Unique-Identifier

Write a-line from duplicate-record-key-message

Write a-line from transaction-record

else

Write new-master-record from TR-transaction-data

end-if.

The key fields of the master record and transaction record are compared in this routine. Comparison is the primary ingredient in a sequential file maintenance operation. The desirable situation for an add operation is that the two are not equal. If they are equal, this implies the record already exists in the master file and therefore trying to add it again is inappropriate. It may be that the key field was incorrectly entered and the rest of the data record is correct, or it may be that someone is trying to add the same record a second time. The user must examine the data to determine how to correct the problem. Remember that if the input data files are not in the same sequence the entire process will fail.

The else part above signifies that the two key fields are not equal. This means the key field of the transaction record, when it reaches this specific point, is less than the key field of the master record. This must be true by virtue of how the input is obtained, along with the fact that the input files are in the same sequence. (Can you create test cases to prove that this must be true?)

It turns out that getNextMasterRecord in merge-io.pro continues until the key field for the master record is equal to or greater than that of the transaction record. Therefore, at the else in the add component the transaction record key is less than the master record key. When this event happens, the new record is written, the transaction file is read again in the top-level module, and adding can continue as long as

a) the transaction record key is still less than the

master record key, and

b) the transaction code is equal to "A".

9.5.2 Change Component

The following change process is contained in update.pro:

changeRoutine.

If OMR-Unique-Identifier > TR-Unique-Identifier

Write a-line from no-master-for-change-message

Write a-line from transaction-record

else

Write new-master-record from TR-transaction-data

perform ReadMasterFile

end-if.

This change module assumes that an entirely new record is provided, including fields that are not being changed. A more desirable situation is to have only those fields that are being changed be provided as part of the transaction, with the rest blank. Then an additional function in the program would copy the original data before moving the changed fields. That process requires an additional perform statement before the write command shown above, along with the extra function itself.

The key fields of the master record and transaction record are compared, in a slightly different fashion than in the add component. The desirable situation for a change operation is that the two records are equal. If they are not equal, this implies the record does not exist in the master file and therefore trying to change it is incorrect. It may be that the key field was incorrectly entered and the rest of the data record is correct, or it may be that someone is trying to change a record that has not yet been added. The user must examine the data to determine how to correct the problem.

The else part above signifies that the two key fields are equal and the record can be changed. The key field of the transaction record when it reaches this specific point cannot be greater than the key field of the master record, for the same reason presented in section 9.5.1. The routine getNextMasterRecord in merge-io.pro continues until the key field for the master record is equal to or greater than that of the transaction record.

Therefore, at the else in the change component, the transaction record key is equal to the master record key. When this event happens, the new record is written (changed), another master file record is read to replace the one that was changed, the transaction file is read again in the top-level module, and changing can continue as long as

a) the transaction record key is still equal to the

master record key, and

b) the transaction code is equal to "C".

9.5.3 Delete Component

The following delete process is contained in update.pro:

deleteRoutine.

If OMR-Unique-Identifier > TR-Unique-Identifier

Write a-line from no-master-for-delete-message

Write a-line from transaction-record

else

perform ReadMasterFile

end-if.

This delete module is similar to the change module, except that no record is written to the new master file. When the two key fields are equal, no record is written, another master file record is read to replace the one that was effectively deleted, the transaction file is read again in the top-level module, and deleting can continue as long as

a) the transaction record key is still equal to the

master record key, and

b) the transaction code is equal to "D".

9.6 Chapter Summary

Data was processed on the first computers through the use of sequential files. They still serve a useful purpose today. Sequential file maintenance can be done solely with sequential files; or with an indexed file being used as the transaction file in sequential access mode, and a sequential file being used as the master file. For indexed master files, whenever there are an extremely large number of transactions which need to be processed, such as insurance claims, payroll transactions, etc., then maintaining or updating files sequentially may be more effective than using direct access and commands from chapter 4 still apply.

The sequential maintenance process for sequential files is not yet automatic in COBOL, requiring several programs run in series, oftentimes with a good deal of code involved in both the edit and merge programs. Effective controls must be used to ensure that only good data is included, and the input files must be in the same sequence. The sort program is generally quite small, or a systems software utility is used. Sorting is also useful when reports are required in a variety of sequences.

Records may be added, changed or deleted in the maintenance process. Records to be added are actually merged in the proper location in the new master file. Records to be changed are merged from the transaction file, replacing the original master file records in the proper location. Records to be deleted are simply not written to the new master file. The transaction file must include a code to represent each transaction. The sample maintenance program shown in the text and available on the student disk uses "A", "C" and "D" to make the program easier to understand, although numeric codes such as 1, 2 and 3 may be used instead.

For the entire process to work, each record must consist of a unique key field similar in concept to the primary key field of an indexed file or the search key of a table. This field is used for both the sorting process and the merge process. Since the merge process involves comparing these key fields, it is useful to incorporate high-values in the end condition because they represent the highest character values on the computer system (hexadecimal F's) and therefore the possibility of inadvertently comparing the false value with a real value within the transaction data file is virtually eliminated, allowing for a clean finish every time.

We know that one day the world as we now know it will pass away, including indexed files, sequential files, even COBOL itself. The Bible teaches that knowledge will pass away,

1 Corinthians 13:8b (NIV)

...where there are tongues, they will be stilled;

where there is knowledge, it will pass away.

And there will be a new heaven and a new earth,

Revelation 21:1

Then I saw a new heaven and a new earth, for the first heaven and the first earth had passed away, and there was no longer any sea. (NIV)

In spite of what God shows us will happen at some future point in time, we don't know when these events will occur so we do our best at what we are capable of doing. Therefore, rejoice in the Lord, serve Him with great joy until that day. And may God richly bless you in return.

9.7 Review Questions

1. Discover another Bible verse to indicate

that computers will pass away.

2. What are the three components of a

sequential file maintenance system?

3. How are records added to a sequential file?

4. Do records in the master file need to be

physically sorted prior to an update?

5. How are records changed in a sequential

file?

6. How are records deleted from a sequential

file?

7. List five things a batch validation program

should check for.

8. What are the outputs from a batch edit

program?

9. Under what conditions is sorting required in

a sequential file maintenance process?

10. At what point is sorting performed?

11. How is sorting tables different from sorting

files?

12. Does the select entry for the SD in a sort

program require an organization clause?

13. Identify the problem which exists with this

code to be used for a sort operation.

File Section.

SD SD-File.

1 Sort-Record.

5 SR-item-number pic 9(7).

5 pic x(155).

FD Input-File.

1 pic x(164).

FD Output-File.

1 pic x(160).

14. What fields need to be named in a sort

program?

15. How many distinct functions are evident in

the BatchMrg program described in this

chapter?

16. What significant relationship must be true

when the else statement is reached in the change component?

17. What significant relationship must be true

at the point the else statement is reached in

the add component?

18. What significant relationship must be true

when the else statement is reached in the

delete component?

19. Given that low-values represent the lowest

possible values on the computer system - hexadecimal 0's, which is less than zero - in what situations might this prove useful?

Answers to even-numbered review questions.

2. edit, sort, merge

4. Not usually.

6. Records are deleted by not writing them to the new master file.

8. The unsorted transaction file and an error list.

10. after the edit cycle when the users have corrected all the transaction

data errors, and before the merge

12. No

14. Only those directly involved in the sort process

16. change component - the key field of the transaction must be equal to

that of the master record

18. delete component - the key field of the transaction must be equal to that

of the master record

9.8 Projects

1. Compile, link and run the merge program

provided on the student disk.

2. Create a new set of data for the merge

program. Prepare a test plan to thoroughly

test the merge program and have your new

test data fulfill all the requirements in your

plan. Be sure data files are in the same

sequence and test the merge program

completely. Summarize results in a brief

paper.

3. Improve on the merge program's error

report by adding headings and using Report

Writer.

4. Design a file and a batch data validation

program to verify that data is correctly

added to the file. Use any available editor to type in several records, including errors,

and test your program.

5. Rewrite the sequential file update prototype

program using different function names and

adding comments for each function to high- light the processes. Compile and test your

resulting program, comparing your results

with those of the original program.

6. Write a sort program to sort the states.dat

file available on the student disk in

descending sequence from highest to

lowest.

7. Simulate an indexed file by creating a

separate sequential file of key fields for a

given main sequential file. Design a simple

main sequential file and a set of processes to

create this and its corresponding sequential

file of key fields. How would you design an

update process to work for this simulated

indexed file? Present your ideas in a short

paper and be prepared to present them in

class. Be sure to address at least these

specific questions in the paper:

How could you add a record efficiently without reading the

main sequential file?

How might the change process work?

How could the delete component work without accessing the main sequential file?

Is this a good method to use?

8. Create a new function that requires the user

to provide only those fields which will be

changing as part of the transaction data file,

instead of the entire record including any

unchanging fields.

Design a simple data file to use with the

prototype merge program provided on the

student disk and include references to your

new routine in the program. Adequately

test the resulting new program using your

own test data and summarize your results

in a brief paper. Include a brief description

of the new function along with user

instructions for creating a change

transaction.

9. What happens if the >= is just > in this code segment?

* merge-io.pro - referenced by batchmrg.cbl

getNextMasterRecord.

Perform until OMR-Unique-Identifier >= TR-Unique-Identifier

OR eof-master-file

Write new-master-record from old-master-record

Read old-master-file

end move high-values to OMR-Unique-Identifier

move 1 to old-master-end-of-file

end-read

end-perform.

First run the program correctly using the

data supplied on the student disk and save

the results under a new name. Then

recompile the program with the single

change suggested above. Compare the first

output file with the corrupted one visually

and with the MS-DOS fc command.

Determine precisely what happens and

summarize your results in a short paper

# describing the process error in detail.
Part 4

Return to contents

Appendices

Micro Focus has improved its products since this text was originally written so be sure to reference those aspects of the product currently available for your operating system at https://www.microfocus.com/.

Appendix A - Using Workbench

1. If running on a network and it's required by your system administrator, run the

initialization routine for your system. For a

typical system, be sure the i:\net\bat\

cobinit.bat file is part of your individual

h:\docs\netinit.bat file either by copying it

in or by using MS-DOS Call. The MS-DOS

Edit command can be used to create or

modify the h:\docs\netinit.bat file.

2. Activate Workbench by typing wb at the

network MS-DOS prompt.

3. Select F2 (Edit) to begin creating or modifying a program.

4. If access is needed to an already existing

program, select Alt-F3 within F2 to load a

file. Either type the file name, including the

path, or select F2 within Alt-F3 to display a

directory of files.

5. When changes are complete, type Alt-F4

within F2 to save the file.

6. Perform syntax checking by pressing F2

twice within F2, followed by the Enter key.

7. If there are syntax errors they're displayed

one at a time.

8. Once the syntax is correct, compile the

program by using F5 (Compile) from the

main menu. This creates either of two

possible files, .gnt or .obj. The .gnt can be

run within the Workbench environment.

The .obj must be linked using Alt-F7 (Link)

from the main menu.

9. Once the compile has worked, and the link if

using .obj files, the program can be run

using F6 from the main menu. Numerous

run-time errors can occur even when the

program has been checked and compiled

correctly.

Appendix B - Compiling and Linking

When a source program has been typed in, it must be checked for syntax errors and compiled. The syntax checking process is a process of finding spelling and grammatical errors and can be started by visually inspecting the code. Syntax checking is generally performed automatically either prior to or along with the compilation process in most development environments. Once syntax checking has been completed with no errors, then the program may be compiled.

The Micro Focus compiler produces object code. This has the extension .obj and is only executable when it has been linked with system files. The linking process creates an .exe file which can be run in the operating environment in which it was prepared (MS-DOS, Windows, etc.).

Programs may be compiled to .obj code from within Workbench or in a single step by using the COBOL command at the operating system level.

Link files for the sample Interact application need to include the menu and the infilter mouse-handling program as shown here:

rem parts.bat:

rem Compile and Link the interface

rem model for use in Win 10

cobol menu;

cobol infilter;

cobol parts-01;

cobol parts-02;

cobol parts-03;

cobol parts-04;

cobol parts-05;

cbllink menu+infilter+parts-01+parts-02+parts-03+parts-04+parts-05

Appendix C - Workbench Screens Tool

Access Screens by pressing Alt F2 from the main Workbench screen.

The next thing to do is provide a name for the screen, to be referenced with the accept and display commands. Press ALT F10 to accomplish this task.

Experiment with colors by pressing Alt F9 (attribute palette). This is used to change background/foreground colors. Use arrows to select a color combination from the palette and F7 to set. Then use F6 from the top level to roll through the color combinations specified.

Use arrow keys to move around the screen, type labels and specify fields where you want them. The ^ (shift 6) key is used to identify field location and length. For instance, ^^^^ specifies a field of length 4. To specify field attributes, use F3. Within this option, F2 will select/unselect clauses while F4 is the number/ character toggle.

To move labels or fields around on the screen or rearrange them use F2 to mark the text then F7 to cut and F2 to paste.

Alt-F5 automatically generates COBOL code, which includes a .ss file for the Screen Section and a skeleton program. If any manual changes have previously been made to the .ss file, be sure there is a backup before proceeding in order to to reinstate them. Within this option, the F6 toggle to turn blank screen on is helpful for applying colors properly. F2 generates the .ss file and F3 generates a skeleton program.

When ready to save work, use Alt-F4. Alt-F3 can be used to load a previously saved screen.

Appendix D - Workbench File Loader

Creating and Using Profiles

Access Workbench File Loader (WFL) by pressing F9 from the main Workbench screen. The next screen that appears (WFL screen) has blanks to be filled in for two files. The first file could be a sequential file to be converted to an indexed sequential file, or the file could be a mainframe EBCDIC file to be converted to a PC ASCII file. Numerous other possibilities exist.

The case we are concerned with here is creating an indexed file from a sequential file which has previously been created using any commonly available text editor and saved in ASCII format.

First enter the name of the sequential file which already exists. Then Tab to the Type entry. Select line sequential from the list. Continue using Tab as you fill in the rest of the file details. Tab past ASCII and IEEE, accepting those values by default. For record length, enter the exact length of a typical record in both the Min and Max fields.

This gets to the second file prompt. Enter the name for the indexed sequential file (different from the name of the first file). Tabbing through, choose indexed sequential, fixed length as the file type, enter the record length, along with the primary key field starting position for a typical record and length of the primary key field.

Prime key split should be left as N for No. If creating alternate keys, press F5 to specify their location and length.

At this point, save the information entered for possible future use. It will be called a profile, use F4 to assign a name and store it on a disk. It will automatically be given file extension .pro.

To create a new indexed file, press F10 (convert).

If there are ever problems with an indexed file, there is a Rebuild utility (F9 on the WFL screen) which restores indexes (.idx files) or both indexes and data. It is better however to backup your indexed file and its corresponding index before doing any updates to the data, in the event a program fails and there is a need to restore previous data. Create backups on a regular basis, or as often as testing requires. This can help minimize the need for the Rebuild utility except in cases where a system crash occurs between backups.
About the Author

With an earned M.S. in Computer Science and over 40 years experience developing software and databases, managing projects and teaching, Wes Sweetser "retired" in 2018.

In his spare time he and his wife enjoy bike riding and spending time with family. They draw their strength from the Lord Jesus Christ. At age 30, Wes realized that Jesus was indeed risen from the dead, having believed the testimony of the 500 (1 Cor 15:6), and received from Lord Jesus the great gift of eternal life along with the Holy Spirit. It's been a wonderful ride since that day!

The Approved Workman Series

COBOL for the Approved Workman is available online from Smashwords.

C# for the Approved Workman, is available online from Smashwords.

Future Books in the Series

Visual Basic for The Approved Workman, will be available online from Smashwords. Expected publication date 2019.
