CHAPTER 3

image

Data Declaration in COBOL

As you explore the COBOL language, you will notice many differences between it and other programming languages. Iteration, selection, and assignment are all done differently in COBOL than in languages like C, Java, and Pascal. But on the whole, these differences are fairly minor—more a question of nuance than a radical departure. When you are familiar with how iteration and selection work in other languages, COBOL’s implementation requires only a small mental adjustment. Assignment might create more of a hiccup, but there is nothing too radical even in that. The real difference between COBOL and these other languages lies in how data is declared.

This chapter explores the different categories of data used in COBOL. It demonstrates how you can create and use items of each category. Because COBOL’s approach to data declaration affects assignment in COBOL, that topic is also examined in this chapter.

Categories of Program Data

COBOL programs basically use three categories of data:

  • Literals
  • Figurative constants
  • Data items (variables)

Unlike other programming languages, COBOL does not support user-defined constants.

COBOL Literals

A literal is a data item that consists only of the data item value itself. It cannot be referred to by a name. By definition, literals are constants in that they cannot be assigned a different value.

There are two types of literal:

  • Alphanumeric (text/string) literals
  • Numeric literals

Alphanumeric Literals

Alphanumeric literals are enclosed in quotes and consist of alphanumeric characters. Here are some examples:

"William Murphy",   "1528", "-1528",  "1528.95"

image Note  Enclosing the text in quotes defines the item as an alphanumeric literal even though the literal value may be entirely numeric.

Numeric Literals

Numeric literals may consist of numerals, the decimal point, and the plus or minus sign. Numeric literals are not enclosed in quotes. Here are some examples:

1528,   1528.95,  -1528,   +1528

Data Items (Variables)

A data item can be defined as a named location in memory in which a program can store a data value and from which it can retrieve the stored value. A data name, or identifier, is the name used to identify the area of memory reserved for a data item.

In addition to the data name, a data item must also be described in terms of its basic type (alphabetic, alphanumeric, numeric) and its size. Every data item used in a COBOL program must have a description in the DATA DIVISION.

Data Type Enforcement

Languages such as Pascal, Java, and C# may be described as strongly typed languages. In these languages, there are a number of different data types, and the distinction between them is rigorously enforced by the compiler. For instance, if a variable is defined as a float, the compiler will reject a statement that attempts to assign a character value to that variable.

In COBOL, there are only three types of data: numeric, alphanumeric (text/string), and alphabetic. The distinction between these data types is only weakly enforced by the compiler. In COBOL, it is possible to assign a non-numeric value to a data item that has been declared to be numeric.

The problem with this lax approach to data typing is that COBOL programs crash (halt unexpectedly) if they attempt to do computations on numeric data items that contain non-numeric data. In COBOL, therefore, it is the responsibility of the programmer to ensure that non-numeric data is never assigned to a numeric data item intended for use in a calculation. Programmers who use strongly typed languages do not need to have this level of discipline because the compiler ensures that a variable of a particular type can only be assigned an appropriate value.

image Bug Alert  Attempting to perform computations on numeric data items that contain non-numeric data is a frequent cause of program crashes for beginning COBOL programmers. This can easily happen if the data item has not been initialized to a valid starting value.

Figurative Constants

Unlike most other programming languages, COBOL does not provide a mechanism for creating user-defined, named constants. This is a serious deficiency. Named constants make a program more readable and more maintainable.

For instance, although a literal value of .06 (representing the current sales tax rate of 6%) could be used throughout a program whenever the sales tax rate was required, the program would be more readable if the value was assigned to the named constant SalesTaxRate. Similarly, using a named constant would make maintenance easier. If the actual sales tax rate changed, only the constant definition would have to be updated instead of all the places in the program where the literal sales tax rate value was used.

In COBOL, a data item can be assigned a value, but there is no way to ensure that, somewhere in the program, some maintenance programmer has not assigned a different value to the data item.

image ISO 2002  Although this book adheres to the ANS 85 standard, you may be interested to know that this deficiency has been addressed in ISO 2002 COBOL standard by means of the CONSTANT clause entry.

Code example:

01  SalesTaxRate  CONSTANT AS .06.

Although COBOL does not allow user-defined named constants, it does have a set of special constants called figurative constants. Figurative constants are special constant values that may be used wherever it is legal to use a literal value. However, unlike a literal, when a figurative constant is assigned to a data item, it fills the entire item, overwriting everything in it. Figurative constants are often used to initialize data items. For instance, MOVE SPACES TO CustomerName fills the whole data item with spaces, and MOVE ZEROS TO FinalTotal fills that data item with zeros. Table 3-1 shows the COBOL figurative constants.

Table 3-1. Figurative Constants

Figurative Constant

Behavior

ZERO
ZEROS
ZEROES

Behaves like one or more instances of the literal value 0. The constants ZERO, ZEROS, and ZEROES are all synonyms. Whichever is used, the effect is exactly the same.

SPACE
SPACES

Behaves like one or more instances of the space character. SPACE and SPACES are synonyms.

HIGH-VALUE
HIGH-VALUES

Behaves like one or more instances of the character in the highest ordinal position in the current collating sequence (usually the ASCII character set). HIGH-VALUE and HIGH-VALUES are synonyms.

LOW-VALUE
LOW-VALUES

Behaves like one or more instances of the character in the lowest ordinal position in the current collating sequence (the null character [hex 00] in the ASCII character set). LOW-VALUE and LOW-VALUES are synonyms.

QUOTE
QUOTES

Behaves like one or more instances of the quote character. However, it cannot be used to bracket a non-numeric literal instead of the actual quote character. For instance, QUOTE Freddy QUOTE cannot be used in place of "Freddy".
QUOTE and QUOTES are synonyms.

ALL literal

Allows an ordinary literal character to behave as if it were a figurative constant.

Elementary Data Items

An elementary item is the equivalent of a variable in other languages. It is an atomic data item that is not further subdivided. The type and size of an elementary data item are the type and size specified in its PICTURE clause.

In COBOL, an elementary data item declaration consists of a line of code containing the following mandatory items:

  • A level number
  • A data-name or identifier
  • A PICTURE clause

The declaration may also take a number of optional clauses. The most common optional clause is the VALUE clause, which assigns an initial, or starting, value to a data item.

Elementary data items that are not a subdivision of a group item must use a level number of 01 or 77. This book uses 01 for these items. A discussion of the role of level 77s is reserved for later in this chapter.

image Note  A data item declaration may also take a number of other optional clauses such as USAGE, BLANK WHEN ZERO, and JUSTIFIED.

Declaring Elementary Data Items

In typed languages, the data type specified is important because the type determines the range of values that the item can store and governs the operations that can be applied to it. For instance, a Java int data item can store values between -2,147,483,648 and 2,147,483,647 and can only be used in operations that expect an operand of that, or a compatible, type. From the type of the item, the compiler can establish how much memory to set aside for storing its values.

COBOL is not a typed language, so it employs a very different mechanism for describing its data items. COBOL uses what could be described as a “declaration by example” strategy. In effect, you provide the system with an example, or template, or picture of the size and type (alphabetic, numeric, alphanumeric) of the item. From this PICTURE clause, the compiler derives the information necessary to allocate the item.

PICTURE Clause Symbols

To create the required picture, you use a set of symbols. The most common symbols used in standard PICTURE clauses are shown in Table 3-2.

Table 3-2. Common Symbols Used in Standard PICTURE Clauses

Symbol

Meaning

A

Indicates an occurrence of any alphabetic character (a to z plus blank) at the corresponding position in the picture:

01 ThreeLetterAcronym   PIC AAA VALUE "DNA".

X

Indicates an occurrence of any character from the character set at the corresponding position in the picture:

01 Salutation           PIC XXX VALUE "Mr.".

9

Indicates the occurrence of a digit at the corresponding position in the picture:

01 CardinalValue        PIC 9(4) VALUE 1234.

V

Indicates the position of the decimal point in a numeric value. It is often referred to as the assumed decimal point because it is not part of the value but is rather information about the value:

01 TotalSales           PIC 9(5)V99 VALUE ZEROS.

S

Indicates the presence of a sign, and can only appear at the beginning of a picture:

01 IntegerValue         PIC S9(4) VALUE -1234.

image Note  There are many more picture symbols than those listed in Table 3-2. Most of the remaining symbols will be introduced when you explore edited pictures in Chapter 9.

PICTURE Clause Notes

Although the word PICTURE can be used when defining a PICTURE clause, it is normal to use the abbreviation PIC. The recurring symbols in a PICTURE clause can become difficult to count, especially at a glance, so it is normal practice to specify recurring symbols by using a repeat factor inside brackets. For instance:

  • PIC 9(8) is equivalent to PICTURE 99999999.
  • PIC 9(7)V99 is equivalent to PIC 9999999V99.
  • PICTURE X(15) is equivalent to PIC XXXXXXXXXXXXXXX.
  • PIC S9(5)V9(4) is equivalent to PIC S99999V9999.
  • PICTURE 9(18) is equivalent to PIC 999999999999999999.

The repeat factor in brackets is normally used for any picture string with more than three symbols. For instance, a three-digit data item might be described as PIC 999, but a four-digit item would be PIC 9(4).

Numeric values can have a maximum of 18 digits, whereas the limit on string values (PIC X) is usually system dependent.

image ISO 2002  In the 2002 standard, the maximum number of digits in a numeric literal or PICTURE clause was increased from 18 digits to 31 digits.

Example Declarations

In typed languages, because the memory required is defined by a variable’s data type, a picture of what is happening to the data in the memory is not useful. In COBOL, however, knowing what is happening to the data in memory is very important for a proper understanding of how data declaration and data movement work. For this reason, many of the examples in this book are accompanied by an illustration that attempts to show what is happening to the data.

Consider the examples that follow. A simplified version of what is happening in memory is shown in Example 3-1. Later examples use more granular illustrations that show each character of storage. One thing you can already note from even this simple example is that although TaxRate is given an initial value of .35, what is actually in memory is 35. The V in the PICTURE clause tells COBOL to treat this item as if it had a decimal point in the leftmost character position. Example 3-1 also reveals that the values in alphanumeric data items are left aligned and space filled (the example shows the space character as *), whereas numeric data items seem to be right aligned (they aren’t—see the “MOVE Rules” section later in this chapter) and zero filled.

Example 3-1. Data Items and Memory Representation

image

DATA DIVISION.
WORKING-STORAGE SECTION.
01 Num1                 PIC 999   VALUE ZEROS.
01 Num2                 PIC 999   VALUE 15.
01 TaxRate              PIC V99   VALUE .35.
01 CustomerName         PIC X(15) VALUE "Mike".

Assignment in COBOL

In typed languages, the assignment operation is simple because assignment is only allowed between items with compatible types. The simplicity of assignment in these languages is achieved at the cost of having a large number of data types.

In COBOL, there are only three basic data types:

  • Alphabetic (PIC A)
  • Alphanumeric (PIC X)
  • Numeric (PIC 9)

But this simplicity is achieved at the cost of having a complex assignment statement.

The MOVE Verb

Assignment in COBOL is achieved using the MOVE verb. The COMPUTE verb, which assigns the result of an arithmetic expression to a data item, should never be used to assign the value of one item to another. Similarly, the SET verb, which can be used to set a condition name to TRUE or to change the value in a table index, should only be used for these specialized purposes. All ordinary assignments should use MOVE.

MOVE Syntax

The MOVE metalanguage makes the verb seem simple but its operation is complicated by a set of governing rules. The metalanguage for MOVE is as follows:

MOVE Source$#il TO Destination$#i…

MOVE copies data from the source identifier (or literal) to one or more destination identifiers. The source and destination identifiers can be group or elementary data items.

In most programming languages, the data movement in an assignment statement is from right to left. That is, data is copied from the source item on the right to the destination item on the left (for example, Dest := Source Modula-2 or Dest = Source Java). COBOL does things differently. In COBOL, the MOVE verb copies data from the source item on the left to the destination item(s) on the right. Almost all the COBOL verbs conform to this pattern of data movement. The COMPUTE verb, which has its destination data item on the left, is the one exception.

MOVE Rules

The major rules for the MOVE verb are given here. As with all the other verbs, you need to consult your COBOL manual for the more esoteric rules:

  • The source and destination identifiers can be either elementary or group data items.
  • When data is copied into a destination item, the contents of the destination item are completely replaced. The contents of the source item are undisturbed.
  • If the number of characters in the source item is too few to fill the destination item, the rest of the destination item is filled with zeros or spaces.
  • If the number of characters in the source item is too many to fit in the destination item, the characters that cannot fit are lost. This is known as truncation.
  • When the destination item is alphanumeric or alphabetic (PIC X or A), data is copied into the destination area from left to right, with space-filling or truncation on the right.
  • When the destination item is numeric or edited numeric, data is aligned along the decimal point with zero-filling or truncation as necessary.
  • When the decimal point is not explicitly specified in either the source or destination item(s), the item is treated as if it had an assumed decimal point immediately after its rightmost character.

MOVE Combinations

Although COBOL is much less restrictive in this respect than many other languages, certain combinations of sending and receiving data types are not permitted (even by COBOL) and will be rejected by the compiler. The valid and invalid MOVE combinations are shown in Figure 3-1.

9781430262534_Fig03-01.jpg

Figure 3-1. Valid and invalid MOVE combinations
Source: J.M. Triance, Structured COBOL Reference Summary, National Computing Centre Limited, N.C.C Publications, 1984, page 48.

MOVE Examples

Having a dusty set of rules is all very well, but the operation of the MOVE verb can only be appreciated by examining some examples. The examples in this section only feature elementary data items. Things get a lot more exciting when MOVE is used with a group item; you will see some examples of group item moves at the end of the chapter.

Alphanumeric MOVEs

Remember the following rule for alphanumeric MOVEs: when the destination item is alphanumeric or alphabetic (PIC X or A), data is copied into the destination area from left to right with space-filling or truncation on the right.

In Example 3-2, the data item Surname is described as having sufficient storage for eight alphanumeric characters. It has been assigned an initial value of "COUGHLAN".

Example 3-2. Alphanumeric Moves with Truncation and Space Filling

image

When the first move is executed, "SMITH" is copied into Surname from left to right. Because "SMITH" has too few characters to fill Surname, the rest of the data item is filled with spaces.

The second move copies "FITZWILLIAM" into Surname from left to right. Because the literal is too large to fit into Surname, the last three letters (IAM)are truncated.

Numeric MOVEs

Remember the following rule for numeric MOVEs: when the destination item is numeric or edited numeric, data is aligned along the decimal point with zero-filling or truncation as necessary. An edited numeric data item is one that contains symbols such as $ and , and . that format data for output. They are not numeric items, and they can’t be used in calculations (except as the receiving field), but they do obey the decimal-point alignment and zero-filling rules. Edited numeric data items are discussed in Chapter 9.

When the decimal point is not explicitly specified in either the source or destination item(s), the item is treated as if it had an assumed decimal point immediately after its rightmost character.

Example Set 1

In Example 3-3, SalePrice is a data item described as PIC 9(4)V99: that is, a decimal number with four digits before the decimal point and two after it. For each MOVE statement, a diagram showing the contents of the SalePrice data item is given. Each diagram shows the actual data moved in black, the filled zeros in grey, and the truncated digits outside the memory area. The position of the assumed decimal point is indicated with an arrow.

When the figurative constant ZEROS (or ZERO or ZEROES) is moved to SalePrice, the data item is filled with zeros.

When the numeric literal 25.5 is moved to SalePrice, there is alignment along the decimal point of the literal and the assumed decimal point in SalePrice, with the result being zero-filling on both the left and right sides.

When 7.553 is moved to SalePrice, there is alignment of the decimal points, with the result being zero-filling on the left and truncation of the digit 3 on the right. In the diagram the truncated digit is shown outside the memory area.

When 93425.158 is moved to SalePrice, there is alignment of the decimal points, with the result that the most significant digit is truncated on the left and the least significant on the right.

The literal value 128 contains no decimal point, so it is treated as if it had a decimal point in the rightmost position. This decimal point is aligned with assumed decimal point in SalePrice, with the result that there is zero filling on the left and right.

Example 3-3. Numeric MOVEs with Alignment Along the Decimal Point, Truncation, and Zero-Filling

image

Inadvertent truncation is obviously not desirable; but unfortunately, for MOVE operations at least, there is no protection against it. It is up to you to ensure that the data item is large enough to take the data moved into it. Inadvertent truncation is much more likely when calculations are involved. When a number of values are multiplied together, you might not realize that in some cases the result will be too large for the receiving data item. For computations, you can protect against inadvertent truncation by means of the ON SIZE ERROR clause. When this clause is used, it acts like a specialized exception handler. Chapter 4 discusses ON SIZE ERROR when you examine the operation of the COBOL arithmetic verbs.

Example Set 2

In Example 3-4, NumOfEmployees is described as a cardinal number capable of holding a value between 0 and 999. Salary is a decimal number data item with four digits before the decimal point and two after it. CountyName is an alphanumeric data item nine characters long.

The literal value 6745 has no decimal point, so it is treated as if the number has a decimal point in the rightmost position (6745.). NumOfEmployees also contains no explicit decimal point, so it is treated as if the data item has an assumed decimal point specified in the rightmost position:

01 NumOfEmployees PIC 999V

When the literal 6745 is moved to NumOfEmployees, there is alignment along these decimal points. The result is truncation of the most significant digit.

When NumOfEmployees (treated as if defined as 01 NumOfEmployees PIC 999V) is moved to Salary, which does have an explicit decimal point, there is alignment along the decimal points, with the result being zero-filling on both the left and right.

When the literal value 12.4 is moved to NumOfEmployees (treated as if defined as 01 NumOfEmployees PIC 999V), there is alignment along the decimal points with truncation of the digit 4 on the right and zero-filling on the left.

When the literal “Galway” is moved to CountyName, the data movement starts filling the data item from the left. When the value does not entirely fill the data item, the remaining character positions are space-filled.

When the figurative constant ALL and its associated character literal are moved to a data item, the data item is entirely filled with the character specified. In this example, the character specified after ALL is the hyphen, so CountyName is filled with hyphens.

Example 3-4. Numeric and Alphanumeric MOVEs

image

Structured Data

In COBOL, the term elementary item describes an ordinary data item or variable. An elementary item is a data item that is atomic: it has not been further subdivided. Every elementary item must have a PICTURE clause. The PICTURE clause specifies the type and size of the storage required for the data item.

Group Data Items

Sometimes when you are manipulating data it is convenient to treat a collection of elementary items as a single group. For instance, you might want to group the data items Forename, MiddleInitial, and Surname as the group EmployeeName. Alternatively, you might want to group the YearOfBirth, MonthOfBirth, DayOfBirth data items as the group DateOfBirth. In addition, you might want to collect both these group items and some elementary items in an employee record description.

In COBOL, you can easily create groups like these using group items. A group item in COBOL is a data item that is a collection of elementary and/or group data items. It is a heterogeneous data structure. In languages like Pascal and Modula-2, group items are referred to as records. In C and C++, they are called structs. Java has no real equivalent.

The constituent parts of a group item may be elementary items or other group items. But ultimately, every group item must be defined in terms of its subordinate elementary items. Because a group item is ultimately defined in terms of elementary items, it cannot have a PICTURE clause, and its size is the sum of the sizes of its subordinate elementary items. A group item is simply a convenient name that you give to a collection of (ultimately) elementary items. Using that name, you can manipulate the collection.

In a group item, the hierarchical relationship between the various subordinate items of the group is expressed using level numbers. The higher the level number, the lower the item is in the hierarchy and the more atomic it is. If a group item is the highest item in a data hierarchy, it is referred to as a record and uses the level number 01.

The type of a group item is always assumed to be alphanumeric (PIC X, even if it contains only numeric data items) because a group item may have several different data items and types subordinate to it, and an alphanumeric picture is the only one that can support such collections.

Level Numbers

Level numbers01 through 49 are the general level numbers used to express data hierarchy. There are also special level numbers such as 66, 77, and 88:

  • Level 66 is used with the RENAMES clause. The RENAMES clause allows you to apply a new name to a data-name or group of contiguous data-names. It is similar to the REDEFINES clause; but because of the maintenance problems associated with it, the RENAMES clause has largely fallen into disuse and in some programming shops is banned. You learn more about the operation and shortcomings of the RENAMES clause when the REDEFINES clause is examined later in the book.
  • Level 77 is used to identify a noncontiguous, single data item in the WORKING-STORAGE or LINKAGE sections; it cannot be subdivided, and it cannot be part of a group item. In the past, 77s were used for efficiency purposes (77s used less memory than the same items defined as a level 01). Nowadays level 01 is often used instead of 77. Some programming shops take the view that, instead of declaring large numbers of indistinguishable 77s, it is better to collect the individual items into named groups for documentation purposes even if the group, as a group, has no practical purpose. For instance, you might group individual totals such as ShopTotal, CityTotal, StateTotal, and CountryTotal under the group item Totals for documentation purposes. You could not create such a grouping if the items were declared using level 77s.
  • Level 88 is used to implement condition names. Whereas level 66 and level 77 are not used in modern COBOL, level 88s and condition names are very important, useful, and unique weapons in COBOL’s armory. Chapter 5 provides a detailed examination of the declaration and use of level 88s and condition names.

Data Hierarchy

Level numbers are used to express data hierarchy. The best way to understand the data hierarchy and the data-manipulation opportunities afforded by this organization is by means of an example.

Suppose you want to store information about students. You can create a data item called StudentRec and describe it as follows:

01 StudentRec   PIC X(44).

You can load some data into StudentRec using this statement:

MOVE "1205621William  Fitzpatrick 19751021LM051385" TO StudentRec.

Once you have done this, the StudentRec area of storage is instantiated with the data as shown in Example 3-5.

Example 3-5. StudentRec as an Elementary Data Item

WORKING-STORAGE SECTION.
01 StudentRec    PIC X(44).

image

You can see that the data in StudentRec consists of a number of pieces of information: the student’s ID, the student’s name, the date of birth, the course ID, and the student’s grade point average (GPA). But because you have defined StudentRec as an elementary item (an undifferentiated string of characters), you have no easy way of getting at the individual pieces of data. You can move or display the contents of the entire string, but you cannot easily, for instance, display only the date of birth or the student’s name.

What you need to do is to describe StudentRec as a group item that is subdivided into StudentId, StudentName, DateOfBirth, CourseId, and GPA. The revised StudentRec description and the way it appears in storage are shown in Example 3-6.

Example 3-6. StudentRec as a Group Data Item

WORKING-STORAGE SECTION.
01 StudentRec.
   02 StudentId          PIC 9(7).
   02 StudentName        PIC X(21).
   02 DateOfBirth        PIC X(8).
   02 CourseId           PIC X(5).
   02 GPA                PIC 9V99.

image

StudentRec has been subdivided into a number of individual data items. Because StudentRec is now a group item, it has no PICTURE clause. Its size is the sum of the sizes of the elementary items, and its type is alphanumeric.

Defining StudentRec this way presents you with a number of data-manipulation opportunities. You can still manipulate the whole record. For instance, you can flush the entire 44-character area with spaces using a statement like this:

MOVE SPACES TO StudentRec

Or you can move the entire contents to another data item with a statement such as

MOVE StudentRec to StudentRecCopy

But now you can manipulate the individual pieces of data with statements such as these:

DISPLAY "Student name = " StudentName
MOVE ZEROS TO StudentId
MOVE "LM067" TO CourseId
DISPLAY "Current GPA = " GPA
MOVE 2.55 TO GPA
MOVE 19751022 TO DateOfBirth

It is useful to be able to access the individual pieces of data that constitute StudentRec, but the structure is still not quite granular enough. For instance, you can only access the entire student name. It would be nice to be able to manipulate the forename and the surname individually. Similarly, you would like to be able to access the year, month, and day of birth as separate items.

To make these changes, you need to describe StudentName and DateOfBirth as group items. The revised StudentRec description and the effect of this restructuring on the data storage are shown in Example 3-7.

Example 3-7. StudentRec as a Group Data Item

image

With this new structure, many more data-manipulation opportunities become available. You can still access StudentRec, StudentId, StudentName, DateOfBirth, CourseId, and GPA as before, but now you can also manipulate the data at a more granular level using statements like these:

DISPLAY "Student date of birth is " DOB "/" MOB "/" YOB
DISPLAY "Student name = " Surname "," SPACE Forename
MOVE "Billy" TO Forename
MOVE 22 TO DOB

The first statement displays the date of birth on the computer screen:

Student date of birth is 21/10/1975

The second statement displays the student’s name:

Student name = Fitzpatrick, William

image COBOL Detail  When a figurative constant is used with the DISPLAY verb, it inserts only one character; it does not matter if SPACE or SPACES is used, because they are synonyms. If you wanted to insert two spaces in the previous statement, you would have to write the statement as follows:

DISPLAY "Student name = " Surname "," SPACE SPACE Forename

Level-Number Relationships Govern Hierarchy

Level numbers express the data hierarchy. A data hierarchy starts with level number 01; the subdivisions then use any number between 02 and 49 to express the hierarchy. The rule to remember is this: a data item with a level number higher than the preceding data item is a subdivision of that data item; a data item with the same level number as the preceding item is at the same level as that item; a data item with a level number lower than the preceding item is at the same level as its first matching preceding level number. For instance, in Example 3-7, Forename has a level number higher than StudentName, so Forename is a subdivision of StudentName. Surname has the same level number as Forename, so it too is a subdivision of StudentName.

In a hierarchical data description, what is important is the relationship of the level numbers to one another, not the actual level numbers used. For instance, the record descriptions shown in Example 3-8, Example 3-9, and Example 3-10 are equivalent.

Example 3-8 shows my preferred organization and the one used in this book. This organization seems logical and offers benefits of clarity by making the level numbers coincidental with the levels in the structure.

Example 3-8. Preferred Format

01 StudentRec.
   02 StudentId       PIC 9(7).
   02 StudentName.
      03 Forename     PIC X(9).
      03 Surname      PIC X(12).
   02 DateOfBirth.
      03 YOB          PIC 9(4).
      03 MOB          PIC 99.
      03 DOB          PIC 99.
   02 CourseId        PIC X(5).
   02 GPA             PIC 9V99.

Example 3-9 shows that level numbers are used only to show the relationship with the immediately preceding items. For instance, the fact that YOB, MOB, and DOB use level number 14 and Forename and Surname use level 12 is not relevant. What is relevant is that the level numbers show that the items are subordinate to their respective preceding items (StudentName in the first case and DateOfBirth in the second).

Example 3-9. Arbitrary Format

01 StudentRec.
   07 StudentId       PIC 9(7).
   07 StudentName.
      12 Forename     PIC X(9).
      12 Surname      PIC X(12).
   07 DateOfBirth.
      14 YOB          PIC 9(4).
      14 MOB          PIC 99.
      14 DOB          PIC 99.
   07 CourseId        PIC X(5).
   07 GPA             PIC 9V99.

Example 3-10 uses a layout often found in programming shops and COBOL books. This organization lets you create group items by slipping a group item into the description without otherwise disturbing the layout (see the MOBandDOB data item in Example 3-11). This seems like a good idea, and it is is part of the coding standards for some programming shops; but over time, this approach causes the structure’s clarity to deteriorate. In my view, if the data hierarchy needs to be reorganized, then it should be reorganized properly, so that future maintenance programmers will have no difficulty in comprehending the structure created.

Example 3-10. Common Format

01 StudentRec.
   05 StudentId       PIC 9(7).
   05 StudentName.
      10 Forename     PIC X(9).
      10 Surname      PIC X(12).
   05 DateOfBirth.
      10 YOB          PIC 9(4).
      10 MOB          PIC 99.
      10 DOB          PIC 99.
   05 CourseId        PIC X(5).
   05 GPA             PIC 9V99.

Example 3-11. Common Format in Use

01 StudentRec.
   05 StudentId       PIC 9(7).
   05 StudentName.
      10 Forename     PIC X(9).
      10 Surname      PIC X(12).
   05 DateOfBirth.
      08 YOB          PIC 9(4).
      08 MOBandDOB.
         10 MOB       PIC 99.
         10 DOB       PIC 99.
   05 CourseId        PIC X(5).
   05 GPA             PIC 9V99.

Summary

This chapter provided an introduction to data in COBOL. It introduced the different types of data used, and it showed how you can create and use variable data in the form of elementary data items. The chapter examined the assignment operation and discussed the data-manipulation opportunities afforded by the hierarchical structure of group item data declarations.

But this is just an introduction to data declaration in COBOL. In the rest of this book, you expand your knowledge of data declaration by exploring such topics as the implicit redefinition of data items in the FILE SECTION, the operation of the REDEFINES clause, the preparation of data for output using edited pictures, the USAGE clause, and the declaration of tabular information.

LANGUAGE KNOWLEDGE EXERCISE

Using a 2B pencil, write your answer to each exercise question in the area provided.

  1. Create an elementary data item called TaxAmount to hold a value between 0 and 99,999.99.

    _____________________________________________________________________

  2. Create an alphanumeric elementary data item called VideoName large enough to hold 35 characters. Define VideoName so that it is initialized with spaces when the program starts.

    _____________________________________________________________________

  3. A data item called MinimumWage is defined as PIC 9V99. Show what happens to the data after execution of the statement
    MOVE 123.5 TO MinimumWage

    image

  4. A group item called CustomerRec is defined
    01 CustomerRec.
       02 CustId               PIC 9(5)    VALUE ZEROS.
       02 CustName.
          03 Initials          PIC XX      VALUE SPACES.
          03 Surname           PIC X(4)    VALUE SPACES.
       02 Gender               PIC X.      VALUE SPACES.
       02 Payment              PIC 9(5)V99 VALUE ZEROS.
    1. A partial diagram representing the CustomerRec is provided. Complete the diagram by showing how the subordinate data items map to the 19 characters of storage reserved for CustomerRec.
    2. In the first row of the diagram, show how each VALUE clause initializes the data items in CustomerRec.
    3. For each statement in the following program, show what happens to the data in CustomerRec. Use a row for each statement.
      PROCEDURE DIVISION.
      10-BEGIN.
      MOVE "45145MCRyanF23445.67" TO CustomerRec
      MOVE "Male" TO Gender
      MOVE "GSPower" TO CustName
      MOVE "Fitzroy" TO Surname
      MOVE 34 TO Cust-Payment
      STOP RUN.

      image

LANGUAGE KNOWLEDGE EXERCISE—ANSWERS

  1. Create an elementary data item called TaxAmount to hold a value between 0 and 99,999.99.
    01 TaxAmount    PIC 9(5)V99.
  2. Create an alphanumeric elementary data item called VideoName large enough to hold 35 characters. Define VideoName so that it is initialized with spaces when the program starts.
    01 VideoName    PIC X(35).
  3. A data item called MinimumWage is defined as PIC 9V99. Show what happens to the data after execution of the statement
    MOVE 123.5 TO MinimumWage

    image

  4. A group item called CustomerRec is defined as
    01 CustomerRec.
       02 CustId               PIC 9(5)    VALUE ZEROS.
       02 CustName.
          03 Initials          PIC XX      VALUE SPACES.
          03 Surname           PIC X(4)    VALUE SPACES.
       02 Gender               PIC X.      VALUE SPACES.
       02 Payment              PIC 9(5)V99 VALUE ZEROS.
    1. A partial diagram representing the CustomerRec is provided. Complete the diagram by showing how the subordinate data items map to the 19 characters of storage reserved for CustomerRec.
    2. In the first row of the diagram, show how each VALUE clause initializes the data items in CustomerRec.
    3. For each statement in the following program, show what happens to the data in CustomerRec. Use a row for each statement.
      PROCEDURE DIVISION.
      10-BEGIN.
      MOVE "45145MCRyanF23445.67" TO CustomerRec
      MOVE "Male" TO Gender
      MOVE "GSPower" TO CustName
      MOVE "Fitzroy" TO Surname
      MOVE 34 TO Cust-Payment
      STOP RUN.

      image

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.219.33