Custom Search

mainframes cobol defining and using variables

Defining and Using Variables

When you define a variable in the WORKING-STORAGE SECTION of the DATA DIVISION, you are providing information for the compiler about the size of the variable and the type of data that can be stored in it.

A numeric variable is used to store numbers. The picture character used to represent a digit in a numeric variable is a 9, as in this example:

01 THE-NUMBER PICTURE IS 99.

This description defines a variable named THE-NUMBER that can be used to hold a numeric variable that is two digits long; in other words, any value in the range of 0 through 99.

New Term: Variables that can hold character data are called alphanumeric variables.

Alphanumeric data contains one or more printable characters. Some examples of alphanumeric values are Hello, ??506^%$A, and 123-B707. An alphanumeric variable is defined in the same way as a numeric variable, except that the picture character used to represent one alphanumeric character is an X. The following syntax example defines an alphanumeric variable that can hold a word or message of no more than 10 characters:

001200 01 THE-MESSAGE PICTURE IS XXXXXXXXXX.

An alphanumeric variable can also be used to hold numbers (such as storing 123 in a PICTURE IS XXX variable), but you will not be able to use the values as numbers. For example, you could display the PICTURE IS XXX variable containing 123, but you couldn't use the COMPUTE verb to add 1 to it.

In Listing 2.6, a modified version of hello.cbl named hello02.cbl illustrates the use of alphanumeric variables.

TYPE: Listing 2.6. Using an alphanumeric variable.

000100 IDENTIFICATION DIVISION.

000200 PROGRAM-ID. HELLO02.

000300 ENVIRONMENT DIVISION.

000400 DATA DIVISION.

000500

000600 WORKING-STORAGE SECTION.

000700

000800 01 THE-NAME PICTURE IS XXXXXXXXXX.

000900

001000 PROCEDURE DIVISION.

001100

001200 PROGRAM-BEGIN.

001300

001400 DISPLAY "Enter someone's name.".

001500

001600 ACCEPT THE-NAME.

001700

001800 DISPLAY "Hello " THE-NAME.

001900

002000 PROGRAM-DONE.

002100 STOP RUN.

The following is an example of the output from hello02.cbl, using Erica as the name entered at the keyboard:

OUTPUT:

C>pcobrun hello02

Enter someone's name.

Erica

Hello Erica

C>

ANALYSIS: At line 001400, the user is asked to enter a name. At line 001600, the ACCEPT verb will cause the computer to accept input from the keyboard until the user presses Enter. Whatever is typed (up to 10 characters) will be stored in THE-NAME. THE-NAME then is displayed in a hello message.