Visual Cobol
Visual Cobol
COBOL
Course Handbook
Visual COBOL
Contents
01 COBOL Course Introduction
11
Module Summary
21
Introduction
12
Quick Quiz
21
Module Objectives
12
22
Student Assumptions
12
Introduction
23
Course structure
12
Module Objectives
23
13
Programming Layout
23
COBOL Features
13
Identification Division
26
14
Environment Division
27
14
Data Division
27
What is COBOL?
14
File Section
27
Class setup
15
Working-Storage Section
27
Samples
15
Linkage Section
29
16
Procedure Division
29
Module Summary
16
Use of periods
30
Quick Quiz
17
30
02 COBOL Introduction
18
Module Summary
30
Introduction
19
Exercise
30
19
31
19
04 Data Representation
32
Divisions
19
Introduction
33
Simple Example
20
Module Objectives
33
Exercise
21
Defining Data
33
Module Objectives
Index
X Close
Quick Quiz
Back | Next
Visual COBOL
Data Names
34
Simple Example
51
34
Statement Termination
52
Reserved Words
35
55
Data Hierarchy
35
DISPLAY verb
55
36
ACCEPT verb
55
38
MOVE verb
56
Exercise 1
39
PERFORM Verb
58
39
Using Comments
62
40
STOP Verb
63
Usage DISPLAY
41
63
Usage BINARY
41
67
42
Module Summary
68
43
Exercises
68
Figurative Constants
43
69
45
06 Best Practice
70
46
Introduction
71
46
Module Objectives
71
Quick Quiz
Exercise 2
47
71
47
Structure Diagrams
73
Module Summary
48
Example
74
48
Truth tables
76
Quick Quiz
48
76
05 Basic Verbs
50
Module Summary
78
Introduction
51
Exercise 1
78
51
Exercise 2
79
Module Objectives
Index
X Close
Back | Next
Visual COBOL
Exercise 3
80
Module Objectives
96
Quick Quiz
81
The IF statement
96
82
Condition phrases
97
Introduction
83
101
Module Objectives
83
Simple EVALUATE
101
83
Condition EVALUATE
102
84
Compound EVALUATE
103
Connecting Files
84
103
Identifying Files
84
Infinite loops
103
85
Module Summary
105
86
Exercise 1
105
86
Exercise 2
105
86
106
Exercise 1
90
106
90
107
Quick Quiz
107
90
91
09 Data Manipulation
108
Points to remember.
91
Introduction
109
92
Module Objectives
109
Module Summary
92
Manipulating Data
109
Exercise 2
93
Exercise 3
93
Arithmetic verbs
110
Quick Quiz
93
115
08 Decision Logic
95
Introduction
96
INSPECT Statement
Index
X Close
109
Back | Next
116
116
Visual COBOL
STRING Statement
118
UNSTRING Statement
119
134
Reference Modification
120
Introduction
135
Module Summary
120
Module Objectives
135
Exercise 1
120
Edited Fields
135
Exercise 2
121
Leading Zeros
135
Exercise 3
121
136
Optional Exercises
124
137
Quick Quiz
125
137
10 Repeating Data
126
Currency symbols
138
Introduction
127
139
Module Objectives
127
139
127
Insertion characters
139
140
Quick Quiz
132
128
Look up tables
129
141
Exercise 1
129
142
Indexes
129
142
Subscripts v Indexes
130
144
130
Module Summary
144
Exercise 2
130
Exercise
144
131
146
Quick Quiz
Multi-dimensional tables
131
147
131
Introduction
148
Module Summary
132
Module Objectives
148
Exercise 3
132
148
Index
X Close
Back | Next
Visual COBOL
149
Exercise 2
169
Random Access
151
Exercise 3
169
Exercise 1
153
Module Summary
170
156
Quick Quiz
170
157
14 Screen Handling
171
158
Introduction
172
158
Module Objectives
172
158
172
Use of Declaratives
160
173
Module Summary
160
174
Further Exercises
161
Module Summary
174
Exercise 2
161
Quick Quiz
174
Exercise 3
161
15 Database Use
175
Exercise 4
161
Introduction
176
163
Module Objectives
176
13 Modular Programming
164
Database connection
176
Introduction
165
Sample database
176
Module Objectives
166
166
Microfocus Wizard
185
167
Module Summary
186
Call Nesting
167
Exercise
187
Passing parameters
167
187
168
188
Exercise 1
168
Introduction
189
169
189
Quick Quiz
Index
X Close
Quick Quiz
Module Objectives
Back | Next
Visual COBOL
189
Introduction
206
190
206
Class Structure
190
Module Objectives
206
191
206
Exercise 1
191
Load project
207
Exercise 2
192
Project Properties
207
Exercise 3
194
Main Program
208
Exercise 4
197
Form Program
208
Exercise 5
198
Designer view
209
Module Summary
198
Form1.designer.cbl view
210
Quick Quiz
199
Legacy Program
211
17 .NET Introduction
200
Toolbox view
212
Introduction
201
213
Module Objectives
201
201
213
201
213
Evolving demonstrations
.NET Overview
215
203
215
203
Add a Label
216
203
216
203
217
203
217
Module Summary
203
Quick Quiz
204
Module Summary
219
18 Windows Forms
205
Quick Quiz
220
Index
X Close
Back | Next
Visual COBOL
19 Web Forms
221
240
Introduction
222
241
Module Objectives
222
222
Add a client
242
223
243
224
244
225
244
227
Module Summary
244
227
Quick Quiz
245
229
21 Mixed Languages
246
Module Summary
230
Introduction
247
Quick Quiz
230
Module Objectives
247
20 Web Services
231
247
Introduction
232
248
Module Objectives
232
252
232
253
233
255
256
242
233
234
235
Module Summary
257
235
Exercise 6 - Using C#
257
238
Quick Quiz
258
257
238
259
238
Introduction
260
239
260
Index
X Close
Module Objectives
Back | Next
Visual COBOL
260
Inheritance
281
260
Casting
283
261
Interfaces
284
261
Class names
286
262
Intrinsic types
287
266
288
Exception Example
Module Summary
267
Reflection
289
267
What Next?
289
Quick Quiz
267
Further Reading
290
23 Course Conclusions
268
291
Course Follow-on
269
Introduction
292
Course Examination
270
Module Objectives
293
271
293
Introduction
272
Report writing
294
272
294
272
Local-Storage Section
294
Objects
275
Intrinsic functions
294
276
Library routines
295
Constructors
277
296
Recap
278
Properties
278
Exercise
307
Method Visibility
279
307
Local Data
280
Recap
280
280
Data Types
Index
X Close
296
Module Summary
Back | Next
Visual COBOL
Forward
Welcome. We are glad you have selected Visual COBOL: Modern COBOL for the Next
Generation. We believe in the unique power and flexibility of the COBOL language.
Today, 85% of the worlds business applications and 70%
of business data processing is dependent on COBOL.
COBOL is everywhere and touches our daily lives in many
ways. Did you know that the average person interacts with
COBOL at least 10 times per day and is typically unaware.
The perfect example of this interaction is at the ATM. Each
of us, who withdraw money from our banking provider,
interacts with COBOL. Yes, there is a fancy, interactive
interface at the ATM, but behind the scenes, COBOL is
the driving engine, delivering account balance
information, depositing funds, or withdrawing money
from your account.
But just as ATM interfaces have changed, so has the
enterprise application development market. COBOL,
once considered, the exclusive enterprise language for
business is now challenged by more modern languages
such as C#, or Java. Todays business applications are
moving forward, seeking to harness new technologies.
So, what does this movement mean for COBOL? Can
the COBOL language evolve and embrace these next
generation technologies as well?
Its time for a step change forward - Its time for Visual
COBOL.
Index
X Close
Back | Next
10
Visual COBOL
COBOL Course
Introduction
Index
X Close
Back | Next
11
Visual COBOL
Introduction
This book takes you through the structure and features of the COBOL programming language.
It starts with traditional COBOL and then moves through the implementation of Object Oriented COBOL in the
1990s and then on to more recent developments; providing fully featured Visual COBOL using all the powers of the
Microsoft.NET framework.
It will be shown how COBOL is completely integrated with all the other .NET languages such as C# and VB .NET.
Examples will be provided, showing how other languages can be used to fully integrate with legacy COBOL code,
as well as more modern COBOL applications.
The course will not contain every single detail of COBOL coding but will cover all the major language features that
you will most commonly be using. At the end of the course, there is an appendix, which will list further features of
COBOL and point to other reading material to extend your knowledge.
Module Objectives
At the end of this module you will be familiar with:
You will also have set up the sample programs and projects that you will use during this course. In addition you will
have configured a number of settings in Visual COBOL which you will need.
Student Assumptions
It is assumed that you, the student:
Are comfortable with the use of an Integrated Development Environment (IDE) such as Visual Studio.
Course structure
During each module there will be a series of student exercises. The end of each module there will be a short quiz
with mainly multiple-choice questions (Or True/False questions). The answers to these quiz questions are provided
to your instructor, in a separate document, which can be given to you, as required.
At the end of the course, there will be a final course examination, which is also mainly a set of multichoice questions.
A set of answers are also provided for the instructor.
At the end of the regular course materials you will find 2 Appendices:
Appendix 1 Contains a refresher of Object Oriented COBOL programming with some additional description
and features that have not been fully covered in the course.
Appendix 2 Contains descriptions of some less used COBOL features, which may be of interest to you.
Index
X Close
Back | Next
12
Visual COBOL
What is COBOL?
COBOL (COmmon Business Oriented Language) is one of many high-level computer programming languages.
COBOL was originally designed to solve common business problems, which often require collection, processing
and reporting on large quantities of data. For example, COBOL programs generate payroll information, store and
report on personnel information, provide stock control and produce profit and loss statements etc.
Some languages are geared toward solving scientific problems that require complex algorithms. Some languages
are targeted at user interface features such as Windows Forms or Web Forms. COBOL, in its earliest form, was
best suited for financial and business data processing and reporting. In later evolutions of COBOL the use of
Windows Forms, Web Forms and Web Services has become very simple to implement, entirely in COBOL.
COBOL still remains very much the language of choice for complex business and financial applications as well as
providing very strong simple interfaces to data storage; whether it is regular data storage or integration to databases
such as relational, hierarchical or pointer driven databases etc.
COBOL is an easy-to-understand language. It uses English-like structures, such as paragraphs, statements, and
verbs. Paragraphs contain statements; statements can include verbs. It also is a highly structured language, where
different types of statements must be included in specific parts of the program. This structure helps in the analysis
of COBOL programs.
For the above reasons COBOL is a very easy language to maintain. Most commercial applications pass though
many update processes in their life span. Ease of maintenance is generally a very high priority when choosing a
suitable programming language.
There are hundreds of thousands of COBOL programs in use today; which began life 30 or 40 years ago. These
legacy programs represent over 50% of the worlds program source, containing billions of line of code. This legacy
code is an extremely valuable asset to the Organizations to which they belong.
What we would like to do is to retain as much of this legacy code as possible, while moving forward to more
modern user and data interfaces. COBOL provides us with many mechanisms to do just this.
COBOL Features
COBOL includes the following features:
Representation of commercial concepts of files and records, such as employee name and salary information in
personnel records.
Comprehensive file-handling capabilities, such as methods to open and close files, store file data, and update
file records.
High-level data processing commands (for example, sort, merge, and table manipulation commands)
Conformity to an agreed standard, so that different companies can offer COBOL programming tools with the
same features.
Index
X Close
Back | Next
13
Visual COBOL
Support for common mathematical functions, such as trigonometric and logarithmic functions, although
COBOL was not initially designed to solve highly complex scientific problems.
The ability to code for Windows Forms, Web Forms and Web Services.
Index
X Close
Back | Next
14
Visual COBOL
Class setup
You can use this course very simply, as though you were reading a book. However this is not the best way to learn a
programming language.
The course uses many illustrated examples and exercises and these are best demonstrated with the use of a
program development environment.
So in order to effectively use the materials, provided throughout this course, you are advised to install:
You will also find it valuable to install the Micro Focus data tools add-pack to allow you to view and edit your
data files.
NOTE: If you wish to have a version of Visual Studio supporting more languages than just COBOL, then you will
need to download a licenced version from Microsoft, prior to installing Visual COBOL.
Samples
A variety of sample projects, programs and data files are provided. These are installed by executing the compressed
file COBOLClass.exe to extract to your C:\ drive. This gives the following folders:
These folders and files will be used extensively during the running of this class.
Index
X Close
Back | Next
15
Visual COBOL
These are now the default locations that Visual COBOL will use during
the class.
4. Click OK to save these settings. You are now ready to go.
Module Summary
At the end of this module you should now be familiar with:
You have set up the sample programs and projects that you will be using during this course. In addition you have
configured a number of settings in Visual COBOL.
Index
X Close
Back | Next
16
Visual COBOL
Quick Quiz
1. When was COBOL first used?
a. 1949
b. 1959
c. 1969
d. 1979
2. Traditional legacy COBOL is good at:
a. .NET integration
b. Object Orientation
c. Business Logic
d. Complex arithmetic
3. Modern COBOL is good at:
a. .NET integration
b. Object Orientation
c. Business Logic
d. All of these
e. None of these
Index
X Close
Back | Next
17
Visual COBOL
COBOL
Introduction
Index
X Close
Back | Next
18
Visual COBOL
02 COBOL Introduction
Introduction
In this module we will take you through the basic structure of a traditional COBOL program.
For now we will be looking at COBOL programs which many would regard as traditional legacy programs.
Later modules will deal with the later extensions to COBOL which include Object Oriented COBOL and .NET
COBOL.
Module Objectives
At the end of this module you will be familiar with:
Divisions
A COBOL program includes four Divisions. Although some compilers will permit the omission of some of the
divisions, they must appear in the following sequence.
IDENTIFICATION DIVISION the first division. Statements here define the name of the program and comments
that describe the programs function.
ENVIRONMENT DIVISION the second division. The particular system environment under which the program will
run is defined here.
DATA DIVISION the third division. This is where all data is defined. All programs manipulate data in some way.
PROCEDURE DIVISION the final division. This division contains all the statements that determine what the
program does. Any data items referred to must have been already defined in the Data Division.
Index
X Close
Back | Next
19
Visual COBOL
02 COBOL Introduction
Simple Example
The following COBOL program illustrates the breakdown of the structure of a simple COBOL program:
There you can see the 4 Divisions of a COBOL program together with Sections, Paragraphs and
Statements as appropriate.
Look for the four Divisions; dont worry about the specifics of the code for now.
Look for the Sections within each Division.
Look for Paragraphs within each Section. (This is not so obvious there are 5 in total one of them is
contained in Division, without a Section).
Index
X Close
Back | Next
20
Visual COBOL
02 COBOL Introduction
Exercise
1. Open the solution 02_01_Division_Example.sln from the folder: C:\COBOLClass\Projects\02_01_
Division_Example
2. Double click the DIVEX.CBL in the Solution Explorer and see the COBOL program shown above.
3. What is the name (ID) of the program?
4. How many sections are there in the sample program? (This is not so obvious there are 5 in total).
5. Run this program by pressing F5. (This program does not do anything useful except say Hello World and
then asks you to press the Carriage Return key).
Module Summary
At the end of this module you will now be familiar with:
Quick Quiz
1. The divisions of a COBOL program in order are:
a. Identification, Environment, Data and Procedure
b. Identification, Configuration, Data and Procedure
c. Identity, Environment, Data and Logic
d. Environment, Data and Procedure
2. The name of a program is contained in:
a. Data Division
b. Procedure Division
c. Identification Division
d. Linkage Division
3. The original computer that this program was used on was:
a. A Windows PC
b. An IBM 360 mainframe
c. A UNIX machine
d. An IBM 370 mainframe
4. Which of the following is true:
a. A section can contain paragraphs
b. A paragraph can contain sections
c. A section must contain paragraphs
d. A paragraph must contain sections
Index
X Close
Back | Next
21
Visual COBOL
Basic COBOL
Structure
Index
X Close
Back | Next
22
Visual COBOL
Introduction
In this module we will start to look at the Basic structure of a COBOL program and what each portion of the
code will contain.
Module Objectives
At the end of this module you will be able to:
View a basic COBOL program that includes the four divisions and their sections.
Programming Layout
A typical piece of legacy COBOL code is laid out as shown below:
The program line is divided into distinct column areas each with a specific
function to manage
....+....1....+....2....+....3....+....4....+....5..
PROCEDURE DIVISION.
* This is a comment.
000-MAIN SECTION.
...
7 Indicator
8-11
Area A
12-72
Area B
1-6
Sequence
Number
Index
X Close
Back | Next
23
Visual COBOL
Index
X Close
Back | Next
24
Visual COBOL
Index
X Close
Back | Next
25
Visual COBOL
Identification Division
The Identification Division is the first division in the program.
It contains the name of the program in the Program-ID paragraph. (As we will see later in the course, the program-id
can be replaced by class-id for Object Oriented COBOL).
There are other possible entries in this division, but all these additional entries are treated as comments. e.g.
Index
X Close
Back | Next
26
Visual COBOL
Environment Division
This second division is used to identify any parts of the program that apply to specific computer hardware or devices.
This section also specifies any data files used in the program.
This division can contain two sections.
CONFIGURATION SECTION contains particular entries that define the actual environment. This section is
often omitted, if no such entries are necessary.
INPUT-OUTPUT SECTION is present whenever the program reads from or writes to data files. This section is
covered in more detail in a later module, but is used to link the internal file names to external file locations. e.g.
e.g.
Where InFile and Outfile are the internal program names and datain and dataout are the real physical file
names and would have been defined as something like:
C:\COBOLClass\DataFiles\Mydatain.dat and C:\COBOLClass\DataFiles\Mydataout.dat
Data Division
The Data Division describes the data items needed by the program.
Data can originate from input sources such as files on disk, or tables in databases, or data from internal
working areas.
This division often contains the following Sections:
The FILE SECTION, which is used when accessing data files.
The WORKING-STORAGE SECTION, which holds all the data items that the program needs, e.g. counters
and intermediate variables.
Index
X Close
Back | Next
27
Visual COBOL
File Section
This is used to define the data file contents, used during the execution of the program. e.g.
In this example:
The fd is File Description or File Definition and the names in here must match the names in the SELECT
statement of the input-output section shown earlier.
Working-Storage Section
This section contains the data definitions of definitions of the variables that the program needs during it execution.
e.g.
In this example:
Index
X Close
Back | Next
28
Visual COBOL
Linkage Section
LINKAGE SECTION
Calling Program
Called Program
Data Division
Data Division
Passed Data
(Linkage Section)
Passing Data
(Working-Storage
Section)
The Linkage-Section is contained in the program that is called, not in the calling program.
Procedure Division
The Procedure Division contains the programs processing statements. e.g.
As stated earlier, all the section and paragraph names are user defined.
In the above simple example:
Index
X Close
Back | Next
29
Visual COBOL
Use of periods
The use of periods is important. Each division and section definition must end with a period (referred to as a full
stop). Period is also used to terminate each statement within the first three divisions (IDENTIFICATION,
ENVIRONMENT, and DATA).
If you omit a necessary period, the compiler may notice an error only at the beginning of the next line, causing a
misleading error message to appear. If you ever see an error message that makes little sense, check missing
periods first.
The rules for using periods in the PROCEDURE DIVISION are slightly different, and are discussed in a later module.
Module Summary
At the end of this module you are now able to:
View a basic COBOL program that includes the four divisions and their sections.
Exercise
1. Inside Visual COBOL, load the solution 03_01_Simple_structure.sln from the folder C:\COBOLClass\
Projects\03_01_Simple_structure. (This is the program you have seen above).
2. First of all examine this program to see the contents of the various divisions, sections and paragraphs.
3. Other than the program-id, change the entries in the Identification Division to be more sensible.
4. Run the program by pressing F5 and you will see that it displays the details of the first record on the output file.
5. See how the data file assignments have been done by opening the file application.config from the
Solution Explorer.
Index
X Close
Back | Next
30
Visual COBOL
7. You will see a new section here; Linkage Section. This will be discussed later in the course.
Quick Quiz
1. What does working-storage section contain?
a. Details of the file definitions
b. Details of data used in the program
c. Details of data passed to the program from another program
d. Logical definitions of data file locations
2. What must be defined after the Installation paragraph?
a. The name of the program
b. The fixed value MARS
c. Anything you like
d. Nothing must be defined here
3. In File-Control what are the 2 names
a. The names of the 2 data files
b. The relationship between internal file name and external file name
c. The data items used by the file
d. The procedure names to use in paragraphs
4. What is Linkage Section used for?
a. To contain the file assignments
b. To contain file data definitions
c. To allow data to be passed between programs
d. To contain working data definitions
Index
X Close
Back | Next
31
Visual COBOL
Data Representation
Index
X Close
Back | Next
32
Visual COBOL
04 Data Representation
Introduction
This module will show the way that data is represented inside a COBOL program. You will see also how data can be
grouped into records. In addition, you will also see how copy files are used.
Before you can write COBOL programs, you need to learn about how data is defined and processed.
Data is defined in the same way in all three sections within the DATA DIVISION.
File Section
Working-Storage Section
Linkage Section
Procedural statements to use that data are provided in the PROCEDURE DIVISION.
Data items are often referred to as fields. For example: a last name or a telephone number. In COBOL, rules govern
how you can define data items. This module looks at:
Names that are reserved and cannot be used to identify your own fields.
How data item characteristics can be defined using the PICTURE clause.
Module Objectives
On successful completion of this module you will be able to:
Defining Data
There are a number of questions to be asked:
The lowest level of data is the FIELD (often called an elementary item)
Index
X Close
Back | Next
33
Visual COBOL
04 Data Representation
Data Names
Unlike in some programming languages COBOL encourages you to use long meaningful names. This will help in the
future when the program is maintained. For example you could choose names like:
Data Description
Data Name
Employee-First-Name
Employee-Last-Name
Employee-ID
Employee-Salary
INPUT Reserved words are not allowed as a name. INPUT is a reserved word.
Index
X Close
Back | Next
34
Visual COBOL
04 Data Representation
Reserved Words
COBOL uses some words for special processing instructions. These words are known as reserved words. The data
item name must not be a reserved word, such as DATA. COBOL uses the word DATA for itself, so DATA cannot
be used as a data name. However, you can use a reserved word as part of a larger name. DATA-GROUP would
be acceptable.
The following give examples of some reserved words that cannot be used when naming data fields.
All Division and Section names and the words DIVISION and SECTION
AND, CLOSE, DISPLAY, FILE, INPUT, MOVE, MULTIPLY, NOT, OPEN, OR, PICTURE, RECORD, SPACE
Data Hierarchy
Defining a field in the DATA DIVISION requires a specific data hierarchy: either at a Group Level or a subordinate
Elementary Level.
When describing data, we see not only the size of different data fields, but also how they relate to each other. This is
done through level numbers.
Index
X Close
Back | Next
35
Visual COBOL
04 Data Representation
Data items defined above are either elementary items or group items.
Elementary items
EMPLOYEE-TITLE
EMPLOYEE-INITIALS
EMPLOYEE-SURNAME
EMPLOYEE-GENDER
EMPLOYEE-ADDRESS-LINE(1)
EMPLOYEE-ADDRESS-LINE(2)
EMPLOYEE-ADDRESS-LINE(3)
EMPLOYEE-ADDRESS-LINE(4)
Group items
EMPLOYEE-ADDRESS is an 80 character group item containing 4 recurring fields
EMPLOYEE-NAME
is a 37 character group item containing 3 fields
EMPLOYEE-RECORD is a 118 character group item containing 3 fields (2 of which are themselves
group items)
Index
X Close
Back | Next
36
Visual COBOL
04 Data Representation
Literals (both numeric and alphanumeric) and be applied to data items when defining these. For example is the code
example the word Hello is a literal value of DATA-FIELD4.
Alphabetic Data Fields
Use the PIC A syntax to identify a field as alphabetic. You could use format 1 or format 2.
Format 1
01 DATA-FIELD1
PIC A(3).
Format 2
01 DATA-FIELD1
PIC AAA.
In Format 2 each of the three As identifies the storage for one character. The 3 in the first format is merely another
way to write this.
Alphanumeric Data Fields
Fields containing letters, numbers, and spaces are identified by PIC X.
01 DATA-FIELD2 PIC X(3). or
01 DATA-FIELD2 PIC XXX.
Numeric Data Fields
Define a field containing all numbers along with optional + or sign as numeric data by using the PIC 9999 clause.
Each 9 represents one digit.
01 DATA-FIELD3 PIC 9(4). or
01 DATA-FIELD3 PIC 9999.
Numeric fields can be up to a maximum of 31 digits.
Always make the definitions for numeric fields large enough to accommodate any possible number. If a field needs
to hold 1 million, many programmers will at first define this in a PIC 9(6) field. Such a field will hold 999,999 with
ease. However, adding one sets the field to zero, as the leading 1 is lost to the left probably not what is needed.
Index
X Close
Back | Next
37
Visual COBOL
04 Data Representation
PIC 99999V99.
Each 9 after the V represents a digit after the decimal point. So, an EMPLOYEE-SALARY would appear as
$50000.00, two digits after the decimal point. Alternatively, you could write this as:
01 EMPLOYEE-SALARY
PIC 9(5)V9(2).
Negative Numbers
The notation of 9(5)V99 allows only for zero or positive values. However, if we needed to allow for negative numbers,
for example, for a customers account balance, we would say something like the following.
01 CUSTOMER-BALANCE
PIC S9(5)V99.
S stands for signed. The sign is stored on the data item itself and does not take an extra byte.
Literals
Literals are used to give data items specific values, either numeric values (for example, 53 or 2) or alphanumeric
values (for example, Hello). Literals represent the actual contents of the data rather than the name of the data
item.
03 DATA-FIELD4
03 AMOUNT-FIELD
A decimal point can be included, but not at the end of the literal.
Surround the literal with either single or double quotation marks (for example, USA or USA).
Index
X Close
Back | Next
38
Visual COBOL
04 Data Representation
Exercise 1
1. In Visual Cobol load the solution 04_01_Data_Representation.sln from the folder C:\COBOLClass\
Projects\04_01_Data_Representation.
2. Use the DataRep1.cbl to add a record layout for a company employee. There is already a record there for
CUSTOMER. So add a new record for EMPLOYEE to include the following data fields:
a.
Title (3 characters or Bytes)
b.
Initials ( 4 bytes)
c.
Surname (30 bytes)
d.
Gender (1 byte)
e.
Address lines (4 lots of 30 bytes)
f.
Postal code (8 bytes)
3. Add a Salary field for the employee to hold 5 bytes of before decimal point and 2 after.
4. Change the layout to ensure the address lines are grouped.
5. Change the layout to ensure the name can be accessed as one unit.
6. How long is the record layout in bytes?
7. If you require a solution program to the above exercise, DataRep2.cbl is contained in the same folder as
DataRep1.cbl.
EMPLOYEE-RECORD.
03 EMPLOYEE-GENDER
PIC X.
Since for this case we are not interested in those first 37 bytes, we can use a FILLER as shown next.
01
EMPLOYEE-RECORD.
03 FILLER
03 EMPLOYEE-GENDER
03 FILLER
Index
PIC X(37).
PIC X.
PIC X(135).
X Close
Back | Next
39
Visual COBOL
04 Data Representation
EMPLOYEE-RECORD.
03
03 EMPLOYEE-GENDER
03
PIC X(37).
PIC X.
PIC X(135).
FIELD1
FIELD2
FIELD3
PIC 9(4).
PIC 9(4) COMP.
PIC 9(4) COMP-3.
Since the default is USAGE DISPLAY, this is almost always omitted to give:
03
03
03
FIELD1
FIELD2
FIELD3
PIC 9(4).
PIC 9(4) COMP.
PIC 9(4) COMP-3.
By default, when usage is not specified, numeric data is held in the format we have seen previously, as shown in the
following example.
01
RECORD-COUNTER
PIC 9(4).
This is known as USAGE Display. The number is stored as one digit per byte, in just the same way as an
alphanumeric (PIC X) or alphabetic (PIC A) field. Such fields work perfectly well, in that you can carry out any
arithmetical operations on them that you wish.
Yet, other methods of storing numeric data are more efficient (the calculations take place more rapidly) and the data takes
up less room. Programmers tend to use such data types for internal data items (ones say in WORKING-STORAGE).
Let us look at three ways in which a data item that needs to hold up to 9,999 can be stored. (On some compliers
there are other variants too such as COMP-5 and COMP-X). Where the word COMP is an abbreviation of
COMPUTATIONAL
Usage Display Format
PIC 9(4)
Index
X Close
Back | Next
40
Visual COBOL
04 Data Representation
Usage DISPLAY
The base form is USAGE Display,
01
RECORD-COUNTER
PIC 9(4).
This method (Usage Display) allocates one byte per digit, which is what we are familiar with. If the number contained
1234, it would be stored like this.
00110001 00110010 00110011 00110100
in binary
31 32 33 34 in hex
Usage BINARY
This format allocates the number of Bits to the field for storage
01
RECORD-COUNTER
01
RECORD-COUNTER
01
RECORD-COUNTER
8 bits to a byte.
The Binary Format method allocates the actual number of bits needed to hold the maximum number (9,999) and
then rounds that up to the next byte. So, 9999 (binary 10011010101011) can be held in 14 bits and would occupy
2 bytes (16 bits). The number 1234 would be stored as shown in the following.
10011010010
04D2
in binary
in hex
Index
X Close
Back | Next
41
Visual COBOL
04 Data Representation
1 byte
2 byte
3 bytes
4 bytes
5 bytes
6 bytes
7 bytes
8 bytes
Signed fields are exactly the same size (the number is held in twos complement format). A decimal number is
stored according to its total number of digits, for example a PIC 9(6)v9(4) will fit in 5 bytes.
Index
X Close
Back | Next
42
Visual COBOL
04 Data Representation
WS-ITEMS.
03 WS-NAME
03 WS-SALARY
03 WS-AGE
PIC X(20)
VALUE SMITH.
PIC 9(6)V99 VALUE 27500.
PIC 99
VALUE ZERO.
The VALUES shown in lines 3 and 4 are known as numeric literals. In the case of PIC X or PIC A fields, the values
must be enclosed in quotes.
In the above example, WS-NAME will now contain SMITH followed by fifteen spaces.
WS-SALARY will contain 027500.00. In other words, if the value of the literal does not fill up the field, then character
fields are padded with spaces on the right and numeric fields padded with zeros on the left.
Entering too large a value into a field (for example, giving WS-NAME a value of General Dwight D Eisenhower)
causes the COBOL compiler to identify an error.
Also, use a numeric literal that matches the PICture of the item. Since WS-SALARY is defined as PIC 9(6)V99, (the
first 9 indicating a numeric data type), it would be wrong to assign SALARY a VALUE of NONE (which is an
alphabetic value).
Figurative Constants
In addition to numeric literals, you can use VALUE clauses with figurative constants. Figurative constants preset data
items to useful values. The following figurative constants are available.
LOW-VALUES
HIGH-VALUES
ALL literal
WS-NAME
Index
PIC X(20)
VALUE SPACES.
X Close
Back | Next
43
Visual COBOL
04 Data Representation
WS-RECORD.
03 WS-NAME
03 WS-ADDRESS
03 WS-SALARY
PIC X(20).
PIC X(100).
PIC 9(5)V99.
WS-NUMBER
Another example will result in binary zero (hex 00) throughout the two bytes of the field, as shown next
03
This results in a nasty little trap that is very easy to fall into.
In the following sample, the programmer is trying to set all four items in the group to zero. Instead, ZERO gets
moved to the group. Because the group is alphanumeric, hex 30 is moved to each of the eight bytes, setting all the
items to 2336! (hex 3030). Note: Each field defined in the example as PIC 9(4) COMP is stored as 2 bytes.
01
WS-NUMBERS.
03 WS-NUM-1
03 WS-NUM-2
03 WS-NUM-3
03 WS-NUM-4
PIC
PIC
PIC
PIC
9(4)
9(4)
9(4)
9(4)
COMP.
COMP.
COMP.
COMP.
So; MOVE ZERO TO WS-NUMBERS will not put 0 into each of the individual fields.
The correct way to do this is:
INITIALIZE WS-NUMBERS
Index
X Close
Back | Next
44
Visual COBOL
04 Data Representation
WS-NUMBERS.
03 WS-NUM-1
03 WS-NUM-2
03 WS-NUM-3
03 WS-NUM-4
PIC
PIC
PIC
PIC
9(4)
9(4)
9(4)
9(4)
COMP.
COMP.
COMP.
COMP.
WS-STARS
WS-LINE
Important note: Use the VALUE clause, as shown above, only in the Working-Storage Section. It has no relevance in the
FILE section or the LINKAGE section since these fields are populated from outside (either by reading from a file or from a
calling program).
WS-RECORD.
03 WS-NAME
03 WS-DOB
03 WS-DOB-XX
PIC X(30).
PIC 9(8).
REDEFINES WS-DOB
PIC X(8).
The redefining item must immediately follow the one being redefined. Redefine items at any level (except 01 in the
File Section, as we shall see later). A redefined item can have a VALUE clause, but the redefining clause cannot.
Index
X Close
Back | Next
45
Visual COBOL
04 Data Representation
WS-COUNTERS.
03 WS-NUMBER-OF-EMPLOYEES
03 WS-TOTAL-SALARY
03 WS-TOTAL-TAX
03 WS-TOTAL-DEDUCTIONS
PIC
PIC
PIC
PIC
9(4).
9(8)V99.
9(7)V99.
9(6)V99.
When code needs to be shared in this way, the best solution is to store the relevant lines in a copyfile, that is, a text
file that can be automatically copied into the program.
In the following example, the file was saved as counters.cpy. The COPY statement is typically inserted in Area A,
though it is also valid in Area B.
COPY COUNTERS.CPY
Sometimes full stops (periods) are absolutely necessary. The full stop at the end of a COPY statement must never
be omitted. In the above example, such an omission would cause the compiler to be unable to compile the
statement following the COPY.
(TAG)-NUMBERS .
03 (TAG)-NUM-1
03 (TAG)-NUM-2
03 (TAG)-NUM-3
PIC 9(4).
PIC 9(6).
PIC 9(5).
Index
X Close
Back | Next
46
Visual COBOL
04 Data Representation
WS01-NUMBERS.
03 WS01-NUM-1
03 WS01-NUM-2
03 WS01-NUM-3
PIC 9(4).
PIC 9(6).
PIC 9(5).
01
WS02-NUMBERS.
03 WS02-NUM-1
03 WS02-NUM-2
03 WS02-NUM-3
PIC 9(4).
PIC 9(6).
PIC 9(5).
While copy files are commonly used to hold data hierarchies, such as records, they can also be used to hold
executing code, that is, statements that are found in the Procedure Division.
Exercise 2
1. In Visual Cobol load the solution 04_02_Data_Representation.sln from the folder
C:\COBOLClass\Projects\04_02_Data_Representation.
2. Look at the program to see how the same copy file has been used twice in the program. In the 2 versions the
tag has been replaced with different values.
3. You can look at the contents of the copy file by double clicking the WS.CPY file in the solution explorer.
4. Execute the program by pressing F5 to see how the different versions of the copy file are used.
5. How would you initialize the copy file field contents with zeroes at run-time?
6. Reset the values of the counters to zeroes during the execution to simulate a restart of the program.
7. What would be the effect of setting the WS01-Numbers group to Low-Values?
WS-INPUT-AREA-1.
03 EMPLOYEE-NAME
03 EMPLOYEE-ADDRESS
03 EMPLOYEE-SALARY
PIC X(20).
PIC X(60).
PIC 9(6)V99.
01
WS-INPUT-AREA-2.
03 EMPLOYEE-NAME
03 EMPLOYEE-DOB
PIC X(20).
PIC 9(8).
Index
X Close
Back | Next
47
Visual COBOL
04 Data Representation
Module Summary
On completion of this module you can now:
04_05_Numeric moving
Quick Quiz
1. Which of the following statements are true?
a. There are no data name restrictions
b. Level Numbers are used to group records
c. PIC S9(5)v9(3) represents an integer field
d. COBOL Reserved Words cant be used to identify data names
e. None of the above
Index
X Close
Back | Next
48
Visual COBOL
04 Data Representation
Index
X Close
Back | Next
49
Visual COBOL
Basic Verbs
Index
X Close
Back | Next
50
Visual COBOL
05 Basic Verbs
Introduction
This module will deal with some of the basic verbs that you will find in the procedure division of a COBOL program.
Do you recall that the PROCEDURE DIVISION is the final division in the program?
It is where the logic code is written.
The PROCEDURE DIVISION heading starts in Area A
Code written in this division should be
Module Objectives
On successful completion of this module you will be able to:
Simple Example
We will start by using a very simple example program. This example can be found by opening the project
05_01_Basic_Verbs.sln
The program here contains the following code:
Index
X Close
Back | Next
51
Visual COBOL
05 Basic Verbs
MOVE
DISPLAY
ACCEPT This requires you to enter a value on the screen and places the value into the data item
STOP The first Stop display a message requiring you to press <CR>
The Stop Run, terminates the program
This program should be run by pressing F5 to see the results of the execution. The result of running will be:
Where George Washington was the name you entered on the screen.
Statement Termination
Up until the mid-1980s it was common practice to terminate each statement with a full stop (period). Indeed in
many cases it was essential to do this.
Since the mid-1980s, additional syntax was introduced into COBOL which meant that statement termination was
done by statement terminators.
Lets see an example using the IF verb (Yes IF is a verb in COBOL).
Pre 1985
IF CUSTOMER-AGE < 21
DISPLAY CUSTOMER TOO YOUNG.
Post 1985
IF CUSTOMER-AGE < 21
DISPLAY CUSTOMER TOO YOUNG
END-IF
Another example might be:
Pre 1985
IF CUSTOMER-AGE < 21
IF PARENTS-CONSENT = YES
DISPLAY CONSENT GIVEN
ELSE
DISPLAY CUSTOMER TOO YOUNG.
Index
X Close
Back | Next
52
Visual COBOL
05 Basic Verbs
Post 1985
IF CUSTOMER-AGE < 21
IF PARENTS-CONSENT = YES
DISPLAY CONSENT GIVEN
ELSE
DISPLAY CUSTOMER TOO YOUNG
END-IF
END-IF
On the face of it this does not seem to be much different, but consider how this post 1985 statement could have
been coded pre 1985
IF CUSTOMER-AGE < 21
IF PARENTS-CONSENT = YES
DISPLAY CONSENT GIVEN
END-IF
ELSE
Index
X Close
Back | Next
53
Visual COBOL
05 Basic Verbs
Index
X Close
Back | Next
54
Visual COBOL
05 Basic Verbs
DISPLAY
ACCEPT
MOVE
PERFORM ...
STOP
DISPLAY verb
DISPLAY can be used to output the value of any combination of data items and literal.
In the example below (DISPLAY WS-NAME), DISPLAY sends the contents of the field WS-NAME to the screen.
MyProgram.CBL
working-storage Section.
01 WS-NAME
Pic X (20).
PROCEDURE DIVISION.
DISPLAY WS-NAME
Display
My File
ACCEPT verb
ACCEPT is the opposite of DISPLAY. It is used to allow the person running the program to input a value into a data item.
In the example at below (ACCEPT WS-NAME), ACCEPT copies the value on the screen into the contents of the
field named WS-NAME.
ACCEPT
MyProgram.CBL
working-storage Section.
01 WS-NAME
Pic X (20).
PROCEDURE DIVISION.
ACCEPT WS-NAME
Index
X Close
Back | Next
55
Visual COBOL
05 Basic Verbs
MOVE verb
Contrary to the English use of the word MOVE, MOVE copies a value from a data item (or a literal or figurative
constant) to one or more data items. The field which is the source of the MOVE remains unchanged.
For example, if a program read a record and stored it, you could use MOVE to move the data from the input storage
area to the output storage area. Here is a simple form of MOVE.
MOVE DATA-SEND-FIELD TO DATA-TARGET-FIELD
Then sending field could contain one of the following
Index
X Close
Back | Next
56
Visual COBOL
05 Basic Verbs
NAME-IN
NAME-OUT
NAME-IN
NAME-OUT
NUM1
NUM2
NUM3
NUM4
CHAR1
CHAR2
PIC
PIC
PIC
PIC
PIC
PIC
9(4)V99.
99V99.
9.
V99.
XX.
X(10).
Index
X Close
Back | Next
57
Visual COBOL
05 Basic Verbs
1234.56
34.56
4
.56
12
123456
PERFORM Verb
Up until now the course has shown programs that execute in the order that the statements appear. However, you
can control the order of execution sequence using the PERFORM verb. You can control execution using several
formats of the PERFORM verb, including using it with an IF condition or using PERFORM UNTIL a condition occurs.
The following shows how to use PERFORM.
PERFORM paragraph-header
PERFORM identifies the instruction to be done on paragraph-header, which is the name of a sub-process to be
executed. The sub-process must also be written in your program. Here is an example.
In the first line of the procedure division in the following program, the verb PERFORM executes INIT-PARA, a subprocess that begins 3 lines further on. Upon completion of the INIT-PARA, the execution point returns to the
statement after the PERFORM INIT-PARA.
WORKING-STORAGE SECTION.
01 WS-TIMES
PIC 9(4).
01 WS-NUM1
PIC 9(4).
01 WS-NUM2
PIC 9(4).
01 WS-NUM3
PIC 9(6).
PROCEDURE DIVISION.
PROG.
PERFORM INIT-PARA
PERFORM LOOP-PARA WS-TIMES TIMES
PERFORM END-PARA.
INIT-PARA.
DISPLAY A SIMPLE MULTIPLIER
DISPLAY HOW MANY TIMES (1 TO 6)?
ACCEPT WS-TIMES
IF (WS-TIMES > 6) OR (WS-TIMES < 1)
MOVE 1 TO WS-TIMES
END-IF.
LOOP-PARA.
DISPLAY FIRST NUMBER?
ACCEPT WS-NUM1
DISPLAY SECOND NUMBER?
ACCEPT WS-NUM2
MULTIPLY WS-NUM1 BY WS-NUM2 GIVING WS-NUM3
Index
X Close
Back | Next
58
Visual COBOL
05 Basic Verbs
Index
X Close
Back | Next
59
Visual COBOL
05 Basic Verbs
Index
X Close
Back | Next
60
Visual COBOL
05 Basic Verbs
Index
X Close
Back | Next
61
Visual COBOL
05 Basic Verbs
[Single]
[Series]
This Perform THRU option is not something which is used commonly in modern COBOL applications but you will
find extensive use of it in older legacy programs.
PERFORMing Sections
Performing a single section is also very efficient.
All the paragraphs within the section will be performed in sequence. e.g.
MY-MAIN SECTION.
PARA-1.
MOVE A TO B
. . . .
PARA-2.
. . . .
PARA-3.
. . . .
The statement:
PERFORM MY-MAIN
Will execute PARA-1, PARA-2, PARA-3 in sequence.
You would get the same result with:
PERFORM PARA-1 THRU PARA-3
Using Comments
It has already been said that you should use comments as much as possible in a COBOL program to help with
subsequent developers understanding the code.
A comment line is normally recognized by column 7 having an asterisk.
However, since 1985 you can also use what is known as the in-line comment.
In this case if you place the characters *> anywhere in the code, then the rest of the line, after *> is regarded as a
comment. e.g.
Index
X Close
Back | Next
62
Visual COBOL
05 Basic Verbs
STOP Verb
STOP is not issued on its own, it is most commonly written with RUN to terminate a program.
STOP RUN stops the current program.
Any statements following STOP RUN in the same paragraph can never be executed.
As you have seen in the preceding examples it is also used together with a literal. e.g.
STOP Press <CR> to continue
This causes a pause in the program, while the user presses the <CR> key
Index
X Close
Back | Next
63
Visual COBOL
05 Basic Verbs
PROG
PARA
PARA
PARA
PARA
PARA
1
2
3
4
5
PROG
PARA
PARA
PARA
PARA
PARA
1
2
3
4
5
Index
X Close
Back | Next
64
Visual COBOL
05 Basic Verbs
PROG
PARA-3
PARA-4
PARA-5
PROG
PARA-3
PARA-1
PARA-2
PARA-3
PARA-4
PARA-5
Index
X Close
Back | Next
65
Visual COBOL
05 Basic Verbs
PARA 2.
PARA 3.
PARA 4.
PARA 5.
The results of executing this code would be the following values are displayed on the screen:
IN
IN
IN
IN
PROG
PARA-3
PARA-4
PARA-5
PROG
PARA-3
PARA-4
PARA-5
PARA-1
PARA-2
PARA-3
PARA-4
PARA-5
Index
X Close
Back | Next
66
Visual COBOL
05 Basic Verbs
Index
X Close
Back | Next
67
Visual COBOL
05 Basic Verbs
Module Summary
Now you have completed this module you are be able to:
Exercises
Make sure you execute the example solutions in debug mode (use F11 to step through the execution of the code)
to understand what is happening in the 4 programs inside these solutions.
05_01_Basic_Verbs.sln
05_02_Simple_Performs.sln
05_03_Simple_Performs.sln
05_04_Mix_GOTO_Perform.sln
Index
X Close
Back | Next
68
Visual COBOL
05 Basic Verbs
Quick Quiz
1. Which of these statements is always true?
a. You can move any data type to any data type
b. You can move character data of any size to character data of any size
c. You can move character data of any size to numeric data of any size
d. You can move numeric data of any size to numeric data of any size
e. You can move numeric data of any size to character data of any size
2. True or false?
a. It is compulsory to use END-IF to terminate an IF statement
b. It is compulsory to use a period to terminate an IF statement
c. It is compulsory to terminate an IF statement
3. True or false?
a. The DISPLAY verb reads information from the screen
b. The ACCEPT verb reads information from the screen
4. If the data items WS-COUNTER contains 14 and STORE-COUNTER contains 25, when you execute the
statement:
MOVE WS-COUNTER TO STORE-COUNTER
the values of the two data items become?
a. WS-COUNTER 25, STORE-COUNTER
b.
WS-COUNTER 25, STORE-COUNTER
c. WS-COUNTER 14, STORE-COUNTER
d.
WS-COUNTER 0, STORE-COUNTER
e. WS-COUNTER 14, STORE-COUNTER
Index
14
25
14
14
0
X Close
Back | Next
69
Visual COBOL
Best Practice
Index
X Close
Back | Next
70
Visual COBOL
06 Best Practice
Introduction
Over the life of a typical COBOL application, many different people might make fixes and improvements at
different times.
Often this maintenance work may take many times more than the initial effort needed to create the application in
the first place.
Implementing best practices when creating new programs speeds up the process of getting a stable,
high-quality application; yet also yields huge benefits during the maintenance phase.
We will look at ways in which a COBOL program can be written to support this long term objective of ease
of maintenance.
Module Objectives
Upon successful completion of this module, you will be able to:
Of course it does, but it is surprising how many programmers simply embark upon coding without thought
to overall design.
Could the code be written immediately with no thought being given to program structure?
It is always possible to write a program in this way, but in all but the simplest programs, it is rarely sensible.
Most programs need to make decisions at some point and these need to be taken care of sensibly.
Many programs will contain procedural logic, meaning, certain things must take place before other actions
can be undertaken.
Programs may have to execute a loop a particular number of times or until some condition is true, as we saw
in the discussion of the PERFORM...IF or PERFORM...UNTIL verb.
If a program has to do any of these things, then bad design or not designing at all, will introduce logic errors.
Logic errors cause the code to behave differently than the programmer expects.
The COBOL compiler cannot find such logic errors, and they may remain undetected until the program goes live,
surfacing in the future. A well-designed program very much reduces the number of logic errors. Spending time on
the design avoids many problems later.
Usually the later an error is found, the more expensive it is to fix.
Index
X Close
Back | Next
71
Visual COBOL
06 Best Practice
Monolithic
STRUCTURED
START
PROG
CODE
START
CODE
CODE
CODE
END
CODE
CODE
END
CODE
CODE
Monolithic programming.
Monolithic programming
Entails the program logically starting at the beginning and flowing through to the end as though reading a novel.
Index
X Close
Back | Next
72
Visual COBOL
06 Best Practice
Structure Diagrams.
Truth tables.
Truth Tables
Structure Diagrams
We will briefly indicate the use of structure diagrams in our program design.
A logic block contains either the overall structure, or parts of the structure.
In our example we will use a goods train to view the structures possible.
TRAIN
A top-level block
TRAIN
Top level
Lower level
MIddle
Bit
Index
X Close
Back | Next
73
Visual COBOL
06 Best Practice
A locomotive.
A Guard Van.
MIddle
Bit
*
A selection block is
identified by a in
the top right corner
An iteration block
is identified by a
* in the top right
corner
Wagon
Example
As a more meaningful example you are asked to design a program that sequentially reads a file of records and then
operates using the following rules:
Index
X Close
Back | Next
74
Visual COBOL
06 Best Practice
Each Section/Paragraph could contain a descriptive comment that instructs the next developer about the section
function.
Sample Code
COMMENTS what the
section will do perhaps?
SECTION
Header
During the design of the program you took into consideration various factors.
The IF statement only tests for record type A or B.
What if there was no record, or, you had reached the end of file.
Index
X Close
Back | Next
75
Visual COBOL
06 Best Practice
Truth tables
The program line is divided into distinct column areas each with a specific
function to manage
Question
We will see how we can use truth tables within COBOL later, using the EVALUATE statement.
Now back to our COBOL program to read the data file and produce the results we require!
The input file can contain any number of records, including zero.
There are two types of input records, type A and type B. We will assume that there is a PIC X field on the
record containing the vale A or the value B.
If we find a type A record, create an output record based on that record, and write it out. (No details of record
yet).
If we find a type B record, just increment a type B counter, which will be displayed at the end of the program.
Index
X Close
Back | Next
76
Visual COBOL
06 Best Practice
INPUT FILE
Iteration
*
Record
Selection
TYPE A
Selection
TYPE B
*
Type a
Actions
INIT
BOD
END
9, 2, 3
1, 8, 4
PROCESs
Record
Index
TYPE A
TYPE B
5, 6, 4
7, 4
1) Open Files
2) Close Files
3) Stop Run
4) Read File
5) Set up output record
6) Write output record
7) Add 1 to Type B counter
8) Clear Counters, etc
9) DIsplay Type B counter
X Close
Back | Next
77
Visual COBOL
06 Best Practice
Module Summary
Now you have completed this module, you will be able to:
Exercise 1
In relation to the program shown above, look at the following:
Index
X Close
Back | Next
78
Visual COBOL
06 Best Practice
BOD Perform PROCESS-REC until the flag is true. If the file was empty, then the flag is already true and the
PERFORM wont happen at all.
END Display the type B counter [9], which must be getting updated elsewhere, close the files [2] (again, lets
assume that this is a good thing to do), and stop the run [3].
PROCESS-REC If the record we have at the moment is a Type A, Perform Type-A; else Perform Type-B.
TYPE-A Set up the output record (presumably by copying values from the input record) [5], and write an
output record [6]. Try and read another record [4]. This read will either succeed (in which case we go round the
loop again) or fail because of the end-of-file (in which case we have finished the loop).
TYPE-B Add 1 to the type B counter [7], and try and read another record [4], as above. Again the same
logic applies. If we find a record, we go round again; if not, we leave the PERFORM.
Exercise 2
Create a structure diagram for each example below.
1. A dinner party with a number of guests, each of whom is either male or female.
2. A dinner party, where only couples are invited.
3. The meal at the dinner party. The starter is quails egg salad, langoustines or vegetable terrine. Next, include a
main course of steak (well-done, medium rare, or rare) with vegetables (and either French fries or salad) or
spinach and aubergine bake. Guests may drink one or more glasses of wine with this portion of the meal.
Peaches in Armagnac or lime and durian ice cream make the final course. (Both the first and third courses are
optional).
Finally, everyone can have one or more cups of coffee (black or with cream) or a liqueur.
4. The train (now passenger, not goods) with first- and standard-class carriages, a buffet car, and an extra
locomotive at the rear.
5. A holiday that consists of a flight at the beginning and a return flight at the end. Between those two events are
days where the holidaymaker goes to the beach, takes a coach trip, or goes shopping. Allow for the luggage
missing on the flight out.
6. An encyclopedia that consists of many volumes, each containing many articles. Each volume has a table of
contents and an index. A supplementary volume also has a table of contents and index of all the volumes
together with an atlas.
7. A persons life, defined in different ways. Firstly, draw a structure showing the person going to school (more than
one, possibly) and college, getting a job, and having a working life, followed by retirement. After you have done
this, produce a totally different structure, showing the person getting married, having children, and grandchildren.
Index
X Close
Back | Next
79
Visual COBOL
06 Best Practice
Exercise 3
Load the solution 06_01_Program_Design.sln and look at the logic of the code in the program.
This program is incomplete since the full program code has not yet been fleshed out.
A fully fleshed out solution can be found in 06_02_Program_Design_full.sln. Inside this solution you will find
code that we have not yet fully explored, but you may want to look through this code for now. Full details of what
the code is doing will be discussed later.
The best was to look at this code is probably to debug the code using F11.
The only part of file handling you need to understand at this time is that when you READ a sequential file is that
you read the next record on the file.
The contents of this file are:
Index
X Close
Back | Next
80
Visual COBOL
06 Best Practice
Quick Quiz
1. When designing a program the first task we undertake is:
a. Make a list of actions the program must perform
b. Start writing the code
c. Think about the comments you can use
d. Design the structure of the program
2. If a file is input to a program it must contain at least 1 record?
a. TRUE
b. FALSE
3. A file which is output from a program must already exist?
a. TRUE
b. FALSE
Index
X Close
Back | Next
81
Visual COBOL
Handling
Sequential
Data Files
Index
X Close
Back | Next
82
Visual COBOL
Introduction
At the end of the previous module you had a glimpse of how sequential files are handled in COBOL.
The ability to easily and flexibly handle data files is central to commercial computing needs and, not coincidentally,
to COBOL.
The language regards files as either sequential or random access. Here, we look at the constructs and techniques
for handling sequential files effectively.
Module Objectives
Upon successful completion of this module, you will:
Use the Environment Division and Data Division entries in a COBOL program that uses input or output
sequential files.
Use the correct format of READ, WRITE, OPEN and CLOSE statements in the Procedure division for sequential
files, including testing for an end-of-file condition.
Describe how COBOL deals with multiple record types on the same file.
Be able to design and code a typical COBOL program that handles sequential files.
Sequential.
Relative.
Indexed.
Index
X Close
Back | Next
83
Visual COBOL
A sequential file is a file containing records that must be retrieved in the order first to last in sequence.
We will take the program from the previous module and examine it in more detail.
We shall also examine the way that COBOL deals with multiple record types, within an input or output file.
Connecting Files
Before opening a file in your program, you must first establish its identity in your program and specify its layout so
your program can access it appropriately. This is done in two steps and two places within a program.
Identify a file within the ENVIRONMENT DIVISION using a SELECT statement.
Specify a files layout within the DATA DIVISION.
Identifying Files
The ENVIRONMENT DIVISION has not been used up until now. Now, we must identify the file to our program using
a SELECT statement.
The SELECT statement must be included in the INPUT-OUTPUT SECTION of the ENVIRONMENT DIVISION.
The INPUT-OUTPUT SECTION contains an entry for each file.
The following code shows an entry for two files:
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT INFILE ASSIGN INNAME
ORGANIZATION SEQUENTIAL.
SELECT OUTFILE ASSIGN OUTNAME
ORGANIZATION SEQUENTIAL.
Index
X Close
Back | Next
84
Visual COBOL
This SELECT statement assigns the INNAME file with an internal file on your system.
While the Division and Section entries begin in Area A, the file entries should start in Area B.
An alternative method for assigning filenames, directly in the program, is shown below:
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT INFILE ASSIGN C:\COBOLClass\DataFiles\TEMPIN.DAT.
SELECT OUTFILE ASSIGN C:\COBOLClass\DataFiles\TEMPOUT.DAT.
Each file needs its own SELECT statement.
Each of them should be terminated with a period.
Any input file must exist, while an output file might not exist. If it does, by default the program overwrites it and
loses existing records.
Although we have now told the program that we are going to access one or more files, the program needs detail of
the data on the records within the file(s).
This information appears in the DATA DIVISION, inside the FILE SECTION.
Index
X Close
Back | Next
85
Visual COBOL
OPEN
READ
WRITE
CLOSE
OPEN and CLOSE are always used before and after file access.
Index
X Close
Back | Next
86
Visual COBOL
A file cannot be written unless it has been opened for either output or extend.
INFILE
INFILE
OUTPUT OUTFILE
Two types of access include INPUT and OUTPUT; there are other types, but we need only these two for now.
Notice again that the names used with the verbs are those associated with both the SELECT and FD entries.
When opening for input
The file would not normally exist, since the file will be created with the OPEN OUTPUT statement, thereby
deleting the existing file.
If it does exist, it can be opened to overwrite the current data if you require.
Alternatively it can be opened to append to the current data using the OPEN EXTEND statement.
Index
X Close
Back | Next
87
Visual COBOL
You may remember that we mentioned that by default COBOL clears output files if they exist.
This is what OPEN OUTPUT does. If you instead write OPEN EXTEND, a pointer is positioned at the end of any
existing records, and new records are added to the end of the file. e.g.
OPEN EXTEND OUTFILE
Note: If you try to open a file that is already opened, you will get a run-time error.
The READ verb
The file to be READ must have been opened as input.
The READ of a sequential file reads the next record in the file (At the start of the file, it reads the first record on file).
The statement should also inform the program what to do when there are no more records to be read. In our
sample solution 06_02_Program_Design_Full.sln the result of a successful read:
AT END
MOVE 1 TO WS-END-OF-FILE
END-READ
If the READ succeeds, that is, if there is a record or another record, the contents of that record will go into all
of the 01 descriptions specified.
In our case, the contents go into the record description of both RECORD-TYPE-A and RECORD-TYPE-B, as
shown in our code previously. (This area is known as the record buffer.) WS-END-OF-FILE will not be touched.
If the read fails, WS-END-OF-FILE will be set to 1. The contents of RECORD-TYPE-A and RECORD-TYPE-B
may be undefined (if there has never been a record) or those of the last record read (if there have been previous
records). Logically, we should not look at them anyway, because there has been no new record read.
Why do we read a file name?
You will notice that the READ statement refers to the file name, not the record name. It is possible that a file may
contain records of two or more types (as is the case for us here). Because this is an input file, we have no idea what
record type is coming in next. All we can do is read the file name.
Index
X Close
Back | Next
88
Visual COBOL
Index
X Close
Back | Next
89
Visual COBOL
Exercise 1
In the previous module we briefly saw the solution 06_02_Program_Design_full.sln.
Now load this solution and study its behaviour, in debug mode, using the knowledge that you have obtained so far
in this module.
How would you alter the program to add to the end of the output file, each time the program is run?
Have AT END.
e.g.
READ INFILE
AT END
MOVE 1 TO WS-EOF
NOT AT END
PERFORM GOT-A-RECORD
END-READ
It can also be extended to READ a record directly into a working-storage data item.
Index
X Close
Back | Next
90
Visual COBOL
INFILE DATA
DATA DIVISION.
FD INFILE
01 INREC PIC X(34).
WORKING-STORAGE SECTION.
01 WS-INREC.
05 WS-EMP-NO
PIC 9(6).
05 WS-START-DATE PIC 9(8).
05 WS-NAME
PIC X(20).
PROCEDURE DIVISION.
...
PROCESS-REC.
READ INFILE INTO WS-INREC
AT END
MOVE Y TO WS-END-OF-FILE
END-READ
DATA DIVISION.
FD OUTFILE
01 OUTREC PIC X(34).
OutFILE DATA
WORKING-STORAGE SECTION.
01 WS-OUTREC.
05 WS-EMP-NO
PIC 9(6).
05 WS-START-DATE PIC 9(8).
05 WS-NAME
PIC X(20).
PROCEDURE DIVISION.
...
PROCESS-REC.
WRITE OUTREC FROM
WS-OUTREC.
Points to remember.
Index
X Close
Back | Next
91
Visual COBOL
If you use READ INTO, make sure your working-storage item is big enough to handle the largest record.
If you use WRITE FROM, make sure the working-storage item complies with the record length you require.
You can think of a READ INTO and WRITE FROM as 2 statements. In that way you will avoid any size mistakes.
So for a READ
READ INFILE INTO WS-INREC
is exactly the same as:
READ INFILE
MOVE INREC TO WS-INREC
For a WRITE
WRITE OUTREC FROM WS-OUTREC
is exactly the same as:
MOVE WS-OUTREC TO OUTREC
WRITE OUTREC
Module Summary
Now you have completed this module, you can:
Use the Environment Division and Data Division entries in a COBOL program that uses input or output
sequential files.
Use the correct format of READ, WRITE, OPEN and CLOSE statements in the Procedure division for sequential
files, including testing for an end-of-file condition.
Describe how COBOL deals with multiple record types on the same file.
Be able to design and code a typical COBOL program that handles sequential files.
Index
X Close
Back | Next
92
Visual COBOL
Exercise 2
There is a solution 07_01_multi_records.sln which you should load. The program in here illustrates many of the
features we have defined above.
The purpose of this program is to read an employee file, create two output files and display a counter.
One file will contain the normal employee records; the other file will contain records for each employee leaving the
company and a control record at the end of the file.
The program will also count and display the number of records written to both output files.
Study this program to ensure that you understand all the processing.
Exercise 3
There is another solution 07_02_multi_records2.sln which is similar to the last. You may find it useful to step
through the code in this program to re-emphasise the way that sequential files are processed.
You will notice that there are a few comments on the program. You will see we have used a level 88 data name
(this is a condition name), also look at the SET statement to set the condition to true. We will discuss these later
in the class.
Quick Quiz
1. Name the five verbs used in sequential data file handling
2. How is a data file appended to, rather than overwritten?
3. How is the empty file event handled when opening a file for input?
4. You wish to retrieve data from a file, which of the following statements would you most likely use?
a. READ INFILE INTO OUTREC
b.
READ INFILE AT END MOVE Y TO WS-EOF
c. READ INREC AT END MOVE Y TO WS-EOF
d. WRITE OUTREC FROM INREC .
5. Which of the following is true of an AT END clause after a READ?
a. It must be terminated with a period
b. It must be terminated with an AT END
c. It does not need to be terminated
d. It must be terminated with something
6. AT END can be used with both a READ and WRITE?
a. TRUE
b. FALSE
Index
X Close
Back | Next
93
Visual COBOL
Index
X Close
Back | Next
94
Visual COBOL
Decision Logic
Index
X Close
Back | Next
95
Visual COBOL
08 Decision Logic
Introduction
Implementing the required decision logic in a program effectively means higher quality programs, shorter testing
time, and better maintenance productivity.
Here, we understand the different conditional constructs available in COBOL and understand when and how
to use them.
Most programming requires making a choice.
Module Objectives
Upon successful completion of this module, you will be able to:
Use the verb EVALUATE and the IF condition as well as the Level 88 construct in testing conditions.
The IF statement
The following is a simple IF Statement
IF [condition] (THEN)
[do one or more statements]
(ELSE)
[do one or more statements])
(END-IF)
The entries in round brackets ( ) are optional.
This code indicates that if a condition is true, then perform an action.
Otherwise (if the condition is false), do a different action.
Lastly, END-IF marks the end of the conditional statement. Prior to 1985 a period denotes the end of the IF).
Index
X Close
Back | Next
96
Visual COBOL
08 Decision Logic
Condition phrases
In the above sample IF statement, the condition phrase can take a number of forms:
Relational conditions
Class conditions
Sign conditions
Condition-name conditions (Level 88s)
Compound conditions
Nested conditions
Relational conditions
A relational condition compares two or more operands, for example:
IF CUSTOMER-AGE < 21
DISPLAY CUSTOMER TOO YOUNG
END-IF
You can also use the NOT to negate the condition, for example:
IF PARENTS-CONSENT NOT = YES
DISPLAY NO CONSENT GIVEN
END-IF
In some cases we might want to determine whether a data is not equal to something.
Prior to 1985 no equivalent existed for <>, which means not equal; however, we could express it in one of the
following ways.
IF
IF
IF
IF
WS-TOTAL
WS-TOTAL
WS-TOTAL
WS-TOTAL
NOT = 6
UNEQUAL 6
NOT EQUAL TO 6
<> 6
Relational conditions are clear when comparing numeric items. However, relational comparisons are also
completely valid for comparing alphanumeric items.
is less than A
For the first four bytes FRED and FREDA are equal.
Index
X Close
Back | Next
97
Visual COBOL
08 Decision Logic
Index
X Close
Back | Next
98
Visual COBOL
08 Decision Logic
INREC.
03 INREC-AGE
PIC 99.
88 VALID-AGE
VALUE 13 THRU
88 TEEN
VALUE 13 THRU
88 YOUNG-ADULT
VALUE 20 THRU
88 STILL-YOUNGISH
VALUE 30 THRU
88 PAST-IT
VALUE 40 THRU
IF NOT VALID-AGE
DISPLAY TOO YOUNG TO JOIN FACEBOOK!
END-IF
IF PAST-IT
PERFORM MAKE-TEXT-BIGGER-FOR-OLD-EYES
END-IF
IF TEEN
PERFORM TREAT-WITH-CARE
END-IF
IF YOUNG-ADULT
PERFORM NOT-TO-BAD
END-IF
IF STILL-YOUNGISH
PERFORM BUY-A-DRINK
END-IF
99.
19.
29.
39.
99.
WS-GENDER
88 FEMALE
88 MALE
PIC X.
value F f.
value M m.
01
01
INREC.
03 INREC-TYPE
PIC
88 VALID-TYPES
88 CEO
88 VICE-PRESIDENT
88 SENIOR-MANAGER
88 MANAGER
88 TEAM-MEMBER
88 JANITOR
88 TRAINER
Index
X.
VALUE
VALUE
VALUE
VALUE
VALUE
VALUE
VALUE
VALUE
X Close
A THRU E G Z.
A.
B.
C.
D.
E.
G.
Z.
Back | Next
99
Visual COBOL
08 Decision Logic
WS-END-OF-FILE
PIC 9 VALUE 0.
88 NO-MORE-RECORDS
VALUE 1.
PERFORM PROCESS-REC UNTIL NO-MORE-RECORDS
[other code]
READ INFILE
AT END
SET NO-MORE-RECORDS TO TRUE
END-READ
Using LEVEL 88s encourages more English-like statements in the PROCEDURE DIVISION.
The code:
PERFORM PROCESS-REC UNTIL NO-MORE-RECORDS
is clearer than:
PERFORM PROCESS-REC UNTIL WS-END-OF-FILE IS NOT EQUAL TO ZERO
Compound Conditions
To test more than one condition at once, use compound conditions in your IF statement:
IF WS-TOT-3 = 5 OR WS-SUM-X > 22
IF WS-TOTAL > 23
OR WS-FINAL = 444
When using AND and OR in the same test always use brackets for clarity, so that the condition in brackets is
evaluated before anything else. e.g. the following 3 IFs all behave differently. So make sure you use brackets for
clarity:
IF WS-TOTAL > 23 AND WS-SUM = 200 OR WS-FINAL = 444
IF (WS-TOTAL > 23 AND WS-SUM = 200) OR (WS-FINAL = 444)
IF (WS-TOTAL > 23) AND (WS-SUM = 200 OR WS-FINAL = 444)
Nested Conditions
It is possible to nest IF statements as you can see in this example:
IF INREC-JOB-TITLE = MANAGER
IF INREC-SALARY > 50000
IF INREC-START-DATE < 20000101
[actions1]
ELSE
[actions2]
END-IF
ELSE
[actions3]
Index
X Close
Back | Next
100
Visual COBOL
08 Decision Logic
ELSE
[actions4]
END-IF
Such statements, even when indented as shown, can be difficult to understand, and used to be avoided before
END-IF became available after 1985.
The NEXT SENTENCE clause
The next sentence clause is used to exit an IF statement. e.g.
IF DATA-NAME = FRED
NEXT SENTENCE
ELSE
ADD 1000 TO WS-NUMBER
END-IF
Simple EVALUATE
This simple evaluate tests the values in a data item and behaves as appropriate.
EVALUATE INREC-TYPE
WHEN A THRU D
PERFORM MANAGER-STUFF
WHEN E
PERFORM OTHER-CODE
WHEN G
PERFORM JANITOR-CODE
WHEN Z
PERFORM TRAINER-FUNCTIONS
WHEN OTHER
PERFORM INVALID-RECORD
END-EVALUATE
The WHEN OTHER clause is very useful in an EVALUATE statement, as it is a catch-all for when none of the
conditions specified are met.
This often indicates invalid data or, at the very least, something the programmer did not expect to happen.
Index
X Close
Back | Next
101
Visual COBOL
08 Decision Logic
Condition EVALUATE
The following code tests three conditions using the Evaluate True version:
When one of these conditions is true, then the EVALUATE is true and the condition-specific action is taken.
Once one condition is tested and found true, then the Evaluate terminates (the other tests are ignored). So in
the above example, if both NO-MORE-RECORDS is true and WS-COUNTER = 99 then only the first condition
NO-MORE-RECORDS would be acted upon.
The EVALUATE statement can be much simpler to code and much easier to read than a series of nested
IF statements.
Index
X Close
Back | Next
102
Visual COBOL
08 Decision Logic
CUSTOMER-TITLE
PIC X(4).
88 MALE-TITLE
VALUE MR.
88 FEMALE-TITLE
VALUE MRS MISS MS.
EVALUATE TRUE
WHEN MALE-TITLE
CONTINUE
WHEN FEMALE-TITLE
PERFORM FEMALE-CUST
WHEN OTHER
PERFORM INVALID-TITLE
END-EVALUATE
Infinite loops
As in any other programming language, you can produce loops that never terminate.
Example 1:
01
MY-COUNTER
PIC 99.
MAIN-PROCESS.
PERFORM PROCESS-DATA
VARYING MY-COUNTER FROM 1 BY 1 UNTIL MY-COUNTER > 100
In this example MY-COUNTER can never reach 100 since the data item is only 2 bytes. When it reaches 99 and then
is increment by 1, the data item will revert to 0.
The solution would be to make MY-DATA a PIC 999.
Index
X Close
Back | Next
103
Visual COBOL
08 Decision Logic
Index
X Close
Back | Next
104
Visual COBOL
08 Decision Logic
Module Summary
Now you have completed this module, you will be able to:
Use the verb EVALUATE and the IF condition as well as the Level 88 construct in testing conditions.
Exercise 1
You should first load the solution 08_01_Decision_Making1.sln.
This solution contains 2 programs:
DecisionMakingProgram1.cbl
DecisionMakingProgram2.cbl
You should first examine DecisionMakingProgram1.cbl and execute it in debug mode to see how the IFs and
EVALUATEs are working.
To debug this first program, press F11 and you will be prompted for which program you want to debug.
When you are happy with an understanding of DecisionMakingProgram1 then you need to do the same with
DecisionMakingProgram2. This program is very similar to the previous program, but with slight changes.
In both cases you should ask yourself the following questions:
1. How is the record type validated?
2. Do any of the 88 levels overlap? Does this create any problems?
3. If you look at the output files, can you see anything wrong with the Special records? If you can, how would
you fix this?
Exercise 2
You are going to write a program whose purpose program is to read the employee records and create three output
files. Each will contain records of employees within a range of salaries; either low medium or high.
This program should also count and display the number of employees in each category.
Additionally, this program should evaluate the TYPE code on each record, rejecting and displaying invalid records.
The steps to follow are:
1. Open the solution 08_02_Decision_Making2.sln from C:\COBOLClass\Projects\08_02_Decision_
Making2
Index
X Close
Back | Next
105
Visual COBOL
08 Decision Logic
08_04_Evaluate_True (test14.sln)
08_05_Evaluate_positive (test36.sln)
Index
X Close
Back | Next
106
Visual COBOL
08 Decision Logic
Quick Quiz
1. The EVALUATE statement must be terminated by?
a. END-EVALUATE
b. A period
c. Either of the above
d. Neither of the above
2. Which of the following is true?
a. The NEXT SENTENCE clause is used in an IF statement
b. The CONTINUE clause can be used in an EVALUATE statement
c. Neither is true
3. In order to test a numeric field for positive or negative the field has to be a signed field?
a. TRUE
b. FALSE
4. Condition names can only apply to an elementary data item?
a. TRUE
b. FALSE
5. When comparing two PIC X(n) fields, they must both be the same size?
a. TRUE
b. FALSE
6. If you are using nested IF statements a period terminates ALL the Ifs?
a. TRUE
b. FALSE
7. You can change the value in a condition name at run time?
a. TRUE
b. FALSE
8. The catchall in an evaluate statement is:
a. WHEN ANY
b. WHEN OTHER
c. WHEN NEITHER
d. There is no catchall statement
Index
X Close
Back | Next
107
Visual COBOL
Data Manipulation
Index
X Close
Back | Next
108
Visual COBOL
09 Data Manipulation
Introduction
Understanding the full range of the data manipulation constructs available in COBOL means more efficient
programming and maintenance.
This module examines the set of COBOL verbs available to manipulate both arithmetic and character data.
Module Objectives
By the end of this module you will be able to:
Use the various arithmetic COBOL verbs, such as ADD, SUBTRACT, MULTIPLY, DIVIDE and COMPUTE.
Use the verbs for manipulating character data, such as INSPECT, STRING and UNSTRING.
Manipulating Data
The COBOL verbs available for data manipulation fall into three distinct groups:
The INITIALIZE verb, which can be used on both numeric and character data
This module also explains how to extract a substring from a string using reference modification.
WS-DATA-ITEMS.
03 WS-NAME
03 WS-SALARY
03 WS-RECORD-COUNT
03
03 WS-ADDRESS
INITIALIZE WS-DATA-ITEMS
Index
PIC
PIC
PIC
PIC
PIC
X(20).
9(6)V99.
9(4) COMP.
X(40).
X(80).
X Close
Back | Next
109
Visual COBOL
09 Data Manipulation
Arithmetic verbs
There are five verbs that we shall consider:
ADD (2 formats).
SUBTRACT (2 formats).
MULTIPLY (2 formats).
DIVIDE (5 formats).
COMPUTE.
Many of these verbs have alternate formats. We will look though each briefly.
Before that, here are some general points:
Index
X Close
Back | Next
110
Visual COBOL
09 Data Manipulation
WS-WEEKLY-SALES TO WS-MONTHLY-SALES
WS-MONTHLY-SALES TO WS-YEARLY-SALES WS-CENTURY-SALES
RESULT-1 RESULT-2 10000 TO WS-TOTAL
2000 TO EMPLOYEES-SALARY
This means that the operand or operands to the left of the TO are added to the field or fields to the right of the
TO, incrementing them.
The fields or literals to the left are unchanged.
The receiving field or fields (to the right of the TO) are formatted according to their PICTURE clauses.
If you want to apply rounding to any of these, you add the word ROUNDED at the end of the line. e.g.
ADD RESULT-1 RESULT-2 10000 TO WS-TOTAL ROUNDED
Using ROUNDED, not surprisingly, rounds the answer according to the number of decimal places specified in the
receiving field.
ADD Format 2
Examples:
ADD WS-WEEKLY-SALES TO WS-MONTHLY-SALES GIVING WS-TOTAL-SO-FAR
ADD WS-WEEK1 WS-WEEK2 WS-WEEK3 WS-WEEK4 250 TO WS-ALL-WEEKS
GIVING WS-TOTAL1 WS-TOTAL2
ADD 100 200 300 400 GIVING WS-ADDITION
As above, if you want to apply rounding to any of these, you add the word ROUNDED at the end of the line. e.g.
ADD 10.01 202.34 305.11 498.32 GIVING WS-ADDITION ROUNDED
SUBTRACT Format 1
Examples:
SUBTRACT 10 FROM WS-TOTAL1 WS-TOTAL2
SUBTRACT WS-TOTAL1 WS-TOTAL2 FROM WS-SALARY
The value in the field or fields to the left of the FROM are added together if appropriate. That total value is
subtracted from the field or fields to the right of the FROM.
As above, if you want to apply rounding to any of these, you add the word ROUNDED at the end of the line.
Index
X Close
Back | Next
111
Visual COBOL
09 Data Manipulation
In this format, the value of the operand (field or literal) before the BY is multiplied by the values in the field or fields
after the BY, and the result is moved to the field(s) after the BY.
NOTE: The following would be incorrect using this format.
MULTIPLY EMPLOYEE-SALARY BY 1.01
Why not? Format 1 stores the results of the multiply in the operand after the BY. Also, 1.01 is a literal and cannot
be used to store data.
As shown in the below, you can also include multiple fields after the BY so that the operand before the BY is
multiplied by the fields after the BY.
MULTIPLY 1.01 BY EMPLOYEE-SALARY MANAGER-SALARY
The results are stored in both EMPLOYEE-SALARY and MANAGER-SALARY.
Rounding, of course, behaves the same way as in ADD and SUBTRACT.
Index
X Close
Back | Next
112
Visual COBOL
09 Data Manipulation
Format 3: DIVIDE BY
DIVIDE Format 1
Examples:
Index
X Close
Back | Next
113
Visual COBOL
09 Data Manipulation
This time the result goes into the field or fields after the GIVING.
DIVIDE Format 3
This format reverses the operands used in DIVIDE...INTO.
Examples:
GIVING WS-NUM-1
GIVING WS-MONTHLY-AVERAGE ROUNDED
This yields the same result as the Format 2 statement above. Again multiple receiving fields can exist after the
GIVING.
DIVIDE Format 4
This format uses a remainder, so the fields need to be integers with no decimal places.
Example:
DIVIDE WS-COUNT INTO WS-TOTAL GIVING WS-NUM-1 REMAINDER WS-REM
DIVIDE Format 5
This format also uses a remainder, so the fields need to be integers with no decimal places as above.
Example:
DIVIDE WS-TOTAL BY WS-COUNT GIVING WS-NUM-1 REMAINDER WS-REM
COMPUTE Format
COMPUTE has the receiving field(s) on the left of the statement.
It uses the standard operands +, -, /, * and ** (exponentiation).
COMPUTE used to be a comparatively inefficient verb and was not used too much in the past. This is no longer the
case with modern compilers.
Examples:
COMPUTE WS-TOTAL = (WS-NET-PAY + (WS-OVERTIME * WS-OT-HRS)) * (100 - WS-TAX-RATE)
COMPUTE WS-MONTH ROUNDED = WS-YEAR / 12.
COMPUTE STAR-LUMINOSITY ROUNDED = 10 ** (0.4 * (4.85 - WS-ABS-MAG))
Index
X Close
Back | Next
114
Visual COBOL
09 Data Manipulation
Exponentiation
In practice, use brackets, wherever possible, to clarify order to you and anyone else who may have to amend your
code in the future.
NOTE: Specify ROUNDED after a receiving field in the normal way.
Index
X Close
Back | Next
115
Visual COBOL
09 Data Manipulation
The examples shown here are using the COMPUTE statement. This clause can be used in any of the other
arithmetic operators also. Because this results in ADD, SUBTRACT, MULTIPLY and DIVIDE becoming conditional
statements, the following terminators are appropriate:
END-ADD
END-SUBTRACT
END-MULTIPLY
END-DIVIDE
INSPECT
STRING
UNSTRING
INSPECT Statement
This statement can be used to look at a string of data and optionally to manipulate it. There are four formats:
In the following examples, we shall use the same fields with the same initial values.
INSPECT Format 1Tallying
Example:
01
01
WS-COUNTS.
03 WS-COUNT-1
03 WS-COUNT-2
03 WS-COUNT-3
WS-STRING
PIC
PIC
PIC
PIC
99.
99.
99.
X(20) VALUE AARDVARK EXTRA.
INITIALIZE WS-COUNTS
INSPECT WS-STRING TALLYING WS-COUNT-1 FOR LEADING A
WS-COUNT-2 FOR ALL R
WS-COUNT-3 FOR CHARACTERS
After the INSPECT statement, the values of the data items will be:
WS-COUNT-1
WS-COUNT-2
WS-COUNT-3
WS-STRING
Index
2
3
14
AARDVARK EXTRA
X Close
Back | Next
116
Visual COBOL
09 Data Manipulation
WS-COUNT-1
0
WS-COUNT-2
0
WS-COUNT-3
0
WS-STRING BASDVARK EXTSA
WS-COUNT-1
0
WS-COUNT-2
0
WS-COUNT-3
0
WS-STRING AAQDUAQK EWTQA
Index
X Close
Back | Next
117
Visual COBOL
09 Data Manipulation
WS-COUNT-1
0
WS-COUNT-2
0
WS-COUNT-3
7
WS-STRING AARDVARK EXTRA
STRING Statement
STRING can be used to concatenate character strings, removing unwanted spaces. For example:
01
01
WS-FIELDS.
03 WS-FIRST-NAME
03 WS-SURNAME
03 WS-SALARY
WS-OUTPUT-NAME
PIC
PIC
PIC
PIC
STRING WS-FIRST-NAME
*
WS-SURNAME
DELIMITED BY SPACE
INTO WS-OUTPUT-NAME
INSPECT WS-OUTPUT-NAME REPLACING ALL * BY SPACE
The result of the STRING and INSPECT statements will place the following value into WS-OUTPUT-NAME:
BEOWOLF SHAEFFER
Here, DELIMITED BY SPACE means to process all the characters in the string until a space is encountered.
So, WS-FIRST-NAME and WS-SURNAME are truncated to the right length.
However, we want a space between the two. We cant specify , as DELIMITED BY SPACE will instantly remove it.
Instead, we specify an asterisk or any other character that will not be found in either part of the name.
Because * does not contain a space, the whole thing is moved.
String Delimit options:
DELIMITED BY {character}
DELIMITED BY SIZE
Index
X Close
Back | Next
118
Visual COBOL
09 Data Manipulation
01
WS-POINTER
PIC 9(4).
WS-FIELDS.
03 WS-FIRST-NAME
03 WS-SURNAME
03 WS-SALARY
WS-OUTPUT-NAME
PIC
PIC
PIC
PIC
INITIALIZE WS-OUTPUT-NAME
MOVE 1 TO WS-POINTER
STRING WS-FIRST-NAME
*
WS-SURNAME
DELIMITED BY SPACE INTO WS-OUTPUT-NAME
POINTER WS-POINTER
ON OVERFLOW
PERFORM TOO-BIG
NOT ON OVERFLOW
PERFORM OK-ACTIONS
END-STRING
As you might recall from discussions about the MOVE verb, MOVE space fills a receiving field if the value received
is too small.
Since STRING does not do this, it is best to initialize the receiving field, and then use POINTER and ON
OVERFLOW clauses, as illustrated above.
After this statement, POINTER contains 17, the number of the next free byte (which is why we set it to 1 at the
beginning).
Note: Specifying POINTER in this way requires setting it to a positive value at the start, or nothing will appear in the
output string.
The ON OVERFLOW clause is triggered if the STRING is impossible because the number of characters being
transferred is too large for the receiving field.
ON OVERFLOW will also be triggered if a POINTER clause cannot occur, which would happen if the pointer field is
less than 1 or greater than the number of bytes in the receiving field.
UNSTRING Statement
UNSTRING uses delimiters to divide up a string of characters. For example:
01
01
INPUT-NAME
RECEIVING-FIELDS.
03 R-FIELD-1
Index
X Close
Back | Next
119
Visual COBOL
09 Data Manipulation
R-FIELD-2
R-FIELD-3
PIC X(12).
PIC X(12).
The UNSTRING format, as you might expect, works in the opposite way to STRING. Use it to divide up a string of
characters.
It works by recognizing delimiter characters.
Reference Modification
Reference modification allows you to examine or modify part of a string. For example:
01
01
WS-ALPHABET
PIC X(26) VALUE ABCDEFGHIJKLMNOPQRSTUVWXYZ.
WS-SMALLER-STRING PIC X(10) VALUE SPACES.
MOVE WS-ALPHABET(12:6) TO WS-SMALLER-STRING.
Module Summary
At the end of this module you should now be able to:
Use the various arithmetic COBOL verbs, such as ADD, SUBTRACT, MULTIPLY, DIVIDE and COMPUTE.
Use the verbs for manipulating character data, such as INSPECT, STRING and UNSTRING.
Exercise 1
Check out the following syntax.
UNSTRING [field]
DELIMITED BY (ALL) [literal or field name]
OR (ALL) [literal or field name] etc.)
INTO [field name]
Index
X Close
Back | Next
120
Visual COBOL
09 Data Manipulation
UNSTRING can use many different potential delimiters to separate out each substring.
In each case, the field specified by DELIMITER holds the actual delimiter used.
POINTER keeps track of the total number of bytes moved over. As with STRING, set it to a positive value
before the statement takes place.
TALLYING IN keeps count of the total number of receiving fields that contain data when the UNSTRING
finishes.
ON OVERFLOW and NOT ON OVERFLOW are as before.
Further Questions
1. Why must POINTER be set to a positive value?
2. Which is likely to be the more useful clause, ON OVERFLOW or NOT ON OVERFLOW?
Exercise 2
There is a solution 09_01_DataManipulation.sln which you should now load. This is bringing together much of
what you have seen so far. Spend some time looking at the program in here. Debugging is a good way to study it.
(You will see a feature we have not described yet that is the use of PIC Z for zero suppression. This will be covered
shortly).
Exercise 3
1. Here is the specification for the program, followed by the code itself.
2. The program reads in a file of sales staff records and does the following:
a. The input file may have any number of records (including 0).
b. All input records contain a one-character region (N, S, E or W), and an eight-digit sales total field (six
digits, two decimal places).
c. Generate four totals, one for each region. As each record is read, update the appropriate total with the value
in the sales total.
d. At the end of the program, all totals display, along with average sales for each region. We therefore need a
record count for each region.
Index
X Close
Back | Next
121
Visual COBOL
09 Data Manipulation
Index
INFILE.DAT.
PIC X.
VALUE N.
VALUE S.
VALUE E.
VALUE W.
PIC 9(6)V99.
PIC 9 VALUE 0.
VALUE 1.
VALUE ZERO.
PIC 9(4).
PIC 9(4).
PIC 9(4).
PIC 9(4).
PIC 9(10)V99.
PIC 9(10)V99.
PIC 9(10)V99.
PIC 9(10)V99.
PIC 9(6)V99.
PIC 9(6)V99.
PIC 9(6)V99.
PIC 9(6)V99.
X Close
Back | Next
122
Visual COBOL
09 Data Manipulation
WS-EDITED-FIELDS.
03 WS-EDITED-N
PIC Z(5)9.99.
03 WS-EDITED-S
PIC Z(5)9.99.
03 WS-EDITED-E
PIC Z(5)9.99.
03 WS-EDITED-W
PIC Z(5)9.99.
01 WS-MESSAGE
PIC X(80).
PROCEDURE DIVISION.
PROG-PARA.
PERFORM INIT-PARA.
PERFORM BOD-PARA.
PERFORM END-PARA.
INIT-PARA.
DISPLAY STARTING CALCULATION PROGRAM.
OPEN INPUT INFILE.
READ INFILE
AT END MOVE 1 TO WS-EOF.
BOD-PARA.
PERFORM PROCESS-REC UNTIL END-OF-FILE.
END-PARA.
IF WS-N-RECORDS > 0
DIVIDE WS-N-TOTAL BY WS-N-RECORDS
GIVING WS-N-AVERAGE ROUNDED
END-IF
IF WS-S-RECORDS > 0
DIVIDE WS-S-TOTAL BY WS-S-RECORDS
GIVING WS-S-AVERAGE ROUNDED
END-IF
IF WS-E-RECORDS > 0
DIVIDE WS-E-TOTAL BY WS-E-RECORDS
GIVING WS-E-AVERAGE ROUNDED
END-IF
IF WS-W-RECORDS > 0
DIVIDE WS-W-TOTAL BY WS-W-RECORDS
GIVING WS-W-AVERAGE ROUNDED
END-IF
MOVE SPACES TO WS-MESSAGE.
STRING WS-N-RECORDS N RECORDS,
WS-S-RECORDS S RECORDS,
WS-E-RECORDS E RECORDS,
WS-W-RECORDS W RECORDS
INTO WS-MESSAGE.
DISPLAY WS-MESSAGE.
MOVE WS-N-AVERAGE TO WS-EDITED-N
MOVE WS-S-AVERAGE TO WS-EDITED-S
MOVE WS-E-AVERAGE TO WS-EDITED-E
MOVE WS-W-AVERAGE TO WS-EDITED-W
MOVE SPACES TO WS-MESSAGE.
Index
X Close
Back | Next
123
Visual COBOL
09 Data Manipulation
36787.15
Optional Exercises
There are a number of other simple solutions that you may choose to study, to gain further familiarity with the
features we have described so far. These are:
09_02_Initialize replacing
09_03_Inspect Tallying
Index
X Close
Back | Next
124
Visual COBOL
09 Data Manipulation
Quick Quiz
1. What are the five verbs that can be used to perform arithmetic calculations?
2. Three of the verbs share the same number of formats what is this number?
3. Is rounding on or off by default?
4. What are the three string manipulation verbs in COBOL?
5. What verbs use DELIMITED BY?
6. Which of the following arithmetic statements are syntactically correct?
a. ADD WS-ITEM-1 WS-ITEM-2 TO WS-ITEM-4 AND WS-ITEM-5.
b. OMPUTE WS-RESULT = 2.667 * 5.4334 ROUNDED.
c. MULTIPLY CEO-SALARY BY 1.1.
d. ADD 2.3 -11 TO WS-RESULT-1 WS-RESULT-2.
Index
X Close
Back | Next
125
Visual COBOL
Repeating Data
Index
X Close
Back | Next
126
Visual COBOL
10 Repeating Data
Introduction
Intelligent use of multi-dimensional tables can rapidly speed up program development and add clarity to application
logic for maintenance programmers.
Here we become familiar with the COBOL constructs for defining and manipulating these tables.
Module Objectives
By the end of this module you will be able to:
Name
Salary
MONTHLY-SALES
SALES-RECORD.
03 SALES-NAME
03 SALES-SALARY
03 SALES-WEEK-1
03 SALES-WEEK-2
03 SALES-WEEK-3
03 SALES-WEEK-4
03 SALES-WEEK-5
PIC 9(8)V99
PIC
PIC
PIC
PIC
PIC
PIC
PIC
X(20).
9(6)V99.
9(5)V99.
9(5)V99.
9(5)V99.
9(5)V99.
9(5)V99.
However, this does not express the whole truth (it does not show that there is a repeating field).
If we wanted to calculate the monthly sales figures, we could write code like:
ADD SALES-WEEK-1 SALES-WEEK-2
SALES-WEEK-3 SALES-WEEK-4
SALES-WEEK-5
GIVING MONTHLY-SALES
Index
X Close
Back | Next
127
Visual COBOL
10 Repeating Data
MONTHLY-SALES
SALES-RECORD.
03 SALES-NAME
03 SALES-SALARY
03 SALES-WEEK
PIC 9(8)V99
PIC X(20).
PIC 9(6)V99.
PIC 9(5)V99 OCCURS 5.
A table holds a set of different data items that have the same definition. The items in the table can be accessed
using a reference to the item, called a subscript. A table is defined using the OCCURS clause in the DATA DIVISION.
We could define the information in the previous code using a table, as above. We now have a much cleaner way of
calculating the monthly sales figures:
01
WS-SUB
PIC 9.
The PERFORM verb starts by setting WS-SUB to 1, and as the subscript is not greater than 5, SALESWEEK(1) is added to MONTHLY-SALES (which should have been initialized at some point).
The loop goes around again. WS-SUB is incremented automatically (BY 1) and the second occurrence is
added. This goes on until SALES-WEEK(5) has been added.
The next time around the UNTIL is now true, so the PERFORM stops.
Although this code takes up as many lines on the page as the explicit adding of all five occurrences, it is far
more logical.
Furthermore, it would be very straightforward to modify both the record and the code to cope with 52 entries.
This is using a variation of the PERFORM statement that we have not yet seen. Instead of PERFORMing a
paragraph or section, this version of the PERFORM is called an in-line PERFORM and performs the embedded
code up to the END-PERFORM (This is COBOL, post 1985).
Index
X Close
Back | Next
128
Visual COBOL
10 Repeating Data
Look up tables
Lookup tables are very common in COBOL programs.
The program matches against the first column. t then reads values from the other columns.
The lookup table needs to use an OCCURS, and also VALUE clauses.
VALUE clauses cannot be used with OCCURS, but REDEFINES gets round this restriction. (of course, tables often
get populated by reading from a data file). If the data above was to be hard coded in a COBOL program, then it
would be done as follows:
01
01
WS-PETFOOD.
03
PIC X(22) VALUE 01Dog Food Large
03
PIC X(22) VALUE 02Cat Food Large
03
PIC X(22) VALUE 03Dog Food Medium
03
PIC X(22) VALUE 04Cat Food Medium
03
PIC X(22) VALUE 05Dog Food Small
03
PIC X(22) VALUE 06Cat Food Small
WS-PETFOOD-REDEF REDEFINES WS-PETFOOD.
03 WS-PET-DETAILS OCCURS 6.
05 WS-TABLE-NUM
PIC 99.
05 WS-FOOD-DESCRIPTION PIC X(16).
05 WS-PRICE
PIC 99V99.
2799.
2399.
1750.
1650.
0999.
0899.
Exercise 1
Load the solution 10_01_Repeating_Data.sln
There are 2 programs in this solution. Study both of them and see the way in which repeating data is used.
Indexes
An index is another way of accessing a lookup table (it holds a relative address of the element it is looking at). Each
index can only be associated with a single table. (So if you have multiple tables you will need to define a different
index for each). You do not declare an index as a COBOL filed in data division. Instead by referring to it in the occurs
definition, the declaration happens automatically.
Indexes have two advantages over subscripts:
Index
X Close
Back | Next
129
Visual COBOL
10 Repeating Data
Subscripts v Indexes
This table must be accessed using a subscript:
01
NOTE: To move a value to an index, do not use the MOVE statement; instead, use SET. We shall see this later.
SEARCH starts at the beginning of the table and searches to the end, which is not efficient across large tables.
SEARCH ALL is more efficient because it performs a binary search starting in the middle determining whether the
value is greater or less than the item being searched. This splitting process continues until the SEARCH ALL is
complete. To use SEARCH ALL, the table must be indexed and the elements of the table must be in ascending or
descending sequence.
Exercise 2
Load the solution 10_01_Repeating_Data2.sln
There are 2 programs in this solution, both using indexes. One program uses SEARCH and the other uses SEARCH
ALL.
Study both of them and see the way in which repeating data is used. Look at them in the order:
PetFoodtablesearch.cbl
PetFoodtablesearchall.cbl
Index
X Close
Back | Next
130
Visual COBOL
10 Repeating Data
Multi-dimensional tables
It is possible to have an OCCURS within an OCCURS (two-dimensional table), or even more dimensions, in COBOL.
For example:
01
WS-SALES-DATA.
03 WS-REGION
OCCURS 10.
05 WS-REGION-NAME
PIC X(20).
05 WS-SALESPERSON
OCCURS 20.
07 WS-PERSONS-NAME PIC X(20).
07 WS-PERSONS-SALES PIC 9(5)V99 OCCURS 52.
OUTREC.
03 OUT-NAME
03 OUT-ADDRESS.
05 OUT-ADDR-LINE
03 OUT-COMMENT-COUNT
03 OUT-COMMENTS.
05 OUT-COMMENT-BYTE
Index
PIC X(20).
PIC X(20) OCCURS 3.
PIC 999.
PIC X OCCURS 0 TO 100
X Close
DEPENDING ON OUT-COMMENT-COUNT.
Back | Next
131
Visual COBOL
10 Repeating Data
CUSTOMER-RECORD.
03 CUSTOMER-NO
PIC 9(6).
03 CUSTOMER-BALANCE
PIC S9(8)V99.
03 CUSTOMER-INVOICE-CNT PIC 999.
03 CUSTOMER-INVOICE
OCCURS 1 TO 500
05 INVOICE-NO
PIC 9(6).
05 INVOICE-DATE
PIC 9(8).
05 INVOICE-AMT
PIC 9(6)V99.
DEPENDING ON CUSTOMER-INVOICE-CNT.
ADD 1 TO CUSTOMER-INVOICE-CNT
MOVE WS-INVOICE-NO TO INVOICE-NO(CUSTOMER-INVOICE-CNT)
MOVE WS-TODAYS-DATE TO INVOICE-DATE(CUSTOMER-INVOICE-CNT)
MOVE WS-INVOICE-AMT TO INVOICE-AMT(CUSTOMER-INVOICE-CNT)
Module Summary
At end of this module you are now able to:
Exercise 3
There a couple of other brief solutions that you may find useful. They are:
10_04_Table Indexing
Quick Quiz
1. Would a PIC 99 subscript be suitable for an OCCURS 100 table?
a. YES
b. NO
2. What is the minimum value a subscript should ever contain while you are using it?
a. 0
b. 1
c. 100
d. There is no minimum
Index
X Close
Back | Next
132
Visual COBOL
10 Repeating Data
Index
X Close
Back | Next
133
Visual COBOL
Printing
and Reports
Index
X Close
Back | Next
134
Visual COBOL
Introduction
Any business programming system will almost certainly require report generation. Users frequently create reports
from static data using interactive report-writing tools. Moving beyond this, COBOL provides very simple and flexible
methods when the required data can be captured only during the program run itself. So print programs, which
produce reports, rather than data files, are common.
Print programs present different challenges both in the design stage and the COBOL procedural coding.
This module examines the following main areas:
Module Objectives
By the end of this module you will be able to:
List the different types of edited fields used for printing or display.
List the COBOL considerations that are relevant when designing a print program.
Edited Fields
Edited fields offer a range of ways to change a value (usually a number) so that it is easier to read, and more
meaningful.
Originally intended for printed reports, edited fields are also useful for DISPLAYed fields
Edited fields fall into the following types:
Currency symbols.
Leading Zeros
Look at the following example:
01
01
WS-NO
WS-EDITED-NO
PIC 9(6)V99.
PIC Z(5)9.99.
Index
X Close
Back | Next
135
Visual COBOL
Value/Picture
9(6)V99
Z(5)9.99
1234.56
00123456
1234.56
123456.78
12345678
123456.78
00000000
0.00
.34
00000034
0.34
Value/Picture
9(6)V99
Z(6).99
ZZZ999.99
1234.56
00123456
1234.56
1234.56
123456.78
12345678
123456.78
123456.78
00000000
0.00
000.00
.34
00000034
0.34
000.34
12.34
00001234
12.34
012.34
The main thing to note here is that numeric edited picture string, as illustrated above are NOT numeric fields and
cannot be used in any calculations. Any calculation must be carried out on the numeric field and then the edited field
used in any display statements by first doing something like:
MOVE WS-NO TO WS-EDITED-NO
DISPLAY WS-EDITED-NO
The MOVE is done, as we would hope, by aligning the data on decimal point.
WS-EDITED-TOTAL
WS-EDITED-TOTAL
Index
PIC Z(6).ZZ.
X Close
Back | Next
136
Visual COBOL
Value/Picture
9(6)V99
Z(5)9.99
Z(6).ZZ
BLANK WHEN ZERO
1234.56
00123456
1234.56
1234.56
123456.78
12345678
123456.78
123456.78
00000000
.34
00000034
0.34
.34
.01
00000001
0.01
.01
WS-PROTECTED
PIC *(5)9.99.
Value/Picture
9(6)V99
*(5)9.99
1234.56
00123456
**1234.56
123456.78
12345678
123456.78
00000000
*****0.00
.34
00000034
*****0.34
WS-BENEFITS
WS-EDITED-BENEFITS
Index
PIC 9(8)v99.
PIC ZZ,ZZZ,ZZ9.99.
X Close
Back | Next
137
Visual COBOL
Value/Picture
9(8)V99
ZZ,ZZZ,ZZ9.99
1234.56
0000123456
1,234.56
123456.78
0012345678
123,456.78
12345678.90
1234567890
12,345,678.90
0000000000
0.00
.34
0000000034
0.34
Currency symbols
Currency symbols are very similar to Zs.
The symbol will move up to the first non-zero number, space filling to the left if appropriate.
So always add one extra symbol, or you will lose a digit if the number field is full.
01
01
WS-BENEFITS
WS-EDITED-BENEFITS
PIC 9(8)v99.
PIC $$$,$$$,$$9.99.
Value/Picture
9(8)V99
$$$,$$$,$$9.99
1234.56
0000123456
$1,234.56
123456.78
0012345678
$123,456.78
12345678.90
1234567890
$12,345,678.90
0000000000
$0.00
.34
0000000034
$0.34
The actual currency symbol that is displayed is determined by a definition in the Environment Division.
This currency symbol is defined in a paragraph we have not discussed before: SPECIAL-NAMES
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
SPECIAL-NAMES.
CURRENCY SIGN IS .
You can also swap the functions of decimal point and comma, as happens in some European countries.
For example:
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
SPECIAL-NAMES.
DECIMAL-POINT IS COMMA.
Index
X Close
Back | Next
138
Visual COBOL
WS-SIGNED-NUMBER
WS-ED-MINUS-1
WS-ED-PLUS-1
PIC S9(8).
PIC -(7)9.
PIC +(7)9.
Value/Picture
S9(8)
-(7)9
+7(9)
1234
00001234+
1234
+1234
-1234
00001234-
-1234
-1234
WS-CRED-1
WS-DEB-1
PIC Z(7)9.99CR.
PIC Z(7)9.99DB.
The CR field is often for use on bills, to show when a customer owes a negative amount (i.e. when they are in
credit). In both cases the CR or DB only appears when the field is negative.
Value/Picture
S9(8)
Z(7)9.99CR
1234
00001234+
1234
-1234
00001234-
1234CR
Z(7)9.99DB
1234
1234DB
Insertion characters
There are four insertion characters that you may wish to use
Example 1
01
01
WS-DATE
WS-EDITED-DATE
PIC 9(8).
PIC 9999/99/99.
If WS-DATE contains 20120707 and is moved to WS-EDITED-DATE then WS-EDITED-DATE will contain
2012/07/07.
Index
X Close
Back | Next
139
Visual COBOL
WS-CRED-CARD-NO
PIC X(16).
WS-EDITED-CRED-CARD-NO PIC X(4)BX(4)BX(4)BX(4).
If WS-CRED-CARD-NO contains 1234567890123456 and is moved to WS-EDITED-CRED-CARD-NO then WSEDITED-CRED-CARD-NO will contain 1234 4568 9012 3456.
Example 3
01
WS-SOL
PIC 999000.
mph
e.g.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT INFILE
ASSIGN INFILE.DAT
ORGANIZATION IS SEQUENTIAL.
SELECT OUTFILE ASSIGN OUTPRINT.TXT
ORGANIZATION IS LINE SEQUENTIAL.
COBOL includes another type of file, called the LINE SEQUENTIAL file, which is a PC text file. It can be read and
modified by any PC text editor, such as Notepad.
Consequently, the file is described as LINE SEQUENTIAL in the Environment Division.
Up until now we have been using RECORD SEQUENTIAL files, which is the default setting. Such files as these are
COBOL data files, and while you may be able to view them in a text editor, if you try to alter them, the layout will be
damaged and can no longer be read by a COBOL program.
Index
X Close
Back | Next
140
Visual COBOL
Consider the range of output lines that need to be written. A print program will likely include a heading, a detail line,
possibly a subtotal, and a grand total line.
The detail line consists of items from an input record and/or calculations, but the other lines show a mixture of
preset values and items examined at runtime.
The preset items would best be coded with VALUE clauses; however, these cannot be used in the File Section.
Therefore it is normally best to include several versions of the print line in working storage, and WRITE the print
record FROM the appropriate line.
WS-HEADING-LINE.
03
03 WS-EDITED-DATE
03
03 WS-PRINT-PAGE-CNT
Index
PIC
PIC
PIC
PIC
X Close
Back | Next
141
Visual COBOL
The heading line is a mixture of these fields and of variable data (the date, and the page counter).
WS-DETAIL-LINE.
03
03 WS-PRINT-NAME
03 WS-PRINT-SALES
A print page typically consists of a number of pages (which, theoretically, may be zero).
A print page might include a header page, followed by normal pages, which will probably display some sort
of heading.
Index
X Close
Back | Next
142
Visual COBOL
Possible
Heading
Heading
Possible
Region Start
[Nothing]
Possible
Region End
Detail Line
Start
[Nothing]
End
[Nothing]
This view may at first seem contrived; however, it avoids any conflict between input and output files. Pages as
such have disappeared; only an iteration of detail group exists.
This ensures that detail lines display and also other events headings or potential start-of or end-of regions occur
automatically. A sample program, later in this module, uses this approach.
Two special points exist at which we must make sure that particular code takes place: at the very start to ensure
that the first heading appears and at the end to make sure that the last region finishes.
We could achieve this in two ways. Firstly, the special code could be explicitly called in each case.
Index
X Close
Back | Next
143
Visual COBOL
http://www.pgrocer.net/Cis52/rptwritr.html
ftp://ftp.software.ibm.com/software/websphere/awdtools/cobolreportwriter/c2643013.pdf
Module Summary
At the end of this module you are now able to:
List the different types of edited fields used for printing or display.
List the COBOL considerations that are relevant when designing a print program.
Exercise
You should first load the solution 11_01_Printing.sln.
The program deals with an input file, consisting of records each with.
an eight-digit numeric field (six digits before the decimal point, two after) for that persons sales.
03
03
03
Index
IN-REGION
IN-NAME
IN-SALES
PIC X .
PIC X(20) .
PIC 9(6)V99 .
X Close
Back | Next
144
Visual COBOL
You should first of all run the program and look at the results. The results can be seen by looking at the output text
file outprintprt.txt. This file is shown in the solution explorer and can be opened directly from there, by doubleclicking.
You should now examine the COBOL code and debug that code to see how it operates.
Consider the following points about the program.
The program ACCEPTs the date in and moves to the heading line. When the program finds a new region, the
program SEARCHes for the region in the table WS-REGION-TABLE-REDEF. (If an unknown region is found, the
program terminates immediately.) The program moves the value found to the start of region line. The value
found is also stored, so that new region is not encountered on every record.
Normally, start of region immediately follows end of region; however, this is not true at the very start of the
program. This explains the pre-setting of WS-REGN to LOW-VALUES.
The program has to make sure that a page is thrown and headings are printed, at the end of every page, and
at the very start of the program. How is this achieved?
Is end of region always indicated by the start of a new region?
Index
X Close
Back | Next
145
Visual COBOL
Quick Quiz
1. What is the another way of writing PIC Z,ZZZ,ZZZ.ZZ?
a. PIC ZZZ,(3)
b. PIC Z,ZZZ,(3)VZZ
c. PIC Z,Z(3),Z(3).Z(2)
2. Difference between a floating plus and a floating minus? Which of the following is true?
a. No difference
b. A minus always shows in both cases if the field is negative
c. A plus always shows in both cases if the field is negative
d. A plus always shows only if the field is positive in the case of floating plus
3. Why is B so called?
a. B stands for Blank
b. B stands for Bold
c. B has no real meaning
4. Why must you always insert one more currency symbol than you need for the size of the field?
a. To allow for longer data values
b. To make space for the currency symbol if the field is full
c. No need to add an extra character in the field
d. Currency symbols require extra storage space than normal numeric characters
5. What organization would you expect for a print file?
a. SEQUENTIAL
b. TEXT
c. LINE SEQUENTIAL
d. INDEXED
6. How many blank lines do you get if you WRITE AFTER 4?
a. 1
b. 2
c. 3
d. 4
e. 5
7. How do you make the print program throw a page?
a. Use BEFORE PAGE THROW
b. Use AFTER PAGE
c. Use AFTER PAGE THROW
d. Use AFTER 25 LINES
Index
X Close
Back | Next
146
Visual COBOL
Using
Indexed Files
Index
X Close
Back | Next
147
Visual COBOL
Introduction
The data file handling capability within COBOL is extremely powerful.
Any business application programmers skill set should include a full understanding of how to take advantage of
these capabilities.
Up until now we have been using sequential files, where records are accessed, or written, one after another.
It is not easy to insert a new record, or delete a record, in the middle of such a file.
Sequential files are very common, but not suitable for applications needing to find a particular record, perhaps to
amend or delete it.
The only way to select a chosen record on a sequential file is to read through the whole file until the correct one is
found hardly an efficient or easy process.
Similarly, inserting a new record into a sequential file might prove difficult.
Indexed files, on the other hand, allow more flexible access.
Finding any record quickly by using its key becomes easier.
Module Objectives
By the end of this module you will be able to:
List the different methods of access and use the associated COBOL statements.
Data file
Index
Other variations on an indexed file are for the Data part and the index part to be stored in the same physical file.
The file handler looks in the index part to determine which record of the data file to access.
You, the COBOL programmer, dont need to know the details of how this is done you just go and get the record
Index
X Close
Back | Next
148
Visual COBOL
Random access go anywhere in the file, to insert, amend or delete a specific record.
Sequential access read through, or write to, part or all of the file. The records will be processed in key order.
Dynamic access carry out both random and sequential access in the same program. A program that
updates certain records on an employee file and then reads sequentially through all of them to produce
paychecks, would be an example of the dynamic access.
File definition
The select statement for an indexed file contains information as shown below.
SELECT EMPLOYEE-FILE ASSIGN EMPLOYEE.DAT
ORGANIZATION IS INDEXED
ACCESS IS RANDOM
RECORD KEY IS EMPLOYEE-NO
ALTERNATE RECORD KEY IS EMPLOYEE-SURNAME.
The ACCESS IS RANDOM can be replaced with:
ACCESS IS SEQUENTIAL or
ACCESS IS DYNAMIC
as defined above
Index
X Close
Back | Next
149
Visual COBOL
If ACCESS is SEQUENTIAL, then the whole clause can be omitted (since it is the default). However, it is better to
leave the clause there for clarity.
The RECORD KEY refers to the unique primary key on the record that can be used to access any particular record.
The ALTERNATE RECORD KEY refers to the alternate key on the record that can be used to access any particular
record.
The indexed file key (referred to as RECORD KEY) can be a compound of more than one field.
It is often stated that the key must be alphanumeric, meaning a PIC X elementary field or a group field.
This is not strictly true, but a MOVE to the key field (which is how the key is set) will always be treated as an
alphanumeric move.
So, it is recommended that the key is alphanumeric. If the key really does have to be a number, then a redefinition
can be used to cheat.
In this example the FD for the file could contain:
FD EMPLOYEE-FILE.
01 EMPLOYEE-REC.
03 EMPLOYEE-NO
03 EMPLOYEE-INITS
03 EMPLOYEE-SURNAME
03 EMPLOYEE-SALARY
03 EMPLOYEE-DEPT
PIC
PIC
PIC
PIC
PIC
X(5).
X(4).
X(16).
9(6)V99.
X(10).
If the key field is actually numeric, this could be dealt with as shown below:
FD EMPLOYEE-FILE.
01 EMPREC.
03 EMPLOYEE-NO.
05 EMPLOYEE-NO-NUMERIC
03 EMPLOYEE-INITS
03 EMPLOYEE-SURNAME
03 EMPLOYEE-SALARY
03 EMPLOYEE-DEPT
PIC
PIC
PIC
PIC
PIC
9(5).
X(4).
X(16).
9(6)V99.
X(10).
The key is now EMPLOYEE-NO a group field, so it automatically has an alphanumeric picture.
Index
X Close
Back | Next
150
Visual COBOL
Random Access
To open a file for Random access, you must first define the file as:
SELECT EMPLOYEE-FILE ASSIGN EMPLOYEE.DAT
ORGANIZATION IS INDEXED
ACCESS IS RANDOM
RECORD KEY IS EMPLOYEE-NO
ALTERNATE RECORD KEY IS EMPLOYEE-SURNAME.
Or ACCESS IS DYNAMIC
The file OPEN statement is then:
OPEN I-O EMPLOYEE-FILE
There are three possible actions you may want to carry out:
Index
X Close
Back | Next
151
Visual COBOL
Index
CLOSE EMPLOYEE-FILE
X Close
Back | Next
152
Visual COBOL
Exercise 1
For this exercise you should open the solution 12_01_Indexed_Files.sln.
Most random-access programs need similar functionality. An indexed file needs changing, in that one or more
records will be inserted, changed or deleted. One method for these amendments is to use a sequential input file
containing details of the changes to be made. The following example uses a sequential input file.
An amendment file
Amendment
type
A
C
D
Key
Fields value
19328465
17684536
16052901
JK
ROWLING
07500000
06550000
Record
key
Add
Indexed
file
Record
key
Change
Delete
Present
Not
Present
Each value in the amendment file will indicate an Add, Change or Delete. The key value may or may not exist on the
indexed file. This yields six possibilities.
The key value does exist, and this is an Add. This is an Invalid Add.
Index
X Close
Back | Next
153
Visual COBOL
The key value does exist, and this is a Change. This is a Valid Change and can be carried out.
The key value does exist, and this is a Delete. This is a Valid Delete and can be carried out.
The key vale does not exist, and this is an Add. This is a Valid Add and can be carried out.
The key value does not exist, and this is a Change. This is an Invalid Change.
The key value does not exist, and this is a Delete. This is an Invalid Delete.
The following program shows one way of tackling these choices. In Record Start the program seeks the key value
on the indexed file, regardless of the amendment type. If the record does not exist, then the program sets a flag.
(The flag must be cleared at a suitable point.) By Record Body the program knows whether or not the record
exists and can act accordingly.
Index
X Close
Back | Next
154
Visual COBOL
Init
Bod
End
1,6,4
2, 3
Process
Rec
Rec
Sta
Rec
Bod
Rec
Fin
5, 7
Key
Found
Invalid
Insert
Valid
Change
12
Valid
Delete
13
Key
Not Found
Invalid
Insert
11
Valid
Change
Valid
Delete
10
Actions
1. Open Files
2. Close Files
3. Stop Run
4. Read amendment file
5. Clear found it flag
6. Clear any other flags
7. Try and find indexed record
8. Display Invalid Insert
9. Display Invalid Change
10. Display Invalid Delete
11. Insert record
12. Rewrite amended record
13. Delete record
You should study this program in debug mode to see how the program is behaving.
Index
X Close
Back | Next
155
Visual COBOL
Index
X Close
Back | Next
156
Visual COBOL
Index
X Close
Back | Next
157
Visual COBOL
Index
X Close
Back | Next
158
Visual COBOL
WS-STATUSES.
03 WS-CHG-STATUS
03 WS-EMP-STATUS
PIC XX.
PIC XX.
Once you have defined file status for a file, then this must be used instead of AT END and INVALID key etc.
If the file operation is successful then the file status value will contain 00.
If there is an error, then certain other values will apply. e.g.
22 indicates Duplicate key condition (trying to store a duplicate record when duplicates are not allowed).
WS-EMP-STATUS
PIC XX.
WS-EMP-STATUS-EXTRA REDEFINES WS-EMP-STATUS.
05 WS-EMP-STATUS-1 PIC X.
05 WS-EMP-STATUS-2 PIC 99 COMP.
The values in this second byte will vary with whatever complier you are using. If you are using the Micro Focus
compiler, then you would need to look in the help system to determine what these values are. For example a value
of 9/65 indicates the file is locked. (Usually because some other user has opened the file for i-o).
Beware, that if you use file-status then you will need to recode the end-of-file; as shown below:
READ EMPLOYEE-FILE KEY IS EMPLOYEE-SURNAME
INVALID KEY
DISPLAY NO SURNAME
END-READ
Will become
READ EMPLOYEE-FILE KEY IS EMPLOYEE-SURNAME
IF WS-EMP-STATUS NOT = 00
Index
X Close
Back | Next
159
Visual COBOL
END-IF
DISPLAY NO SURNAME
Use of Declaratives
Declaratives are sections of code, which if used, must appear first in the Procedure Division by inserting the word
DECLARATIVES. (Note SECTIONS, not PARAGRAPHS).
A Declaratives section will be PERFORMed automatically if a file status error occurs. Errors that you have specifically
coded for, such as AT END, do not trigger Declaratives. This allows you to handle any other errors in file i-o which
you have not specifically coded.
If using Declaratives, make sure that the rest of the Procedure Division code is also in a section and not the same
one as the Declarative.
Sections consist of one or more paragraphs; by convention the last paragraph may be an exit paragraph, marking
the end of the section. (The real end of the section is marked by the fact that another section has been found or by
the physical end of the code).
Example of Declarative:
PROCEDURE DIVISION.
DECLARATIVES.
CHANGES-ERROR SECTION.
USE AFTER STANDARD ERROR PROCEDURE ON INFILE.
CHANGES-ERROR-ACTIONS.
DISPLAY SERIOUS ERROR ON INPUT FILE
STATUS IS WS-IN-STATUS
CLOSE CHANGES-FILE
STOP RUN.
*>[other Declaratives sections]
MAIN SECTION.
PARA.
PERFORM INIT-PARA. *> ETC
Module Summary
At the end of this module you are now able to:
List the different methods of access and use the associated COBOL statements.
Index
X Close
Back | Next
160
Visual COBOL
Further Exercises
There a number of solutions that you can look at to help re-enforce your knowledge of the use of indexed files and
sequential files.
Exercise 2
Open the solution 12_03_Indexed File update
This solutions read a sequential file and applies appropriate update to and indexed file.
Study this program and debug it to view the processing.
Exercise 3
Open the solution 12_04_Meaningful call with indexed file
The solution here shows one program calling another program. This is discussed in some detail in the next
module. In this program you can also see a Microfocus extension to the display and accept verbs, which allow you
to position fields at certain positions on the screen. For now, just debug through the code to see the file handling in
action. (Suitable code to use are 102 125).
Exercise 4
Open the solution inside 12_05_Logic errors
This solution is not handling an indexed file but a sequential file with 2 record types. The program here is reading the
input file test44.dat and producing a report test44.txt. However it contains 4 bugs.
You should use the knowledge you have gained so far to fix these 4 bugs.
The input file contains the following records:
You will see there are 2 kinds of record indicated by the red and blue marks. Type 1 is a STUDENT record and
Type 2 is a COURSE record.
Index
X Close
Back | Next
161
Visual COBOL
The last student on file, HAROLD HARDWORK is missing from the list.
Most of these bugs are due to poor initial program design. Apart from a redesign fix the bugs as best you can. This
is a problem you will face very often, where you will not have the time or budget to rewrite a program.
Please spend some time fixing this, but if you struggle and want to see a solution, then one can be found by
opening the solution data10.sln from the folder 12_02_data10.
Index
X Close
Back | Next
162
Visual COBOL
Quick Quiz
1. What is the verb to change a record on an indexed file?
a. READ
b. WRITE
c. REWRITE
d. AMEND
e. WRITE OVER
f. DELETE
2. What statement allows you to insert a new record?
a. READ
b. REWRITE
c. WRITE
d. AMEND
e. WRITE OVER
f. DELETE
3. Under what circumstances can a DELETE on an indexed record fail?
a. If the file is not opened for i-o
b. If the record already exists
c. If the record does not exist
d. If the record is greater than 500 bytes
4. Which READ statement(s) below are invalid?
a. READ EMPLOYEE-FILE.
b. READ EMPLOYEE-FILE KEY IS EMPLOYEE-SURNAME AT END...
c. READ EMPLOYEE-FILE NEXT RECORD AT END...
d. READ EMPLOYEE-FILE INVALID KEY...
5. If you READ NEXT on an alternate key, there is no way to detect, in the READ, that the alternate key has
changed?
a. TRUE
b. FALSE
6. The syntax to READ the record before the current one in an indexed file is:
a. READ FILE-NAME LAST
b. READ FILE-NAME PREVIOUS
c. READ RECORD-NAME LAST
d. READ RECORD-NAME PREVIOUS
Index
X Close
Back | Next
163
Visual COBOL
Modular
Programming
Index
X Close
Back | Next
164
Visual COBOL
13 Modular Programming
Introduction
Modular programming is the name given to the procedure of tackling a programming problem by writing not one,
but two or more programs, dividing the coding tasks between the separate programs.
Different programs can communicate with each other, passing data as parameters.
Modular programming is very common, for the following reasons:
The programming task may be large. If so, dividing it up into discrete tasks (subroutines or modules) means
that different people can be working simultaneously.
You may want to separate the business logic of a program from the nuts and bolts of how the data is retrieved
or written.
Several programs may need common code, for example tax calculation. That code can be written once, and
called from any program that needs it.
For example, processing the payroll of a companys staff involves calculating different rates of tax and benefits.
The program can be divided up logically if each discrete task is allocated to a separate program, often called a
subroutine, subprogram or module. Different people can write each program separately, if necessary. If a task
requires change, then only that module requires editing and recompiling.
It might be advisable to keep certain actions away from the main program.
Lets imagine that you designed a program that accesses and updates employee records on an indexed file.
However, you later decide to access a database. If all the file access code is contained in a subprogram, then
that could be replaced in the future with code to access a database the code in the main program would not
require changes.
Instead, the subprogram can be told what to do for example, read a record or update a record by
passing down a value, or parameter.
The data fields in a record can be passed back similarly. We can also pass back file status values, so that the
top-level program, as it is called, will know what happened in the module.
Several programs might require the same functionality. For example, it would be useful if some common code
carried out end-of-year tax calculations. Rather than writing the same code many times, create a module that is
called from many different programs.
The code becomes common code. Again, the appropriate data values can be passed back and forth as
parameters.
In this module we shall discuss how to design and implement modular programming. In practice, modular
programming makes program design easier, which is always good!
You saw in one of the examples in the previous module where there was a screen i-o program which called a file
i-o program. This is a very common split of processing.
Index
X Close
Back | Next
165
Visual COBOL
13 Modular Programming
Module Objectives
By the end of this module you will be able to:
In this example the TOPPROG calls the SUBPROG. (SUBPROG must of course exist).
The SUBPROG carries out it processing and then returns to the calling program TOPPROG using the EXIT
PROGRAM syntax (not STOP RUN).
When you call a sub-program, the name you use in the CALL statement is determined differently in different
environments. For example on a Mainframe the name of the program you call is the PROGRAM-ID of the program.
In Micro Focus COBOL, the name of the program you call is the name of the program file on disk. For that reason, it
is strongly recommended that you save the program to disk with the same name as the PROGRAM-ID to avoid
confusion.
Index
X Close
Back | Next
166
Visual COBOL
13 Modular Programming
Call Nesting
PROG1 can CALL PROG2, which can CALL PROG3, and so on.
The level of call nesting will depend on the amount of stack space available.
Of course, this second level call is free to use any data items it wishes in the call, including its own linkage section
items.
Recursion (e.g. PROG1 calling PROG1) is allowed, but is only useful in particular circumstances. It is very rarely in
regular COBOL programs but is used very commonly in Object Oriented Cobol as we will see later.
Passing parameters
A call can pass parameters to a called program. The called program can alter these values, which then get passed
back on the EXIT PROGRAM.
PROG1
Data is passed up
PROG2
For this to work, the called program must have a LINKAGE SECTION. This LINKAGE SECTION is used as a
holding place for the data that is passed from the calling program. The names of the data items in the called
program and the calling program need not be the same. But they must be the same formats. We often prefix the
linkage section versions with something like LS-, just to help us remember that it is linkage data we are referencing
in our program.
Index
X Close
Back | Next
167
Visual COBOL
13 Modular Programming
Exercise 1
Load the solution 13_01_Modular_Programming.sln.
This solution consists of 2 programs:
Program12 this handles access to a sequential file and then calls Program12a.
Program12a this handles an indexed file and updates this file according to the data that is passed to it by
Program12.
01
01
WS-EMPLOYEE-REC.
03 EMPLOYEE-NO
03 EMPLOYEE-INITS
03 EMPLOYEE-SURNAME
03 EMPLOYEE-SALARY
03 EMPLOYEE-ADDRESS
03 EMPLOYEE-DEPT
ws-action
ws-status
PIC
PIC
PIC
PIC
PIC
PIC
pic
pic
X(8).
X(4).
X(16).
9(6)V99.
X(40).
X(10).
X.
xx.
call program12a
using ws-employee-rec
ws-action
ws-status
The syntax in Program12a which is relevant is:
linkage section .
01 ls-EMPLOYEE-REC .
03 ls-EMPLOYEE-NO
PIC X(8) .
03 ls-EMPLOYEE-INITS
PIC X(4) .
03 ls-EMPLOYEE-SURNAME PIC X(16) .
03 ls-EMPLOYEE-SALARY PIC 9(6)V99 .
03 ls-EMPLOYEE-ADDRESS PIC X(40) .
03 ls-EMPLOYEE-DEPT
PIC X(10) .
01 ls-action
pic x .
Index
X Close
Back | Next
168
Visual COBOL
13 Modular Programming
ls-status
pic xx .
Exercise 2
This example is similar to the one you looked at in the previous module.
Load the solution FileInquiry.sln from 13_02_FileInquiry
Study the code in here and debug the programs.
Suitable patron numbers to use are 101 thru 125.
Exercise 3
This simple example can be found at 13_02_Circle.sln
It consists of 2 programs:
Circle-IO which handles the use interface which requests the radius if a circle and then calls the subprogram.
Circle-calculations which very simply calculates the area and circumference of a circle.
Study the behaviour of these 2 programs by first executing and then by debugging.
You will notice that the call to the subprogram is:
Call circle-calculations using
radius
circumference
circle-area
Index
X Close
Back | Next
169
Visual COBOL
13 Modular Programming
Module Summary
Now, at the end of this module you are able to:
Quick Quiz
1. The CALL to a subprogram must pass parameters to the subprogram.
a. TRUE
b. FALSE
2. If parameters are passed, the called subprogram needs a LINKAGE section to receive the parameters.
a. TRUE
b. FALSE
3. A calling program needs a LINKAGE section to send the parameters.
a. TRUE
b. FALSE
4. The CALL to a subprogram must called using a literal.
a. TRUE
b. FALSE
5. The normal use of a return code value would expect a successful return code value to be:
a. 0
b. 1
c. 9
6. If a called program is itself also a calling program, then it must use the same parameters that it was called with?
a. TRUE
b. FALSE
Index
X Close
Back | Next
170
Visual COBOL
Screen Handling
Index
X Close
Back | Next
171
Visual COBOL
14 Screen Handling
Introduction
Standard COBOL offers little in the use of displaying and accepting from the screen.
For that reason, most COBOL compiler writers have provided additions to the COBOL syntax which allows a better
ability to handle a character screen.
We will look briefly at some of the features which Microfocus has provided.
Module Objectives
By the end of this module you will be familiar with:
Future directions.
Index
X Close
Back | Next
172
Visual COBOL
14 Screen Handling
or
DISPLAY DATA-NAME AT LINE 11 COLUMN 8
or
DISPLAY DATA-NAME AT LINE WS-LINE-NO COLUMN WS-COL-NO
Accept:
or
ACCEPT DATA-NAME AT LINE 11 COLUMN 8
or
ACCEPT DATA-NAME AT LINE WS-LINE-NO COLUMN WS-COL-NO
There are a number of other variations, handling color, password protection, etc, which we will not describe here.
(You can find extensive details in the Microfocus help system).
In addition many COBOL suppliers have provided very advanced screen handling. Microfocus has provided a new
data division entry name SCREEN Section along with the advanced Dialog System.
This also shows how you can get function key information from COBOL.
Index
X Close
Back | Next
173
Visual COBOL
14 Screen Handling
See how the tab and back tab keys are working.
Then debug your way through the code. You will see that how this example uses screen section syntax and
uses of Function keys. This is NOT standard COBOL; it is Microfocus extensions to COBOL.
Module Summary
Now at the end of this module you will be familiar with:
Future directions.
Quick Quiz
1. Standard COBOL provides the ability to display and accept from the screen?
a. TRUE
b. FALSE
2. Displaying and accepting from the screen at predefined places on the screen are an extension to COBOL.
a. TRUE
b. FALSE
3. COBOL providers have come up with their own display and accept syntax.
a. TRUE
b. FALSE
Index
X Close
Back | Next
174
Visual COBOL
Database Use
Index
X Close
Back | Next
175
Visual COBOL
15 Database Use
Introduction
Up to now we have been accessing data through sequential files and indexed files.
COBOL, of course, fully supports access to relational databases such as:
SQL Server.
DB2.
Oracle.
The syntax used in COBOL to access a relational data base is name Embedded Structured Query Language
(or ESQL).
It is not intended to be an exhaustive coverage of all the ESQL syntax, but just an illustration of the syntax involved.
Module Objectives
At the end of this module you will have an outline understanding of the way in which COBOL can handle access to
a relational database.
Database connection
The mechanism you use to connect to a database, through ODBC, is almost the same for all databases. All that is
required is for the database provider to supply an ODBC module and for your module to be registered.
Sample database
For the purpose of this training class we will show the access to a simple Microsoft Access data base, named
library. The principles used here are exactly the same for all relational databases.
This sample database contains 2 tables Book and Patron.
The Book table contains the following fields:
Index
X Close
Back | Next
176
Visual COBOL
15 Database Use
Index
X Close
Back | Next
177
Visual COBOL
15 Database Use
You do not need to have Microsoft Access installed on your PC in order to access this data with COBOL.
Registering the database with ODBC
The mechanism we will be using to access this database is through ODBC, so we need to register this database
correctly. Take the following steps:
1. From the Windows Start menu select All Programs, Micro Focus Visual COBOL, Data Tools, Data
Connections, ODBC Data Source Administration (32bit).
Index
X Close
Back | Next
178
Visual COBOL
15 Database Use
Index
X Close
Back | Next
179
Visual COBOL
15 Database Use
5. Enter the Data Source name to be Library and select the Database
C:\COBOLClass\DataFiles\Library.mdb.
Index
X Close
Back | Next
180
Visual COBOL
15 Database Use
Index
X Close
Back | Next
181
Visual COBOL
15 Database Use
Index
X Close
Back | Next
182
Visual COBOL
15 Database Use
Index
X Close
Back | Next
183
Visual COBOL
15 Database Use
Index
X Close
Back | Next
184
Visual COBOL
15 Database Use
Step through the code with F11, as you have done before to see the code being executed.
Microfocus Wizard
Microfocus provides a Wizard which enables you to generate EXEC SQL syntax for your COBOL database
access. This is not described here, but you may wish to explore this in your own time.
The wizard supports the generation of both EXEC SQL code and EXEC ADO code. The default installation is
for EXEC ADO code.
ADO.NET provides consistent access to data sources such as SQL Server and XML, and to data sources
exposed through OLE DB and ODBC. Data-sharing consumer applications can use ADO.NET to connect to
these data sources and retrieve, handle, and update the data that they contain.
For the purpose of this course we will not be considering ADO .NET. So, to change this to EXEC SQL, you
would need to do the following:
1. From the Visual Studio menu select Tools, Options
2. From here, select Micro Focus COBOL, OpenESQL Assistant
3. Under General, change the Mode from ADO.NET to ODBC (at the time of writing, if you are using Visual
Studio 2012, this ADO.NET setting is not yet available)
Index
X Close
Back | Next
185
Visual COBOL
15 Database Use
5. You will then need to close Visual Studio and restart it for the settings to become active.
6. You can then use the Wizard by choosing Tools, Micro Focus, Open ESQL Assistant.
The use of this Wizard is not described here. The appendix at the end of the modules describes this.
Module Summary
Now you are at the end of this module you will have an outline understanding of the way in which COBOL can
handle access to a relational database.
Index
X Close
Back | Next
186
Visual COBOL
15 Database Use
Exercise
If you have not already done so, load the solution SQLProject.sln from
\COBOLClass\Projects\15_01_SQLProject
Examine the code inside this program and debug the code to get a feel for the way the syntax is working.
Quick Quiz
1. Relational database access is the same as indexed file access.
a. TRUE
b. FALSE
2. In order to use relational database access you need to have a copy file for each of the database tables you are
using.
a. TRUE
b. FALSE
3. Copy files relating to the tables include both COBOL data items and database items.
c. TRUE
d. FALSE
4. You cannot mix database access and regular COBOL file access in the same program.
e. TRUE
f. FALSE
Index
X Close
Back | Next
187
Visual COBOL
Object
orientated
COBOL
Index
X Close
Back | Next
188
Visual COBOL
Introduction
This chapter introduces you to Object Oriented syntax in Visual COBOL through a series of evolving solutions.
The purpose of this chapter is to give you a high level overview of using Visual COBOL to code and debug Object
COBOL programs. It is not the intention of this chapter to provide you with an exhaustive list of all the features and
syntax of Object COBOL. Rather it introduces you to the main concepts and practices. Later, as you explore
some of the extensive examples of Visual COBOL which are provided with the Micro Focus product, you should
be aware of all the concepts behind the details.
Module Objectives
At the end of this module you will be familiar with:
Most of the restrictions that traditional COBOL programs have is not the case when considering a Class, as you
will see.
Index
X Close
Back | Next
189
Visual COBOL
Class Structure
Index
X Close
Back | Next
190
Visual COBOL
Evolving demonstrations
There now follows a series of evolving demonstrations/exercises where Object COBOL syntax is used.
This is not shown as an example of what you need to do in practice, but rather demonstrates the structure and
syntax of Object COBOL programs in a series of progressions.
You will see in your sample projects there are a number of OO solutions:
You will load each of these solutions in turn as you progress through this chapter.
What you need to do is to look at the code in each of these cases and then execute the code in debug mode to see
how the various lines of code are set up and executed.
The sections shown below give you points to look out for. Take your time doing this in order to understand
what is happening.
Exercise 1
The first thing to do is to look at a solution we already saw earlier in the course. This is NOT an example of Object
Orientation but simply shows a procedural example that we will evolve into Object Oriented.
So, load the solution 16_01_OO_COBOL.sln
This solution contains 2 programs:
It consists of 2 programs:
Circle-IO which handles the use interface which requests the radius if a circle and then calls the subprogram.
Circle-calculations which very simply calculates the area and circumference of a circle.
The circle-IO program is very simple COBOL code which just displays some textual information and then asks you
to enter a value for the radius of a circle. It then calls the circle-calculations program, which calculates the area and
circumference of the circle and passes these values back to the circle-IO program. The circle-IO program then
displays these results on the screen and asks for the next radius. (Entering a 0 radius terminates the program).
Study the behaviour of these 2 programs by first executing and then by debugging.
Index
X Close
Back | Next
191
Visual COBOL
pic 99.
pic 999v9.
pic 99999v9.
Exercise 2
This next solution changes the Circle-calculations program into an Object Oriented Class.
So, load the solution 16_02_OO_COBOL.sln
First of all execute this project to see that it is behaving in the same way that the previous project behaved.
Now lets look at the code in circle-IO.
Inside the circle-IO program you will see the following in procedure division:
Invoke type CircleCalculations::CalculateArea(radius) returning circle-area
set circumference to type CircleCalculations::CalculateCircumference(radius)
The Invoke invokes a class method inside the circle-IO class. We know it is a class method that we are trying to
invoke the word type in the INVOKE indicates that the method is a class method. We, of course, can only know it
is a class method by looking in the class program itself.
Index
X Close
Back | Next
192
Visual COBOL
Pass the value radius to that method and receive the value circle-area back from that method.
The second statement set circumference . . . is exactly the same, but using a different syntax. If a method returns
just a single value, then you would probably choose to use this set syntax.
So the following 2 statements are identical in behaviour:
Invoke type CircleCalculations::CalculateArea(radius) returning circle-area
Set circle-area to type CircleCalculations::CalculateArea(radius)
If a method returns more than 1 value then you would need to use the Invoke Syntax.
Now lets look at the code in circle-calculations.
Class-ID. CircleCalculations.
*>---------------------------------------------Method-ID. CalculateArea static.
Linkage Section.
01 ls-radius
pic 99.
01 ls-area
pic 99999v9.
Procedure Division Using by value ls-radius
Returning ls-area.
Compute ls-area = 3.14 * ls-radius * ls-radius
Exit Method
.
End Method CalculateArea.
*>---------------------------------------------------------Method-ID. CalculateCircumference static.
Linkage Section.
01 ls-radius
pic 99.
01 ls-circumference pic 99999v9.
Procedure Division Using by value ls-radius
Returning ls-circumference.
Compute ls-circumference = 2 * 3.14 * ls-radius
Exit Method
.
End Method CalculateCircumference.
*>---------------------------------------------------------END CLASS CircleCalculations.
Index
X Close
Back | Next
193
Visual COBOL
Exercise 3
This next solution uses the Circle-calculations Class, but in this case, the methods have become Object Instance
methods.
So, load the solution 16_03_OO_COBOL.sln
First of all execute this project to see that it is behaving in the same way that the previous project behaved.
Now lets look at the code in circle-IO.
Inside the circle-IO program you will see the following in data division.
01
circleObject
type
CircleCalculations.
This is declaring a data item circleObject. It does not have a picture clause. It is declared to be an object
instance reference to an object type CircleCalculations.
In procedure division, this object instance must be created. The object needs to be created by the class, using
the new method. The syntax to create this object is:
set circleObject to type CircleCalculations::New()
From this point on, it is not the class methods which are invoked, but the object instance methods:
Invoke circleObject::SetRadius(radius)
Invoke circleObject::Calculate()
We know these are object instance methods in 2 ways:
We are not using the word type in the invoke. If we did we would get a compiler error).
We are referring to the object Instance circleObject, not the class CircleCalculations.
Index
X Close
Back | Next
194
Visual COBOL
Index
X Close
Back | Next
195
Visual COBOL
The radius is then passed to the object instance using the SetRadius method.
Index
X Close
Back | Next
196
Visual COBOL
Exercise 4
We have gone from a fairly simple procedural program to what appears to be a more complex Object Oriented
solution. We have done this to gain an understanding of the way in which OO works.
Lets now make life simpler.
Load the solution 16_04_OO_COBOL.sln
First of all execute this project to see that it is behaving in the same way that the previous projects behaved.
Lets first look at the CircleCalculations program
Identification Division.
Class-id. CircleCalculations.
Working-Storage Section.
01 Radius
pic 99
property.
01 CircleArea
pic 99999v9 property.
01 Circumference
pic 999v9
property.
Method-ID. Calculate.
Procedure Division.
Compute CircleArea = 3.14 * radius * radius
Compute Circumference = 6.28 * radius
.
End Method Calculate.
End Class CircleCalculations.
This looks like a very simple program. It has just one object instance method Calculate.
It also has 3 data items which are object instance data items. However there is the word property alongside each
data item.
What this means is that if an object instance data item has the word property alongside it, then there are hidden
default get and set methods for that data item. They have the singular function of receiving or returning object
instance data values.
Lets look inside the circle-IO program to see how this is used
To set the radius instance data value we use:
Move ip-radius to circleObject::Radius
To do the calculation we use:
Invoke circleObject::Calculate
To get the instance values back we use:
Move circleObject::Circumference to circumference
Move circleObject::CircleArea to circle-area
Index
X Close
Back | Next
197
Visual COBOL
pic 99
property.
pic 99999v9 property.
pic 999v9
property.
pic 99
property no get.
pic 99999v9 property no set.
pic 999v9
property no set.
The no get clause means that that data item does not have an implicit get method.
The no set clause means that that data item does not have an implicit set method.
So in the example above:
Exercise 5
Load the solution 16_05_OO_COBOL.sln
First of all execute the application. It will ask for a radius and not give any result. It will ask for another radius. Enter a
few radius values and finally enter 0.
Multiple Object Instances have been created.
This will then show you the values in each of the multiple objects that it created!
Finally debug this code and see how it is working.
Module Summary
Now at the end of this module you should be familiar with:
You should now have a high level overview of using Visual Studio to code and debug Object COBOL programs.
It was not the intention of this chapter to provide you with an exhaustive list of all the features and syntax of
Object COBOL. Rather it introduced you to the main concepts and practices.
Index
X Close
Back | Next
198
Visual COBOL
Quick Quiz
1. In a class program do you distinguish class instance data from object instance data?
a. You add the word type after the data definition.
b. You add the word static after the data definition.
c. It is not possible to distinguish class data from object data.
2. In a class program do you distinguish a class method from object instance method?
a. You add the word type as part of the method definition.
b. You add the word static as part of the method definition.
c. It is not possible to distinguish class methods from object methods.
3. When invoking a method how do you ensure that it is a class method you are invoking?
a. You add the word type as part of the method invocation.
b. You add the word static as part of the method invocation.
c. It is not possible to distinguish class methods invocation from object methods invocation.
4. When invoking a method how do you ensure that it is an object instance method you are invoking?
a. You add the word type as part of the method invocation.
b. You add the word static as part of the method invocation.
c. You do not add anything to the invocation.
d. It is not possible to distinguish class methods invocation from object methods invocation.
5. How do you indicate that you want method Calculate in the object MyObject?
a. MyObject.Calculate
b. MyObject:Calculate
c. MyObject::Calculate
d. Calculate in MyObject
6. How do you create a new instance object MyObject from the class MyClass?
a. Invoke MyClass::New() giving MyObject
b. Invoke type MyObject::New() giving MyClass
c. set MyObject to MyClass::New()
d. set MyObject to type MyClass::New()
Index
X Close
Back | Next
199
Visual COBOL
.NET Introduction
Index
X Close
Back | Next
200
Visual COBOL
Introduction
This chapter introduces the Microsoft .NET Framework. It is not attempting to explain the full functionality of the
.NET Framework but just to introduce you to the underlying principles.
Micro Focus Visual COBOL provides a highly productive functionally rich development and analysis environment for
the creation, reuse, extension, analysis and maintenance of COBOL and legacy applications deployed on Windows.
Through Visual COBOL, applications have access to the functionality of the .NET Framework while existing assets
can be reused and extended.
Module Objectives
In this module we will look at:
The Microsoft Intermediate Language (MSIL) and Common Language Runtime (CLR).
C#
VB.NET
.....
Visual
Studio
.NET Framework
Framework
Classes
ADO.NET
Winforms
CLR
MF Server
Webforms
Win 32
COBOL Development
COBOL Deployment
.NET Overview
The Microsoft corporate web site defines Microsoft .NET as follows:
Microsoft .NET is a set of Microsoft software technologies for connecting information, people, systems and
devices.
Microsoft uses .NET as a broad term to cover a number of technologies that encompass operating systems,
server products and software development tools.
The .NET Framework is an environment for developing and executing software applications on platforms
running Microsoft operating systems, from hand-held computers to large multi-processor servers.
.NET enables a high level of software integration through the use of XML Web Services - small, discrete,
building-block applications that connect to each other as well as to other, larger applications over the Internet.
The term .NET is typically usually used by software developers to refer to the Microsoft .NET Framework
Index
X Close
Back | Next
201
Visual COBOL
The same techniques and technologies are used for creating graphical, standalone applications as for
distributed, web-based applications.
Index
X Close
Back | Next
202
Visual COBOL
Each language vendor produces a compiler that converts their source code into a Microsoft specified
intermediate code that is independent of any given computer.
This intermediate code is source-language independent in that you cannot tell from which language it was
generated. MSIL is portable across all platforms that support the .NET Framework. This includes all 64-bit
Windows operating systems and the Windows CE platform used by many hand-held computers.
The Microsoft Common Language Runtime loads and executes code that has been compiled by any of the
.NET compilers whether furnished by Microsoft or another vendor, such as Micro Focus Visual COBOL.
Known as Just in Time (JIT) compiling, as each program element is called, the CLR compiles to machine code
suitable for the machine the assembly is running on. It then caches this code to be used the next time the
element is called before giving execution over to that code.
User interface support, including traditional Windows user interfaces, web-based user interfaces and console
interfaces.
Sending and receiving data using different network protocols.
Module Summary
In this module we looked at:
The Microsoft Intermediate Language (MSIL) and Common Language Runtime (CLR).
Index
X Close
Back | Next
203
Visual COBOL
Quick Quiz
1. What is name of the .NET run time system?
a. CLR
b. RTS
c. MSIL
d. .NET RTS
e. JVM
2. What is the name of the .NET intermediate language?
a. .NET IL
b. MSIL
c. RTS
d. CLR
e. JCM
3. .NET was developed by?
a. Microfocus
b. Microsoft
c. Apple
d. Java
Index
X Close
Back | Next
204
Visual COBOL
Window Forms
Index
X Close
Back | Next
205
Visual COBOL
18 Window Forms
Introduction
This chapter provides an introduction to the Visual Studio Form Designer and generating COBOL Windows Forms
(WinForms). We will also get an overview of the Visual COBOL syntax used in the access to Windows Forms.
We will do this through a series of exercises.
Module Objectives
In this module we will cover the following topics.
Index
X Close
Back | Next
206
Visual COBOL
18 Window Forms
Load project
1. First load this solution and run the project.
This is a GUI version using the same file we saw in the FileInquiry solution earlier in the course.
2. Try a few Patron Numbers (101- 123 should be ok). Also try a number which is not there such as 099.
3. Exit the execution and let us look at the various components in the project.
Project Properties
1. First right click on the project name PatronAccess and select properties.
Index
X Close
Back | Next
207
Visual COBOL
18 Window Forms
Main Program
2. Close the properties window and look at the Main.cbl program.
Form Program
3. Close this program and look at the program Form1.cbl. You will need to right-click on this program and select
View Code. Double clicking will take you into the Windows Form screen painter. This looks like quite a complex
programs, but dont worry, most of it is generated
Index
X Close
Back | Next
208
Visual COBOL
18 Window Forms
Designer view
4. Close this program and then right click on the same program name Form1 and select View Designer. This
takes you into the Windows Form screen painter.
5. Single click on each of the objects in this window and see how the properties change.
Index
X Close
Back | Next
209
Visual COBOL
18 Window Forms
At this point you can move objects around on the screen. But dont do this just yet; we will do it later.
Form1.designer.cbl view
6. Close the Form1.cbl Design view and double click on the program Form1.Designer.cbl. This looks even
more complex than Form1.cbl! Dont worry again, most of it is generated.
You can see above how various objects have been defined using .NET class types.
Index
X Close
Back | Next
210
Visual COBOL
18 Window Forms
Legacy Program
7. Close that program and look at the program LibraryMaint.cbl.
This is a regular procedural piece of Legacy COBOL code.
8. This program provides access to the indexed data file patron.dat. It can be called to read, insert, update or
delete records from the file.
Index
X Close
Back | Next
211
Visual COBOL
18 Window Forms
Toolbox view
9. The final thing we have not seen is the Toolbox view. Select View, Toolbox from the main menu to get:
This seems fairly meaningless at present. It takes on meaning when you are looking at the design view on the
Windows Form.
10. So right click on Form1.cbl name and select View Designer.
The Toolbox may have been minimised to the left hand list.
Index
X Close
Back | Next
212
Visual COBOL
18 Window Forms
This is the Toolbox that is used to paint objects onto our window.
Index
X Close
Back | Next
213
Visual COBOL
18 Window Forms
5. For the Name entry, type a name of your choice, e.g. MyFormProj.
6. Enter whatever folder you are using for these tests into the Location box, e.g. C:\COBOLClass\projects
7. Make certain the Create directory for solution checkbox is checked.
9. Click OK.
Index
X Close
Back | Next
214
Visual COBOL
18 Window Forms
3. In there you will see the Text entry is set to Form1. Change that to some text of your own, such as
My First Attempt.
Index
X Close
Back | Next
215
Visual COBOL
18 Window Forms
Add a Label
4. Now we will put some text into the top of the window itself. From the Toolbox, select All Windows Forms,
Label and drag the Label onto the window.
5. From the properties of the label, change the text to This is my Window and change the font size to 16.
Index
X Close
Back | Next
216
Visual COBOL
18 Window Forms
Index
X Close
Back | Next
217
Visual COBOL
18 Window Forms
Finally you should debug the code and watch how it behaves.
Index
X Close
Back | Next
218
Visual COBOL
18 Window Forms
Module Summary
In this module we covered the following topics:
Index
X Close
Back | Next
219
Visual COBOL
18 Window Forms
Quick Quiz
1. The default program Form1.cbl contains the methods associated with the objects on the form?
a. TRUE
b. FALSE
2. The default program Form1.cbl contains the properties associated with the objects on the form?
a. TRUE
b. FALSE
3. The default program Form1.Designer.cbl contains the methods associated with the objects on the form?
a. TRUE
b. FALSE
4. The default program Form1.Designer.cbl contains the properties associated with the objects on the form?
a. TRUE
b. FALSE
5. The default program Main.cbl contains:
a. Object methods
b. Object property information
c. Application start up code
6. Which of the following programs would you expect to edit directly as a COBOL programmer:
a. Form1.cbl
b. Form1.Designer.cbl
c. Main.cbl
d. LegacyCode.cbl
Index
X Close
Back | Next
220
Visual COBOL
Web Forms
Index
X Close
Back | Next
221
Visual COBOL
19 Web Forms
Introduction
Operating in the.NET environment you can build your Windows forms and write all your processing code in COBOL
incorporating functionality of the .NET Framework as needed.
You can also create Web Forms and employ the power of COBOL via Visual Cobol in the World Wide Web.
For legacy applications, the Web means that COBOL programs can take on new life by adding Web connections
through simple .NET COBOL statements.
It also means that COBOL programmers can use COBOL to program the connections between important enterprise
applications, data, and the rest of the world.
We will also get an overview of the Visual COBOL syntax used in the access to Web Forms.
We will do this through a series of exercises.
Module Objectives
At the end of this module you will be familiar with:
Input data validation with a distinction between client and server side validation.
The server sends the code describing a Web page to the clients browser then terminates the connection to
the browser.
The browser interprets the code and displays the Web page.
The browser connects to the server and returns data from the Web page.
The server disconnects from the browser then executes code associated with the page.
The server reconnects to the browser and returns the page or another page back to the browser.
The browser interprets the code and displays the requested information.
When execution begins with a conventional Windows application, the processing program(s) remain active and the
object data of the defined classes is persistent from one execution of a class to the next.
In a Web application, the browser sends a request to the server, the server responds and then terminates. Data
created during execution of the server-side code is not retained (i.e. stateless) as with Windows applications. An
important feature of Visual Studio is that you can develop Web applications entirely in a local environment (without
going to an outside server).
Index
X Close
Back | Next
222
Visual COBOL
19 Web Forms
2. Highlight the folder where the application resides, which in our case is C:\COBOLClass\Websites\Webdemo
(Just the folder name required).
3. Click Open.
4. Look at the web form by right clicking on default.apsx in the solution explorer and selecting View Designer.
5. First Run the Web Form.
You may be presented with a window entitled Debugging Not Enabled presenting two options. Accept the
enable debugging option.
6. After a moment your browser will appear with a display as if it had come from a remote site on the internet.
A URL will be displayed in the browser: http://localhost:61420/WebDemo/Default.aspx. The entry localhost
indicates this Web page resides on your own computer. That is, your computer is functioning as both the client
and the server.
The number 61420 will vary.
7. Type in your name and press OK.
Index
X Close
Back | Next
223
Visual COBOL
19 Web Forms
2. Now press F5 to run the application. The web page will appear. Enter your name and click OK.
3. This will break into the program as shown.
Index
X Close
Back | Next
224
Visual COBOL
19 Web Forms
4. Make sure the Web Location is set as File System and set the name as
C:\COBOLClass\WebSites\MyFirstWebSite.
5. Click OK.
Index
X Close
Back | Next
225
Visual COBOL
19 Web Forms
6. Right-click on Default.aspx in the solution explorer and choose View Designer you then have an empty form.
7. Populate the form. from the Toolbox, with the entries shown below:
8. Make sure the **** GREETING **** is a label with the name lblGreeting.
9. Add a Click here button and give it the ID btnClickHere.
10. Double click the button and add the following code to the Click Here button code:
Index
X Close
Back | Next
226
Visual COBOL
19 Web Forms
Index
X Close
Back | Next
227
Visual COBOL
19 Web Forms
8. Finally put a valid number back in again and click the button.
9. Check out what is happening inside the COBOL program Nothing!
10. Right-click on the Default.aspx file and select View Markup.
11. Here you will see how the validation has been defined in XML.
So the validation is being done at the Form itself with no return to the program.
Other types of validation can be done also, including:
Index
X Close
Back | Next
228
Visual COBOL
19 Web Forms
Index
X Close
Back | Next
229
Visual COBOL
19 Web Forms
7. You can now spend some time examining the various components of this application and how they all
fit together.
Note: Website design is not a trivial process, but is it no more complex in COBOL than any other
.NET programming language.
Module Summary
Now, at the end of this module you should be familiar with:
Input data validation with a distinction between client and server side validation.
Quick Quiz
1. A Win Form application behave in just the same way as a Web Form application.
a. TRUE
b. FALSE
2. On a Web form data validation is always best done at the Form itself.
a. TRUE
b. FALSE
3. If you want to validate a field on a Web Form against a record key value, this can only be done in the
program, not the form.
a. TRUE
b. FALSE
Index
X Close
Back | Next
230
Visual COBOL
Web Services
Index
X Close
Back | Next
231
Visual COBOL
20 Web Services
Introduction
Web Services essentially provide the ultimate client/server environment.
At the most basic level, the Web Services concept represents a new flavor of standards-based software
technology that lets programmers combine existing computer systems in new ways, over the Internet, within
one business or across many.
Web Services permits organizations to bridge communication gaps between software written in different
programming languages, developed by different vendors and/or running on different operating systems.
We will look at how we can access an external Web Service from COBOL and how we can create our own
COBOL Web Service.
Module Objectives
At the end of this module you will be familiar with:
How to use an existing Web Service available to anyone through the Web.
Index
X Close
Back | Next
232
Visual COBOL
20 Web Services
The example shown above is a Morse code translator. This is sometimes available, sometimes, not. This is
potentially true of all free web services.
At these sites you can obtain needed information to use a service. Be forewarned, however, that these methods are
often experimental, depend on remote servers being up and running or can be arbitrarily changed or removed by
the author.
While the option to use these published services is worth exploring, for the most part, you will need to code and
publish methods on your own enterprise servers.
Index
X Close
Back | Next
233
Visual COBOL
20 Web Services
3. Type in a simple phrase e.g. Romans. This will take a while first time in, depending on your internet connection
speed and the speed of the external server.
4. The results will be:
5. Now try the string lend me your ears and see what is returned.
Index
X Close
Back | Next
234
Visual COBOL
20 Web Services
Index
X Close
Back | Next
235
Visual COBOL
20 Web Services
12. Click the Advanced button and click the Add Web Reference on the next page.
Index
X Close
Back | Next
236
Visual COBOL
20 Web Services
16. Leave the Web reference name as it is and click Add Reference.
17. You may get a message about Value cannot be null. This is not a problem, just click OK.
18. This will generate a number of additional items shown below (no need to touch any of these).
Index
X Close
Back | Next
237
Visual COBOL
20 Web Services
2. Choose the name FirstWebService as the name for both the solution and project and click OK.
Index
X Close
Back | Next
238
Visual COBOL
20 Web Services
6. A test harness is provided for you called the WCF Test Client window will appear showing the two methods
provided in IService1.
7. Double click the method GetData() and this will give you Request and Response entries.
Index
X Close
Back | Next
239
Visual COBOL
20 Web Services
11. Run the service once more as above and step through the code. When you are happy with that,
stop debugging.
Index
X Close
Back | Next
240
Visual COBOL
20 Web Services
13. You will also need to change the method GetData in the interface program IService1.cbl to:
14. Now execute the code again and try out your revised method.
15. Now we feel happy that the Web Service is executing as required, we now need a suitable client to access it.
Index
X Close
Back | Next
241
Visual COBOL
20 Web Services
Add a client
1. While the FirstWebService solution is open, select File, New, Project and give the project the following
properties:
Name : FirstWebClient.
Location: C:\COBOLClass\Projects\FirstWebService.
2. Click OK.
Index
X Close
Back | Next
242
Visual COBOL
20 Web Services
4. Click Discover and select the FirstWebSevice and give the Namespace the name FirstServiceReference.
5. Click OK and this will add reference details into your FirstWebClient.
6. You now need to right click on your FirstWebClient project and select set as startup project.
Index
X Close
Back | Next
243
Visual COBOL
20 Web Services
Note: To make this easier for you, there is a file CopyAndPaste.txt supplied in C:\COBOLClass\DataFiles which
contains the above program code. You can copy and paste this if you require. (You may find it more interesting to
just type this in yourself, line by line, to see intellisense in action). Intellisense is Microsofts implementation of
auto-complete for functions.
Module Summary
Now at the end of this module you should be familiar with:
How to use an existing Web Service available to anyone through the Web.
Index
X Close
Back | Next
244
Visual COBOL
20 Web Services
Quick Quiz
1. A Web Service is another name for a Web Form.
a. TRUE
b. FALSE
2. To use a Web Service you need a Web Form.
a. TRUE
b. FALSE
3. To use a Web Service you need a Client.
a. TRUE
b. FALSE
4. A client to a Web Service can be:
a. A Web Form
b. A Win Form
c. A Console Application
d. Any of these
e. None of these
Index
X Close
Back | Next
245
Visual COBOL
Mixed
Languages
Index
X Close
Back | Next
246
Visual COBOL
21 Mixed Languages
Introduction
This module deals with the use of mixed language applications.
It is often the case where your development team has people who are skilled at developing applications in
languages other than COBOL. Yet you still want to be able to communicate with components written in COBOL.
A good example of this is where you have in-house .NET Visual Basic (or C#) knowledge but need to access
COBOL legacy code for your business logic and file handling.
This module deals with such a scenario.
In order to follow along fully with the example shown you will need to have a version of Visual Studio which
includes Visual Basic .NET. If you do not have this, you will still be able to see what to do, but just not be able to
do it yourself.
So the purpose of this chapter is to introduce the interaction of Mixed Language Applications. The focus is on
Visual Basic both as an interface to a COBOL application and as a vehicle for data exchange. At the end of this
module, you will see equivalent examples using C#.
The principal here is to illustrate how easy it is to combine .NET COBOL with other .NET languages. VB is just
used as the vehicle to do this.
We will do this through a series of exercises.
Module Objectives
At the end of this module you will be familiar with:
A Visual Basic user interface (Windows form) and a COBOL class used to perform calculations.
Passing date data between Visual Basic and COBOL (and the reverse) as string data.
Index
X Close
Back | Next
247
Visual COBOL
21 Mixed Languages
PIC 99
PIC 99v99
PIC XXX
Etc.
INT16
String
Single
Etc.
In order for VB to communicate with COBOL and vice-versa, we need to handle this data type issue.
This problem is easily resolved by using new data types that have been added to Visual COBOL.
Index
X Close
Back | Next
248
Visual COBOL
21 Mixed Languages
You will see a GUI front end where you entre a Radius value and it returns the results. The GUI front end is VB;
the calculations are done on COBOL.
3. Now look at the COBOL program CircleCalculations.cbl.
This is very much the same as we did with the Object COBOL Circle solutions. The only difference here is the
addition of the data type float-short. The COBOL complier matches this to an MSIL data type that both COBOL
and VB understand. For a full list of the matching data type you will need to look in the Visual COBOL help system.
You will notice that the property clause has been added to the COBOL Class data items.
Index
X Close
Back | Next
249
Visual COBOL
21 Mixed Languages
The line CircleCalculatiom.Radius = txtRaduis.Text sets the value of the Radius in the COBOL
program because of the property clause in COBOL.
5. The final thing we need to know is how did the VB project know about the COBOL project? This is done by
adding references to the VB project. Select the VB project CircleUI, right click and select Properties. From
there select the References tab.
You will see 2 COBOL references; one is to the COBOL runtime system, the other is to the CircleCOBOL
project. These were simply selected by clicking Add on this screen.
Index
X Close
Back | Next
250
Visual COBOL
21 Mixed Languages
6. If this is the first time you have seen two projects in one solution, you will see that the CircleUI project is bold,
indicating that it is the startup project for the solution.
7. This was set by right-clicking on the project and selecting Set as Startup Project.
Index
X Close
Back | Next
251
Visual COBOL
21 Mixed Languages
2. You should work through this example at your own pace. The things to look for are:
a. The COBOL method is no longer a Class method but an instance method.
b. Because of the above the VB program will need to create an instance of CircleCalculations
c. New data types have been introduced into the COBOL program.
3. At this point it is easy to understand now how a VB .NET program can communicate with a COBOL Class, but
how can VB communicate with a piece of COBOL legacy code with the different data types? Well that it is easy;
VB needs to communicate using its own data types to a COBOL Class which supports those data types.
4. Of course the COBOL class can communicate with a legacy COBOL program using the data types that are
native to COBOL. So the final unknown is how COBOL converts the new data types to regular COBOL data
types. The answer is with the SET statement. e.g.
DATA DIVISION.
01
01
OLD-CHAR-DATA
OLD-NUM-DATA
PIC X(20).
PIC 99v99.
01
01
NEW-DATA
NEW-NUM-DATA
STRING.
DECIMAL.
PROCEDURE DIVISION.
SET OLD-NUM-DATA TO NEW-NUM-DATA
SET NEW-CHAR-DATA TO OLD-CHAR-DATA
Etc.
Index
X Close
Back | Next
252
Visual COBOL
21 Mixed Languages
Index
X Close
Back | Next
253
Visual COBOL
21 Mixed Languages
This method calls the legacy COBOL program to fill the array from disk.
Notice how the MOVE statement has been used to move data between regular COBOL data types and .NET
data types.
b. TableAccess.cbl is a called procedural program which simulates getting 5 records from disk and passing
them back in linkage section.
Index
X Close
Back | Next
254
Visual COBOL
21 Mixed Languages
4. Execute the application and then debug the application to see how everything fits together.
Index
X Close
Back | Next
255
Visual COBOL
21 Mixed Languages
Managed COBOL
.NET class
C# type
Description
binary-char
System.SByte
sbyte
binary-char unsigned
System.Byte
byte
Not CLS-compliant
An 8-bit unsigned integer
binary-short
System.Int16
short
binary-short unsigned
System.UInt16
ushort
Not CLS-compliant
A 16-bit signed integer
binary-long
System.Int32
int
binary-long unsigned
System.UInt32
uint
binary-double
System.Int64
long
Not CLS-compliant.
A 64-bit signed integer
binary-double unsigned
System.UInt64
ulong
float-short
System.Single
float
float-long
System.Double
double
condition-value
System.Boolean
bool
Not CLS-compliant
A single-precision (32-bit)
floating-point number
A double-precision (64-bit)
floating-point number
A boolean value (true or false)
character
System.Char
char
decimal
System.Decimal
decimal
type System.IntPtr
System.IntPtr
type System.UIntPtr
System.UIntPtr
object
System.Object
object
string
System.String
string
Index
X Close
Not CLS-compliant
The root of the object hierarchy
An immutable, fixed-length string of Unicode
characters
Back | Next
256
Visual COBOL
21 Mixed Languages
Details of these types and other useful information can be found at:
http://documentation.microfocus.com/help/index.jsp?topic=%2Fcom.microfocus.eclipse.infocenter.visualcobol.
vs%2FH2TYRHTYPE01.html
Module Summary
Now, at the end of this module, you should be familiar with:
A Visual Basic user interface (Windows form) and a COBOL class used to perform calculations.
Passing date data between Visual Basic and COBOL (and the reverse) as string data.
Exercise 6 - Using C#
If you are interested in the C# equivalents of the VB examples, there are a few samples you can look at inside:
21_01_CSharpCircleA
21_02_CSharpCircleB
21_03_CSharpCircleC
21_07_CSharpWinBook
Index
X Close
Back | Next
257
Visual COBOL
21 Mixed Languages
Quick Quiz
1. In order for VB to use a COBOL Class, the VB project needs to have COBOL data types
a. TRUE
b. FALSE
2. In order for VB to use a COBOL Class, the COBOL project needs to have .NET data types
a. TRUE
b. FALSE
3. In order for VB to use a COBOL Class, the VB project needs to have a reference to the COBOL run time
a. TRUE
b. FALSE
4. In order for C# to use a COBOL Class, the C# project needs to have a reference to the COBOL run time
a. TRUE
b. FALSE
Index
X Close
Back | Next
258
Visual COBOL
.NET Error
Handling
Index
X Close
Back | Next
259
Visual COBOL
Introduction
A .NET error is an event that interrupts or disrupts the normal flow of code and creates an exception object. The
error is the event, while an exception is the object that the event creates.
Factors that cause errors and subsequent exceptions include user errors, resource failures, and failures of
programming logic.
Exceptions are commonly divided into two categories, application and runtime exceptions.
While a program can handle and recover from application exceptions most runtime exceptions occur as a result of
errors encountered by the .NET CLR and are not recoverable.
Module Objectives
At the end of this module you will be familiar with:
Error recovery.
The above shows a typical error screen in the .NET run-time environment. As you can see this is not the kind of
screen that the end-user of your application would want to see.
Index
X Close
Back | Next
260
Visual COBOL
Try
Statement which can cause an exception, to be monitored/tested for exception occurrence during its execution
Catch exception object
Statements for handling the exception code that is executed only if an exception occurs in the Try block
Finally
Clean up code code that is executed whether of not the catch block is executed
End Try
Index
X Close
Back | Next
261
Visual COBOL
All exceptions in the .NET framework derive directly or indirectly from the System.Exception class.
COBOL requires that you define an object of the exception class since that object will contain exception information
whenever an exception occurs.
Notice that the Catch clause must include an object reference identifying the type of exception to be caught. In
this example, since loExceptionObject is type System.Exception, any occurring exception will be caught here.
Another aspect just for this example is that only one statement comprises the Try block. You would use this
approach in any application where you must monitor a statement that might produce an error when executed.
In this example inclusion of the Trim method forces the exception when there is no entry for the name field. Be
aware that the application itself does not require the Trim. It is included only to produce the error condition.
Note: In this example the try just contains one .NET statement. It can of course contain more if you wish, although
any error that is trapped in the Catch can then be from any of the .NET statements in the Try.
Exception Example
There is a solution ExceptionCircleA.sln inside \COBOLClass\Projects\22_01_ExceptionCircleA which is a
VB/COBOL combination. The GUI screen asks for a name and a circle radius. If the name is empty then a .NET
exception is caused. In this case, the user does not even get an error screen. The program just terminates with no
message not good!
Index
X Close
Back | Next
262
Visual COBOL
The two COBOL programs CircleWrapper and CircleWrapperCheck are basically the same program, but the
check version does handle the exception. In the VB program you can see there is a switch between the two
COBOL programs depending on the value of lstException.Text.
Index
X Close
Back | Next
263
Visual COBOL
All is well!
4. Now leave the No Trap set, delete Your name and put a value into Radius and click Calculate. The
application terminates with no message.
5. Now run the application once more; select Trap, leave Your name empty and put a value into Radius and
click Calculate.
Index
X Close
Back | Next
264
Visual COBOL
7. To see how that was done, look inside the codes in both CircleWrapper.cbl and CircleWrapperCheck.cbl.
Make sure you execute in debug mode.
Circle Wrapper
CircleWrapperCheck
Index
X Close
Back | Next
265
Visual COBOL
This program is used as a holding place for instance data. It is a very popular technique for doing this.
Look how this is used inside CircleWrapper.cbl
Index
X Close
Back | Next
266
Visual COBOL
Module Summary
Now, at the end of this module, you should be familiar with:
Error recovery.
22_02_ExceptionCircleB.
22_03_ExceptionCircleC.
22_04_ExceptionCircleB.
They illustrate more use of try-catch including checking for specific error types and also nested Try-Catches.
Quick Quiz
1. There is no need to check for .NET run time errors
a. TRUE
b. FALSE
2. The syntax TRY-CATCH is traditional COBOL syntax
a. TRUE
b. FALSE
3. You can only use TRY-CATCH for .NET specific run time errors
a. TRUE
b. FALSE
4. Regular COBOL errors must be detected by some other method
a. TRUE
b. FALSE
Index
X Close
Back | Next
267
Visual COBOL
Modern COBOL
Conclusions
Index
X Close
Back | Next
268
Visual COBOL
Course Follow-on
There are many samples provided by Microfocus, which you may want to examine. These samples can be found
from the Windows Start menu under Microfocus Visual COBOL, Samples.
When you select this you will get the Samples Browser:
Just out of interest, this Samples Browser was written using Visual COBOL and you can even load the solution
that does this.
Index
X Close
Back | Next
269
Visual COBOL
Course Examination
You are now ready to take the course examination, as provided by your tutor.
Index
X Close
Back | Next
270
Visual COBOL
Appendix I
Index
X Close
Back | Next
271
Visual COBOL
24 Appendix I
Introduction
This appendix, re-introduces you to the features of Managed COBOL; particularly those which relate to Object
Oriented COBOL.
This course has primarily been directed at the Microsoft .NET environment, using Visual Studio as the
development IDE. However most of what has been covered applies equally to the Java Virtual Machine (JVM),
using Eclipse as the development IDE. (Micro Focus supplies a version of Visual COBOL which is based around
Eclipse and Java JVM).
Index
X Close
Back | Next
272
Visual COBOL
24 Appendix I
Index
X Close
Back | Next
273
Visual COBOL
24 Appendix I
Index
X Close
Back | Next
274
Visual COBOL
24 Appendix I
Objects
Our simple example so far has helped demonstrate the basic concept of a class but the value of Object Oriented
Programming (OOP) is not yet apparent. The power of OO really comes into play when we encapsulate data within a
class, provide methods that perform actions on that data and then create instances of the class for use at runtime.
Creating an instance of a class results in the creation of an object. Each object maintains a separate set of data
items that the methods act upon.
You can create many instances of a class, so therefore you can have many objects each with data distinct from
other objects in the system.
For example, if we considered the kind of data we might need in a simple bank account class, we might think of
such things as account number, balance and some way in which we could store transactions. At runtime, we could
conceivably create a unique object for each customer we were dealing with where each object maintains distinct
data from other customers at our bank.
In our first example, we did not define any data in our class and we didnt create an object at all but we were still
able to invoke the method. This was due to the STATIC clause on the method which can call be applied to data.
method-id SayHello static.
We can invoke static methods directly of the class itself without creating an instance of the class.
Index
X Close
Back | Next
275
Visual COBOL
24 Appendix I
Static methods and static data can be useful at times but there is only ever one instance of the static data. Static
methods can only operate on static data.
Index
X Close
Back | Next
276
Visual COBOL
24 Appendix I
Constructors
method-id New.
procedure division using a-name as string.
Set your-name to a-name
end method.
Whenever an object is created, the runtime system automatically invokes the New method on the class. If you didnt
code one, the compiler automatically creates one for you.
In our method above, not only have we defined a constructor but we have also specified that it take a parameter.
Given this, we need to change our code that creates the object:
set an-obj to new MyClass(Scot)
By the way, this code could also have been written as:
set an-obj to MyClass::New(Scot)
This can be found in the solution 24_04_Simple_object2.sln.
Index
X Close
Back | Next
277
Visual COBOL
24 Appendix I
Recap
So far weve seen how you can create a class with static methods and instance methods declare data, initialize our
data using by defining a constructor and weve also looked at method overloading. Weve also seen how you create
an instance of a class and invoke a method on it.
If you have Visual COBOL installed, now would be a good time to either type this code yourself and step through in
the debugger or to load an examine the 4 solutions already provided.
To do this, either create a Java based JVM COBOL project in Eclipse or a managed COBOL console application in
Visual Studio.
Properties
We already saw briefly how the property clause allows us to access object instance data directly. Lets look some
more at this.
Our class has some data associated with it, a string called your-name. This data is not, by default, accessible
directly by the program using the class just as the working-storage of one program is not accessible to another
program.
Properties allow you to expose your data items to the user of your class.
Currently, our single data item looked like this:
01 your-name pic x(10).
We can turn this data item into a property as follows:
01 your-name pic x(10) property.
Index
X Close
Back | Next
278
Visual COBOL
24 Appendix I
display an-obj::Name
Whilst were looking at properties, lets return to the subject of the STATIC clause which can also be applied to
properties:
01 dataitem pic x(10) property as DataItem static.
If we recall, there is only ever 1 instance of a static data item regardless of how many objects have been created.
Static data items are referenced through the class itself, we do not need an instance to access them:
set MyClass:DataItem to some text
Method Visibility
The Methods we have defined so far have all been public, the default for COBOL. A public method means that it
can be invoked through the object reference. However, most classes have a need to for methods which we dont
want to be visible outside of the class. Such methods are called private methods:
To declare a private method:
method-id ProcessData private.
This method could not be invoked through the object reference and if you tried youd encounter a compiler error.
You can invoke this method from inside the class itself, say, from inside a public method:
method-id DoSomething public.
procedure division using
invoke self::ProcessData
end method.
Notice the use of the special keyword self. In this case, that just means invoke a method called ProcessData which
is defined in this class.
Index
X Close
Back | Next
279
Visual COBOL
24 Appendix I
Local Data
When writing procedural COBOL programs, we only have the choice of declaring all our data in the working-storage
section. When working with classes, we still use the working-storage section for data that is associated with the
class but we can also define data that is used only by a method:
method-id ProcessData private.
Local-storage section.
procedure division.
perform varying counter as binary-long from 1 by 1 until counter > 10
In this example, our method has access to a local variable called counter. The lifetime and scope of this variable is
entirely associated with the execution of this method. This field cannot be referenced outside of the method and on
every invocation of the method, counter is set to its default value.
Recap
Weve now covered properties and method visibility and were probably 50% through the basics of OOP. One thing
worth pointing out here is that classes can contain all of the regular COBOL semantics you use in procedural
programming today.
For example, your class could contain a file section and methods can contain sections and paragraphs if desired
and of course, you can use standard COBOL records within working-storage section.
Data Types
So far, our classes have used COBOL data types such as PIC X. All of the data types you use in COBOL today are
supported in .NET but are only accessible to and understood by COBOL.
.NET and JVM do not have the concept of a PIC X or group record, let alone comp-1,-2,-3,-4,-5,-6,-X types. Whilst
this is fine for your COBOL class and passing these types to other COBOL programs, they are not understood by
other languages in the .NET framework.
To help transition COBOL types to other languages, there are a set of predefined types which are natively
understood by .NET and JVM and map directly. These types are listed in the table at http://documentation.
microfocus.com/help/index.jsp?topic=%2Fcom.microfocus.eclipse.infocenter.visualcobol.
r4u2vc%2FH2TYRHTYPE01.html.
One example where all the following declarations refer to the same type:
01 val-1 binary-short.
01 val-2 pic s9(4) comp-5.
01 val-3 System.Int16
These are all different ways of saying the same thing, declaring a 16bit signed integer.
Index
X Close
Back | Next
280
Visual COBOL
24 Appendix I
Inheritance
Inheritance is an important part of OOP. It allows us to create a new class by extending the functionality of an
existing class. If we choose to, we can also change the behaviour of the class we are extending.
Lets consider a bank account example. We might imagine that accounts of any type, checking, savings, etc. share
common data such as an account number field and a balance but the process of withdrawing money from an
account might require different processing. A checking account may need to check whether an overdraft limit is in
place and a savings account, which will not have an overdraft, will need to check other factors that affect interest
earned, such as the amount of money that can be withdrawn within a given period.
An important consideration well look at later is that whatever is using these objects, lets say the ATM machine,
should not need to determine the type of account its dealing with and then perform different processing. It simply
wants to perform a withdrawal action against whatever account object it is using.
For now though, lets just look at how we can both extend an existing class and customize behaviour.
Heres a simplistic account class:
Class-id BankAccount.
Working-storage section.
01 account-number 9(8) property as AccountNumber.
01 balance float-long.
Method-id Withdraw.
Procedure division using amount as float-long
returning result as condition-value.
*> Process withdrawal
End-method.
End-class.
Index
X Close
Back | Next
281
Visual COBOL
24 Appendix I
This type of class, named BankAccount is often referred to as the base class as it forms the base of a hierarchy of
classes that emanate from this one.
Lets create a new class to represent a specialization of the bank account, a savings account:
class-id SavingsAccount inherits BankAccount.
Method-id Withdraw override.
Procedure division using amount as float-long
returning result as condition-value.
End-method.
*> Specialized process for Savings withdrawal
End-class.
Besides defining a new class for savings accounts we have used the INHERITS clause to denote we are extending
an existing class in the system. All public members (methods, properties, fields defined as PUBLIC) of the base
class become part of the new class.
As such, an object that is of the type SavingsAccount, also has properties called AccountNumber, balance and a
method named Withdraw which have been inherited from the base class BankAccount.
Our SavingsAccount class also has a method called Withdraw which will manage the different way in which money
is withdrawn from a savings account. To indicate this is a change in behaviour to the method in the base class, we
use the OVERRIDE keyword. The significance of this keyword will become more apparent later on.
class-id CheckingAccount inherits BankAccount.
Without fleshing out this new class, which also provides an override for the Withdraw method, we now have
3 classes in our class hierarchy.
Lets look at the effect of object instantiation and method invocation:
Program-id. TestBankAccounts.
01 account type BankAccount.
Procedure division.
set account to new SavingsAccount
set account::AccountNumber to 12345678
set account::Balance to 500.00
End-program.
The key point to notice is the declaration of our objects type, BankAccount, and the creation of it, as a
SavingsAccount.
Index
X Close
Back | Next
282
Visual COBOL
24 Appendix I
We can do this because SavingsAccount inherits (or descends) from BankAccount. The value of doing this is not so
apparent in this example but this next might help:
Method-id PerformWithdrawal.
Procedure division using by value amount as float-long
account as type BankAccount.
If Account::Withdraw(amount) not true
*> perform error condition
End-if
End-method.
In this case, a method receives an argument of type BankAccount from which it performs a withdrawal action. The
method does not need to know about all the different types of accounts but whichever object type is passed in, the
correct Withdraw method associated with that type is executed, be that a savings or checking account.
This is a very useful feature of OOP as it decouples implementation details from clients that use the classes. This in
turn allows us to extend the system by adding new types of bank account but minimizing the impact on existing code.
Under both JVM and .NET, you can only inherit from one base class but, of course, the base class itself can inherit
from a class and so on.
If a derived class needs to invoke the implementation of a method defined in the base class, it can do so using the
SUPER keyword. For example, we can call the BankAccount WithDraw method from within the SavingsAccount
class as follows:
invoke super::Withdraw(100)
SUPER can be used not only to invoke a method we have overridden in the derived class but to invoke any public
method defined in the class hierarchy we have inherited.
Casting
At times, your application will need to work with the specific type of an object rather than the generic base type. If
you find yourself with a reference to the base type, how do you get to the derived type?
Method-id
local-storage section.
01 Savings type SavingsAccount.
Procedure division using by value account as type BankAccount.
Set Savings to account as SavingsAccount.
Here we cast the object passed as an argument to a specific derived type. Casting one object type to another must
always be done with care as errors may occur if the type being cast at runtime is not the type stated at compile time.
The COBOL language includes syntax to help cater for these situations, such as TYPE OF, which can be used to
test the type of an object before casting. More details of this syntax are referenced in the additional reading section.
Index
X Close
Back | Next
283
Visual COBOL
24 Appendix I
Interfaces
Classes and inheritance allow us to decouple implementation details from the user of the class but there is another
aspect of OOP that can help further decouple implementation, the interface.
An interface, like a class, defines a series of methods and possibly data too, but unlike a class, it does not provide
any implementation within the methods. This is because the purpose of the interface is to merely define what
behaviour a class will have behaviour in this case being the methods and properties defined on the class.
Heres an example of an interface:
Interface-id ErrorHandler.
Method-id notifyError.
Procedure division using by value error-code as binary-short.
End-method.
Method-id notifyWarning.
Procedure division using by value warning-code as binary-short.
End-method.
End-interface.
This interface defines just two methods and from which we can probably deduce would be used for logging an error
of some kind.
By defining a class that supports this interface, we are said to implement the interface.
Class-id MyErrorHandler implements ErrorHandler.
Method-id notifyError.
Procedure division using by value error-code as binary-short.
*> display message box to the user
End-method.
Method-id notifyWarning.
Procedure division using by value warning-code as binary-short.
*> depending on configuration, ignore this or print
*> it to the console
End-method.
End-class.
The IMPLEMENTS keyword defines the interface we intend to provide an implementation for in this class and the
compiler will check that all methods have been implemented correctly.
Unlike inheriting a class, which can only be done with a single class, you can implement as many interfaces as you
like in a single class.
Index
X Close
Back | Next
284
Visual COBOL
24 Appendix I
Invoke self::NotifyErrorHandlers(error-code)
End-method.
End-class.
Program-id TestProgram.
Working-storage section.
01 error-handler type MyErrorHandler.
Procedure division.
Set error-handler to new MyErrorHandler
Invoke ProcessData::RegisterErrorHandler(error-handler)
End-Program
Index
X Close
Back | Next
285
Visual COBOL
24 Appendix I
Class names
So far, our classes have had simple names but this could soon lead to clashes with classes created by other
people. To resolve this, we simply create classes with longer names and employ the use of namespaces which is
nothing more than a convention for naming classes.
Heres a fully qualified class name:
com.acme.MyClass
MyClass is a different class from the following:
com.yourcompany.MyClass
Everything leading up to the class name is considered a namespace if working in .NET or a package name if
working in JVM. In this case, com.acme and com.yourcompany.
This convention allows us to create classes that do not conflict with others classes of the same name.
Whilst this is a naming convention, compilers provide directives and syntax to make working with namespace easier.
In fact, there can also be certain rules about the accessibility of classes within namespaces.
When you reference a class that has a namespace you need to use its fully qualified name. For example:
01 an-obj type com.acme.MyClass.
01 another type com.yourcompany.MyClass.
The COBOL compiler provides a directive that allows you to use the abbreviated name of a class.
$set ILUSING(com.acme)
Index
X Close
Back | Next
286
Visual COBOL
24 Appendix I
Intrinsic types
The COBOL compiler is aware of several classes within the .NET and JVM frameworks and does not require you to
specify its fully qualified name. The two well look at are String (System.String in .NET and java.lang.String in JVM)
and Object (System.Object and java.lang.Object).
Object is important because all classes ultimately inherit from this type, whether you specify it or not. Therefore, any
object can be cast to this type.
String is used commonly and is used for storing Unicode data. In both JVM and .NET, the string once created is
considered immutable. Whichever method on the string class you invoke, the result is a new string object:
01 str-1 type System.String.
01 str-2 String.
01 str
string.
All of the above declarations in .NET are the same.
Notice there is no need to call the new method when creating a string:
set str-1 to Hello World
You can combine strings with regular pic X fields:
01 a-pic-x pic X(10) value something.
display a-pic-x & str1 & blah
Heres an example of using one of the many string methods:
set str-1 to str-1::Replace(foo, bar)
Notice how we assigned the result of this method to the original object. If we did not, str1 would have remained
unchanged.
Index
X Close
Back | Next
287
Visual COBOL
24 Appendix I
Index
X Close
Back | Next
288
Visual COBOL
24 Appendix I
When defining a class, it is also possible to provide implementation of some arithmetic operators such as add and
subtract. The DateTime class defines several operators for date and time arithmetic and comparison.
Whilst you can perform arithmetic on objects by using the operator overloads, classes usually provide equivalent
methods you can invoke directly, as is the case for DateTime. The following line would achieve the same:
Set ts to dt2::Subtract(dt1)
The result of either approach results in a TimeSpan object. This object contains the result of the arithmetic
expression.
Finally, we display the result. Whenever you use the DISPLAY verb with an object reference, the compiler
automatically invokes the ToString method that is defined on the base class, Object. If you remember, all classes
ultimately descend from Object. Ordinarily, the ToString method simply returns the name of the Type, but the
TimeSpan class overrides the ToString method and returns a meaningful string about the TimeSpan object:
display ts
Reflection
When you compile a COBOL program for .NET or JVM, the compiler creates an executable that conforms to the
specification of these platforms. This specification must be adhered to by any language supporting .NET or JVM.
Because all languages conform to a common underlying protocol, it allows classes written in any language to be
easily integrated.
Another advantage of this commonality is something called reflection. Reflection is the ability to examine the
underlying details of a given type.
With this ability, it is possible to inspect the methods that a given type provides, the arguments to each method and
even the code in the body of the method. This is a very powerful feature of the framework and opens up many
possibilities for application development. Although it may not seem immediately obvious as to how reflection can be
valuable, understanding that this capability is possible can help when considering how various technologies in
managed code come together to assist the developer in creating more flexible applications.
One example of the use of reflection is something called Intellisense. Intellisense is a feature of the Visual Studio and
Eclipse IDEs that assists the developer by showing a list of methods and properties available on a given object.
What Next?
This appendix has provided a basic introduction to object oriented programming and has covered many of the
fundamental concepts. OOP is however an extensive subject, there are many other areas to cover including the
many technologies provided by the .NET and JVM platforms before one could feel confident enough to build a .NET
or JVM application with COBOL.
Aside from additional self-study, you should also consider a dedicated training course in C#, VB or Java. These
courses will build upon your knowledge of OOP and enable you to build applications in Java, C# or COBOL as the
principals remain the same across all of these languages the key difference being syntax.
A great way to accelerate your understanding of OOP and managed code frameworks is to work directly with
colleagues skilled in Visual Basic, C# or Java.
Index
X Close
Back | Next
289
Visual COBOL
24 Appendix I
Further Reading
There are a series of examples that Micro Focus provides which you can explore as required. You will find these
from your Windows start menu as:
When you have got there you can explore many features:
Index
X Close
Back | Next
290
Visual COBOL
Appendix II
Index
X Close
Back | Next
291
Visual COBOL
25 Appendix II
Introduction
This appendix lists a number of other language features of COBOL that have not been covered in the previous
modules. These features will be covered very briefly in this appendix. If you require more detail then you will find this
in the Visual Studio Help system:
If you select Product Documentation here you will be taken to the following:
Index
X Close
Back | Next
292
Visual COBOL
25 Appendix II
Module Objectives
The intention of this module is to briefly show you some additional features of COBOL which you may decide to use
or may come across in other pieces of COBOL code.
In particular you will see how Micro Focus provides you with a mechanism to generate COBOL code to access a
relational database.
Line sequential data files (PC text files). These files are normally used for producing reports. The syntax for
the SELECT statement is:
SELECT REPORT-FILE ASSIGN REPNAME
ORGANIZATION IS LINE SEQUENTIAL.
Relative data files. These files are an alternative to using indexed files. They are not very commonly used. The
syntax for the SELECT statement is:
SELECT RE-FILE-FILE ASSIGN REPNAME
ORGANIZATION IS RELATIVE.
Relative files do not need a key (although many do have keys stored on them). Without a key the access is physical
offset in the file. If you want to read more about relative files, good starting points are:
http://www.cse.ohio-state.edu/~sgomori/570/relcob.html or
http://cayfer.bilkent.edu.tr/~cayfer/ctp108/relative.htm
Index
X Close
Back | Next
293
Visual COBOL
25 Appendix II
Report writing
COBOL has extensive support of complex report writing. This was briefly mentioned in an earlier module and will not
be covered here.
This is done in a new COBOL data division section called REPORT SECTION.
A good reference to check out the details of this is http://www.pgrocer.net/Cis52/rptwritr.html
http://theamericanprogrammer.com/programming/10-sortex1.shtml
Local-Storage Section
You will possible have seen that some methods have used LOCAL-STORAGE Section rather than WORKINGSTORAGE section. To all intents the way we have used these so far is identical. For our needs so far, they are
interchangeable.
However, this has another function. The presence of a LOCAL-STORAGE Section in a method indicates that this
method can be used recursively. i.e. a method can call itself.
Intrinsic functions
COBOL supports a large number of intrinsic functions such as:
Sine
Square Root
Cosine
Tangent
Annuity
Date conversion
Log
Max, Min
The syntax for using an intrinsic function is illustrated by the use of the Square Root function:
COMPUTE WS-RESULT = FUNCTION SQRT (WS-NUMBER)
Index
X Close
Back | Next
294
Visual COBOL
25 Appendix II
Library routines
In addition, Microfocus COBOL supports a number of library routines which you may find useful. e.g.
Index
X Close
Back | Next
295
Visual COBOL
25 Appendix II
3. This creates a sample program. Do not delete this but just delete all the text inside the file since we are going to
put different code in there.
4.
Index
X Close
Back | Next
296
Visual COBOL
25 Appendix II
2. Expand the Micro Focus COBOL line and choose OpenESQL Assistant.
Index
X Close
Back | Next
297
Visual COBOL
25 Appendix II
Creating a Query
To create a suitable program we will use the OpenESQL Assistant.
1. Select Tools, Micro Focus COBOL, OpenESQL Assistant.
The list on your machine will be different from the list you see above, but you should see the Library database
that you registered in the last module.
3. Select the Library check box to see the 2 tables Book and Patron. Select the Book checkbox.
Index
X Close
Back | Next
298
Visual COBOL
25 Appendix II
This gives you some skeleton COBOL code, but the code is incomplete since you have not yet chosen any
fields to be used in the query.
5. Click on the fields A.BookID, A.BookTitle and A.BookAuthor. As you select each of these, watch what
happens to the COBOL code.
It would be nice to test what result this code would give us if implemented in a COBOL program.
Index
X Close
Back | Next
299
Visual COBOL
25 Appendix II
These results are not what we wanted; we wanted the query to return the results Book Title order!
7. So, to the Sort tab.
Index
X Close
Back | Next
300
Visual COBOL
25 Appendix II
10. Test this new version of the query by click Run Query once more.
11. As you can see the query is now ordered by Book Title.
Index
X Close
Back | Next
301
Visual COBOL
25 Appendix II
Now we need to get that sample code into our empty program.
3. Now put the COBOL program code into the file by clicking Insert Query into Program.
Index
X Close
Back | Next
302
Visual COBOL
25 Appendix II
7. Position your cursor on the COBOL program on line 13 column 9 (immediately before the EXEC SQL END
DECLARE statement.
8. Now place this in the program by clicking the Insert Query into program once more.
Index
X Close
Back | Next
303
Visual COBOL
25 Appendix II
10. The next thing we need to do is to place our original query to the correct place in procedure division.
11. Switch back to the query tab and place your cursor in the COBOL program around line 27, column 9, just
before the EXEC SQL DISCONNECT statement.
12. Now place this query in the program by clicking the Insert Query into program once more.
Note: You may be happier to cut and paste the Cursor Declaration code into data division. It works either way
round, so we will leave it where it is for now.
Index
X Close
Back | Next
304
Visual COBOL
25 Appendix II
Index
X Close
Back | Next
305
Visual COBOL
25 Appendix II
21. You will see that this is correctly ordered by Book title. Press enter to terminate this.
Other SQL code
In addition to a skeleton program and Query statement the ESQL Assistant can be used to generate many other
types of SQL code.
The original program code does not need to be created using the ESQL Assistant. It can be created any way you
wish. The ESQL assistant just provides a convenient mechanism for generating ESQL code.
1. Start the OpenESQL Assistant once more with Tools, Micro Focus COBOL, OpenESQL Assistant
2. If not already selected, choose the library database once more.
3. We saw earlier how, when we created the original query there were a number of variations.
Index
X Close
Back | Next
306
Visual COBOL
25 Appendix II
Exercise
Extend the current query for the book table to include items from the Patron table. i.e. create a table join.
The fields that determine the join are PatronNumber in each table.
You will also need to generate the host variables for the Patron.cpy file
Module Summary
This appendix has briefly shown you some additional features of COBOL which you may decide to use or may
come across in other pieces of COBOL code.
To explore these extra variants you should look inside the help system under Product Documentation.
Once you have selected Product Documentation, you can search for whatever you require.
In addition, there is a very healthy Micro Focus Community which is shown below.
In particular you have also seen how Micro Focus provided you with a mechanism to generate COBOL code to
access a relational database.
Index
X Close
Back | Next
307
microfocus.com/bridgethegap