COBOL NOTES




 

Notes from Wikipedia  http://en.wikipedia.org/wiki/COBOL

 

  Notes from
Wikipedia

 

http://
en.wikipedia.org/wiki/
COBOL

Last updated
10/1/2011 

COBOL - COmmon Business Oriented Language

First compiliers

  • Language specifications completed in 1959
  • First compilers implemented in 1960 on both an RCA computer and also a Remington-Rand Univac computer

ANS COBOL 1968

  • To overcome incompatibility between different versions of COBOL, the American National Standards Institute (ANSI) developed a COBOL standard in 1968 known as (ANS) COBOL.

COBOL 1974

  • ANSI added features.

COBOL 1985

  • Issuedby ANSI and included features including structured language constructs ("scope terminators"), including END-IF, END-PERFORM, END-READ, etc.

COBOL 1997

  • An unofficial draft implemented by Micro Focus, Fujitsu, Veryant, and IBM.
  • Included object-oriented syntax.  based on the 1997 or other drafts of the full revision. The

COBOL 2002 and Object Oriented COBOL

  • The official version inlcuded 1997 features adopted as an ANSI standard by INCITS
    • INCITS is sponsored by the Information Technology Industry Council (ITI), a trade association and operates under rules approved by the American National Standards Institute (ANSI)  [this bullet from http://www.incits.org/geninfo.htm]
  • The 2002 (4th revision) of COBOL included object-orientation and also:
    • National Language support (including but not limited to Unicode support)
    • Locale-based processing
    • User-defined functions
    • CALL (and function) prototypes (for compile-time parameter checking)
    • Pointers and syntax for getting and freeing storage
    • Calling conventions to and from non-COBOL languages such as C
    • Support for execution within framework environments such as Microsoft's .NET and Java (including COBOL instantiated as Enterprise JavaBeans)
    • Bit and Boolean support
    • “True” binary support (up until this enhancement, binary items were truncated based on the (base-10) specification within the Data Division)
    • Floating-point support
    • Standard (or portable) arithmetic results
    • XML generation and parsing 

History of COBOL standards

Cobol 60. issued January 3, 1960  

American National Standards Institute (ANSI) revisions:

In 1985 primary development and ownership assumed by ISO who has issued what ar now ANSI Standards:

  • COBOL 2002
  • Finalizer Technical Report - 2003
  • Native XML syntax Technical Report - 2006
  • Object Oriented Collection Class Libraries - pending final approval...

From 2002, the ISO standard is also available to the public coded as ISO/IEC 1989.

For the latest proposed features, see the COBOL Standards Website.

 

 

 COBOL Programming Course Sub link: The Structure of COBOL Programs

 

U of Limerick
hosts
Michael Coughlan's
"All Things COBOL site"
    A Link from that site:

COBOL Programming Course

Sub link:
The Structure of COBOL Programs

 

 

 COBOL Metalanguage syntax diagrams.

COBOL coding rules

Structure of COBOL programs

Purpose of the IDENTIFICATION, ENVIRONMENT, DATA and PROCEDURE divisions.

The Environment Division

  • Contains all external references, such as to devices, files, command sequences, collating sequences, the currency symbol and the decimal point symbol, are defined in the Environment Division.
     
  • The Environment Division must be maintained when a COBOL program is moved to a new machine, or has new peripheral devices attached, or is required to work in a different country.

COBOL has three main programming constructs - Sequence, Iteration and Selection.

EXAMPLE

We want to write a program which will accept two numbers from the users keyboard, multiply them together and display the result on the computer screen.

Any program consists of three main things;

  • 1.      The computer statements needed to do the job
  • 2.      Declarations for the data items that the computer statements need.
  • 3.      A plan, or algorithm, that arranges the computer statements in the program so that the computer executes them in the correct order.

Program Statements and Data items

What COBOL program statements will we need to do the job specified above and what data items will we need to access?

We will need a statement to take in the first number and store it in the named memory location (a variable) - Num1
      ACCEPT Num1.

We will need a statement to take in the second number and store it in the named memory location - Num2
      ACCEPT Num2.

We will need a statement to multiply the two numbers together and to store the result in the named location - Result
      MULTIPLY Num1 BY Num2 GIVING Result.

We will need a statement to display the value in the named memory location "Result" on the computer screen -
      DISPLAY "Result is = ", Result.

Getting the Algorithm right

 

COBOL MetaLanguage.

In this notation, words in uppercase are reserved words. When underlined they are mandatory. When not underlined they are "noise" words, used for readability only, and are optional. Because COBOL statements are supposed to read like English sentences there are a lot of these "noise" words.

Words in mixed case represent names that must be devised by the programmer (like data item names).

When material is enclosed in curly braces { }, a choice must be made from the options within the braces. If there is only one option then that item in mandatory.

Material enclosed in square brackets [ ], indicates that the material is optional, and may be included or omitted as required.

The ellipsis symbol ... (three dots), indicates that the preceding syntax element may be repeated at the programmer's discretion.

Some notes on syntax diagrams

To simplify the syntax diagrams and reduce the number of rules that must be explained, in some diagrams special operand endings have been used (note that this is my own extension - it is not standard COBOL).

These special operand endings have the following meanings:

$i uses an alphanumeric data-item
$il uses an alphanumeric data-item or a string literal
#i uses a numeric data-item
#il uses a numeric data-item or numeric literal
$#i uses a numeric or an alphanumeric data-item

 

An example syntax diagram

img1.gif

 

This syntax diagram may be interpreted as follows;

We must start a COMPUTE statement with the keyword COMPUTE.

We must follow the keyword with the name(s) of the numeric data item (or items - note the ellipsis symbol (...)) to be used to receive the result of the expression. The #i suffix at the end of word Result tells us that a numeric identifier/data item must be used.

Since the ellipsis symbol is placed outside the curly brackets we can interpret this to mean that each result field can have its own ROUNDED phase. In other words we could have a COMPUTE statement like -

COMPUTE Result1 ROUNDED, Result2 = ((9*9)+8)/5

where Result1 would be assigned a value of 18 and Result2 would be assigned a value of 17.8.

The square brackets after the Arithmetic Expression indicate that the next items are optional but if used we must choose between the ON SIZE ERROR or NOT ON SIZE ERROR phrases.

Because the END-COMPUTE is contained within the square brackets it must only be used when a SIZE ERROR or NOT SIZE ERROR phrase is used.

COBOL coding rules

Traditionally, COBOL programs were written on coding forms and then punched on to punch cards. Although nowadays most programs are entered directly into a computer, some COBOL formatting conventions remain that derive from its ancient punch-card history.

On coding forms, the first six character positions are reserved for sequence numbers. The seventh character position is reserved for the continuation character, or for an asterisk that denotes a comment line.

The actual program text starts in column 8. The four positions from 8 to 11 are known as Area A, and positions from 12 to 72 are Area B.

Although many COBOL compilers ignore some of these formatting restrictions, most still retain the distinction between Area A and Area B.

When a COBOL compiler recognizes the two areas, all division names, section names, paragraph names, FD entries and 01 level numbers must start in Area A. All other sentences must start in Area B.

In our example programs we use the compiler directive (available with the NetExpress COBOL compiler) - $ SET SOURCEFORMAT"FREE" - to free us from these formatting restrictions.

Ancient COBOL coding form

img2.gif

Name construction

All user-defined names, such as data names, paragraph names, section names condition names and mnemonic names, must adhere to the following rules:

  1. They must contain at least one character, but not more than 30 characters.
  2. They must contain at least one alphabetic character.
  3. They must not begin or end with a hyphen.
  4. They must be constructed from the characters A to Z, the numbers 0 to 9, and the hyphen.
  5. They must not contain spaces.
  6. Names are not case-sensitive: TotalPay is the same as totalpay, Totalpay or TOTALPAY.

img3.gif

 

Divisions
A division is a block of code, usually containing one or more sections, that starts where the division name is encountered and ends with the beginning of the next division or with the end of the program text.


Sections
A section is a block of code usually containing one or more paragraphs. A section begins with the section name and ends where the next section name is encountered or where the program text ends.

Section names are devised by the programmer, or defined by the language. A section name is followed by the word SECTION and a period.
See the two example names below -

SelectUnpaidBills SECTION.
FILE SECTION.

 

Paragraphs
A paragraph is a block of code made up of one or more sentences. A paragraph begins with the paragraph name and ends with the next paragraph or section name or the end of the program text.

A paragraph name is devised by the programmer or defined by the language, and is followed by a period.
See the two example names below -

PrintFinalTotals.
PROGRAM-ID.

 

Sentences and statements
A sentence consists of one or more statements and is terminated by a period.
For example:

MOVE .21 TO VatRate
   MOVE 1235.76 TO ProductCost
   COMPUTE VatAmount = ProductCost * VatRate.


A statement consists of a COBOL verb and an operand or operands.
For example:

SUBTRACT Tax FROM GrossPay GIVING NetPay

 

The Four Divisions

Introduction

At the top of the COBOL hierarchy are the four divisions. These divide the program into distinct structural elements. Although some of the divisions may be omitted, the sequence in which they are specified is fixed, and must follow the order below.

            IDENTIFICATION DIVISION.
            Contains program information

             ENVIRONMENT DIVISION.
            Contains environment information

             DATA DIVISION.
            Contains data descriptions

             PROCEDURE DIVISION.
            Contains the program algorithms

 

The IDENTIFICATION DIVISION

 

The IDENTIFICATION DIVISION supplies information about the program to the programmer and the compiler.

Most entries in the IDENTIFICATION DIVISION are directed at the programmer. The compiler treats them as comments.

The PROGRAM-ID clause is an exception to this rule. Every COBOL program must have a PROGRAM-ID because the name specified after this clause is used by the linker when linking a number of subprograms into one run unit, and by the CALL statement when transferring control to a subprogram.

The IDENTIFICATION DIVISION has the following structure:

IDENTIFICATION DIVISION
PROGRAM-ID. NameOfProgram.
[AUTHOR. YourName.]
other entries here

The keywords - IDENTIFICATION DIVISION - represent the division header, and signal the commencement of the program text.

PROGRAM-ID is a paragraph name that must be specified immediately after the division header.

NameOfProgram is a name devised by the programmer, and must satisfy the rules for user-defined names.

Here's a typical program fragment:

Here's a typical program fragment:

IDENTIFICATION DIVISION.
PROGRAM-ID. SequenceProgram.
AUTHOR. Michael Coughlan.

 

The ENVIRONMENT DIVISION

The ENVIRONMENT DIVISION is used to describe the environment in which the program will run.

The purpose of the ENVIRONMENT DIVISION is to isolate in one place all aspects of the program that are dependant upon a specific computer, device or encoding sequence.

The idea behind this is to make it easy to change the program when it has to run on a different computer or one with different peripheral devices.

In the ENVIRONMENT DIVISION, aliases are assigned to external devices, files or command sequences. Other environment details, such as the collating sequence, the currency symbol and the decimal point symbol may also be defined here.

 

The DATA DIVISION

As the name suggests, the DATA DIVISION provides descriptions of the data-items processed by the program.

The DATA DIVISION has two main sections: the FILE SECTION and the WORKING-STORAGE SECTION. Additional sections, such as the LINKAGE SECTION (used in subprograms) and the REPORT SECTION (used in Report Writer based programs) may also be required.

The FILE SECTION is used to describe most of the data that is sent to, or comes from, the computer's peripherals.

The WORKING-STORAGE SECTION is used to describe the general variables used in the program.


The DATA DIVISION has the following structure and syntax:


Below is a sample program fragment -

IDENTIFICATION DIVISION.
PROGRAM-ID. SequenceProgram.
AUTHOR. Michael Coughlan.

DATA DIVISION.
WORKING-STORAGE SECTION.
01 Num1 PIC 9 VALUE ZEROS.
01 Num2 PIC 9 VALUE ZEROS.
01 Result PIC 99 VALUE ZEROS.

 The PROCEDURE DIVISION

The PROCEDURE DIVISION contains the code used to manipulate the data described in the DATA DIVISION. It is here that the programmer describes his algorithm.

The PROCEDURE DIVISION is hierarchical in structure and consists of sections, paragraphs, sentences and statements.

Only the section is optional. There must be at least one paragraph, sentence and statement in the PROCEDURE DIVISION.

Paragraph and section names in the PROCEDURE DIVISION are chosen by the programmer and must conform to the rules for user-defined names.


Sample Program

IDENTIFICATION DIVISION.
PROGRAM-ID. SequenceProgram.
AUTHOR. Michael Coughlan.                     
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Num1 PIC 9 VALUE ZEROS.
01 Num2 PIC 9 VALUE ZEROS.
01 Result PIC 99 VALUE ZEROS.

PROCEDURE DIVISION.
CalculateResult.
   ACCEPT Num1.
   ACCEPT Num2.
   MULTIPLY Num1 BY Num2 GIVING Result.
   DISPLAY "Result is = ", Result.
   STOP RUN.
                   

 

Some COBOL compilers require that all the divisions be present in a program while others only require the IDENTIFICATION DIVISION and the PROCEDURE DIVISION. For instance the program shown below is perfectly valid when compiled with the Microfocus NetExpress compiler.

Minimum COBOL program

IDENTIFICATION DIVISION.
PROGRAM-ID. SmallestProgram.
PROCEDURE DIVISION.
DisplayGreeting.
   DISPLAY "Hello world".
   STOP RUN.
                   

 

 

 Declaring Data in COBOL

 U of Limerick
hosts
Michael Coughlan's
"All Things COBOL site"
    A Link from that site:

COBOL Programming Course

Sub link
Declaring Data in COBOL

 

   Objectives

By the end of this unit you should -

  1. Know how to use and create literals, variables and Figurative Constants.
  2. Understand how to declare numeric, alphabetic and alphanumeric data-items.
  3. Be able to create a record structure by assigning the appropriate level numbers to its data-items.
  4. Understand the difference between group and an elementary data-items.
  5. Be able to assign an initial value to a variable.

Categories of COBOL data

There are three categories of data item used in COBOL programs:

        Variables.
        Literals.
        Figurative Constants.

Variables

A data-name or identifier is the name used to identify the area of memory reserved for a variable. A variable is a named location in memory into which a program can put data, and from which it can retrieve data.

Every variable used in a COBOL program must be described in the DATA DIVISION.

In addition to the data-name, a variable declaration also defines the type of data to be stored in the variable. This is known as the variable's data type.

Variable Data types

Some languages like Modula-2,Pascal or Ada are described as being strongly typed. In these languages there are a large number of different data types and the distinction between them is rigorously enforced by the compiler. For instance, the compiler will reject a statement that attempts to assign character value to an integer data item.

In COBOL, there are really only three data types -

  • numeric
  • alphanumeric (text/string)
  • alphabetic

The distinction between these data types is a little blurred and only weakly enforced by the compiler. For instance, it is perfectly 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, since COBOL programs crash (halt unexpectedly) if they attempt to do computations on items that contain non-numeric data, it is up to the programmer to make sure this never happens.

COBOL programmers must make sure that non-numeric data is never assigned to numeric items intended for use in calculations. Programmers who use strongly typed languages don't need this level of discipline because the compiler ensures that a variable of a particular types can only be assigned appropriate values.

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 constant data-items.

There are two types of literal -

  • String/Alphanumeric Literals
  • Numeric Literals

String Literals

String/Alphanumeric literals are enclosed in quotes and consist of alphanumeric characters.

For example: "Michael Ryan", "-123", "123.45"

Numeric Literals

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

For example: 123, 123.45, -256, +2987

 

Figurative Constants

Unlike most other programming languages COBOL does not provide a mechanism for creating user-defined constants but it does provide a set of special constants called Figurative Constants.

A Figurative Constant may be used wherever it is legal to use a literal but unlike literals, when a Figurative Constant is assigned to a data-item it fills the whole item overwriting everything in it.

The Figurative Constants are:

 

SPACE or SPACES Acts like one or more spaces
ZERO or ZEROS or ZEROES Acts like one or more zeros
QUOTE or QUOTES Used instead of a quotation mark
HIGH-VALUE or HIGH-VALUES Uses the maximum value possible
LOW-VALUE or LOW-VALUES Uses the minimum value possible
ALL literal Allows a ordinary literal to act as Figurative Constant

Figurative Constant Notes

  • When the ALL Figurative Constant is used, it must be followed by a one character literal. The designated literal then acts like the standard Figurative Constants.
  • ZERO, ZEROS and ZEROES are synonyms, not separate Figurative Constants. The same applies to SPACE and SPACES, QUOTE and QUOTES, HIGH-VALUE and HIGH-VALUES, LOW-VALUES and LOW-VALUES.

Declaring Data-Items in COBOL

Because COBOL is not a typed language like Modula-2 or C it employs a different mechanism for describing the characteristics of the data-items in a program.

Rather than using types, as these languages do, COBOL uses a kind of "declaration by example" strategy. The programmer provides the system with an example, or template, or PICture of the storage required for the data-item.

In COBOL, a variable declaration consists of a line in the DATA DIVISION that contains the following items:

  • A level number.
  • A data-name or identifier.
  • A Picture clause.

 

COBOL picture clauses

To create the required 'picture' the programmer uses a set of symbols. The most common symbols used in standard picture clauses are:

9

The digit nine is used to indicate the occurrence of a digit at the corresponding position in the picture.

X

The character X is used to indicate the occurrence of any character from the character set at the corresponding position in the picture.

A

The character A is used to indicate the occurrence of any alphabetic character (A to Z plus blank) at the corresponding position in the picture.

V

The character V is used to indicate the position of the decimal point in a numeric value. It is often referred to as the "assumed decimal point". It is called that because, although the actual decimal point is not stored, values are treated as if they had a decimal point in that position.

S

The character S indicates the presence of a sign and can only appear at the beginning of a picture.

 Picture clause notes

Although the word PICTURE can be used when defining a picture clause it is normal to use the abbreviation PIC.

Recurring symbols may be specified by using a 'repeat' factor inside brackets. For instance:

PIC 9(6)       is equivalent to PICTURE 999999
PIC 9(6)V99    is equivalent to PIC 999999V99
PICTURE X(10)  is equivalent to PIC XXXXXXXXXX
PIC S9(4)V9(4) is equivalent to PIC S9999V9999
PIC 9(18)      is equivalent to PIC 999999999999999999 

Numeric values can have a maximum of 18 (eighteen) digits.

The limit on string values is usually system dependent.

Group and Elementary data-items

Introduction

Although we stated above that each variable declaration consists of a level number, an identifying name and a picture clause, that definition only applies to elementary data-items. Group items are defined using only a level-number and an identifying name; no picture clause is required or allowed.

Which begs the question - what is a group item and what is an elementary item?

Elementary items

An "elementary item" is the name we use in COBOL to describe a data-item that has not been further subdivided. Other languages might describe these as ordinary variables.

Elementary items must have a picture clause because they actually reserve the storage required for the item. The amount of storage reserved is specified by the item's picture clause.

An elementary item declaration consists of;

  • a level number
  • a data name
  • a picture clause

A starting value may be assigned to a variable by means of an extension to the PICTURE clause called the VALUE clause.

Some examples:

01 GrossPay       PIC 9(5)V99 VALUE ZEROS.

01 NetPay         PIC 9(5)V99 VALUE ZEROS.

01 CustomerName   PIC X(20) VALUE SPACES.

01 CustDiscount   PIC V99 VALUE .25.
 

Group items

Sometimes when we are manipulating data it is convenient to treat a collection of elementary items as a single group. For instance, we may want to group the data-items YearofBirth, MonthofBirth, DayOfBirth under the group name - DateOfBirth. If we are recording information about students we may want to subdivide StudentName into FirstName, MiddleInitial and Surname. And we may want to use both these group items and the elementary items StudentId and CourseCode in a student record description.

We can create groups like these in COBOL using group items. A "group item" is the term used in COBOL to describe a data-item - like DateOfBirth or StudentName - that has been further subdivided. In other languages group items might be described as "structures".

A group item consists of subordinate items. The items subordinate to 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.

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. Where a group item is the highest item in a data hierarchy it is referred to as a "record" and uses the level number 01.

Group items are declared using a level number and a data name only. A group item cannot have a picture clause because it does not actually reserve any storage. It is merely a name given to a collection of (ultimately) elementary items which do reserve the storage.

Therefore, the size of a group item is the sum of the sizes of its subordinate elementary items.

The type of a group item is always assumed to be PIC X because a group item may have several different data items and types subordinate to it and an X picture is the only one which could support such collections.

 

Level Numbers

 

Level numbers are used to express data hierarchy. The higher the level number, the lower the item is in the hierarchy. At the lowest level the data is completely atomic.

What is important in a structure defined with level numbers is the relationship of the level numbers to one another, not the actual level numbers used. For instance, the record descriptions shown below are equivalent.

 

Record-A
01 StudentDetails.
   02 StudentId        PIC 9(7). 
   02 StudentName. 
      03 FirstName     PIC X(10).
      03 MiddleInitial PIC X. 
      03 Surname       PIC X(15).
   02 DateOfBirth.
      03 DayOfBirth    PIC 99.
      03 MonthOfBirth  PIC 99.
      03 YearOfBirth   PIC 9(4).
   02 CourseCode       PIC X(4).

 

Record-B
01 StudentDetails.
   05 StudentId        PIC 9(7). 
   05 StudentName. 
      07 FirstName     PIC X(10).
      07 MiddleInitial PIC X. 
      07 Surname       PIC X(15).
   05 DateOfBirth.
      07 DayOfBirth    PIC 99.
      07 MonthOfBirth  PIC 99.
      07 YearOfBirth   PIC 9(4).
   05 CourseCode       PIC X(4).

 Some observations on Record-A

It is useful to examine Record-A above and to answer the following questions:

Q1. What is the size (in characters) of Record-A?
Q2. What is the size of the data-item StudentName?
Q3. What is the size of DateOfBirth?
Q4. What is the data type of DateOfBirth? Is it numeric, alphabetic or alphanumeric.
 

A1. The size of Record-A is the sum of the sizes of all the elementary items subordinate to it (7+10+1+15+2+2+4+4 = 45 characters).
A2. The size of StudentName is the sum of the sizes of FirstName, MiddleInitial and Surname. So StudentName is 26 characters in size (10+1+15).
A3. DateOfBirth is 8 characters in size (2+2+4).
A4. The data type of DateOfBirth is alphanumeric (i.e. PIC X) even though all its subordinate items are numeric because the type of a group item is always alphanumeric.

Level number notes

The level numbers 01 through 49 are general level numbers but there are also special level numbers such as 66, 77 and 88.

  • Level 77's can only be used to define individual elementary items. The use of 77's is banned in some shops who take the view that instead of declaring large numbers of indistinguishable 77's it is better to collect the individual items into groups.
  • Level 88's are used to define Condition Names.
  • Level 66's (RENAMES clause) are used to apply a new name to an identifier or group of identifiers. It is not generally used in modern COBOL programs.

Building a record structure

In the animation below we show how level numbers can be used to define a record structure as hierarchy of data-items.

 

\

 Basic Procedure Division Commands

 U of Limerick
hosts
Michael Coughlan's
"All Things COBOL site"
    A Link from that site:

COBOL Programming Course

Sub link

Basic Procedure Division Commands

 Basic User Input and Output

Introduction

In COBOL, the ACCEPT and DISPLAY verbs are used to read from the keyboard and write to the screen. Input and output using these commands is somewhat primitive because they were originally designed to be used in a batch programming environment to communicate with the computer operator.

In recent years many vendors have augmented the ACCEPT and DISPLAY syntax to facilitate the creation of on-line systems by allowing such things as: cursor positioning, character attribute control and auto-validation of input.

In this tutorial we will examine only the standard ACCEPT and DISPLAY syntax.

 

The DISPLAY verb

The DISPLAY verb is used to send output to the computer screen or to a peripheral device.

As you can see from the ellipses (...) in the metalanguage above a single DISPLAY can be used to display several data-items or literals or any combination of these.

DISPLAY notes
After the items in the display list have been sent to the screen, the DISPLAY automatically moves the screen cursor to the next line unless a WITH NO ADVANCING clause is present.

Mnemonic-Names are used to make programs more readable. A Mnemonic-Name is a name devised by the programmer to represent some peripheral device (such as a serial port) or control code. The name is connected to the actual device or code by entries in the ENVIRONMENT DIVISION.

When a Mnemonic-Name is used with the DISPLAY it represents an output device (serial port, parallel port etc).

If a Mnemonic-Name is used output is sent to the device specified; otherwise, output is sent to the computer screen.

DISPLAY examples

DISPLAY "My name is " ProgrammerName.
DISPLAY "The vat rate is " VatRate. 
DISPLAY PrinterSetupCodes UPON PrinterPort1.
 
 

The ACCEPT verb

The ACCEPT verb is used to get data from the keyboard, a peripheral device, or certain system variables.

ACCEPT notes
When the first format is used, the ACCEPT inserts the data typed at the keyboard (or coming from the peripheral device), into the receiving data-item.

When the second format is used, the ACCEPT inserts the data obtained from one of the system variables, into the receiving data-item.

 

Using the ACCEPT to get the system date and time

The second format of the ACCEPT allows the programmer to access the system date and time (i.e. the date and time held in the computer's internal clock). The system variables provided are -

  • Date
  • Day of the year
  • Day of the week
  • Time

The declarations and comments below show the format required for data-items receiving each of the system variables.

01 CurrentDate         PIC 9(6).
* CurrentDate is the date in YYMMDD format


01 DayOfYear           PIC 9(5).
* DayOfYear is current day in YYDDD format


01 Day0fWeek           PIC 9.
* DAY-OF-WEEK is a single digit where 1=Monday


01 CurrentTime         PIC 9(8).
* CurrentTime is the time in HHMMSSss format where s = S/100
 

 

New formats for the ACCEPT

 

                

 

The problem with ACCEPT ..FROM DATE and ACCEPT..FROM DAY is that since they hold only the year in only two digits, they are subject to the millennium bug. To resolve this problem, these two formats of now take additional (optional) formatting instructions to allow the programmer to specify that the date is to be supplied with a 4 digit year.

 

The syntax for these new formatting instructions is:

 

    ACCEPT DATE [YYYYMMDD]

    ACCEPT DAY [YYYYDDD]

 

When the new formatting instructions are used, the receiving fields must be defined as;

 

    01 Y2KDate PIC 9(8).

    * Y2KDate is the date in YYYYMMDD format

 

    01 Y2KDayOfYear PIC 9(7).

    * Y2KDayOfYear is current day in YYYYDDD format

 

 

ACCEPT and DISPLAY example program

This example program uses the ACCEPT and DISPLAY to get a student record from the user and display some of its fields. It also demonstrates how the ACCEPT can be used to get the system date and time.

 

      $ SET SOURCEFORMAT"FREE"
IDENTIFICATION DIVISION.
PROGRAM-ID.  AcceptAndDisplay.
AUTHOR.  Michael Coughlan.
* Uses the ACCEPT and DISPLAY verbs to accept a student record 
* from the user and display some of the fields.  Also shows how
* the ACCEPT may be used to get the system date and time.

* The YYYYMMDD in "ACCEPT  CurrentDate FROM DATE YYYYMMDD." 
* is a format command that ensures that the date contains a 
* 4 digit year.  If not used, the year supplied by the system
* will only contain two digits which may cause a problem 
* in the year 2000.

DATA DIVISION.
WORKING-STORAGE SECTION.
01 StudentDetails.
   02  StudentId       PIC 9(7).
   02  StudentName.
       03 Surname      PIC X(8).
       03 Initials     PIC XX.
   02  CourseCode      PIC X(4).
   02  Gender          PIC X.

* YYMMDD
01 CurrentDate.
   02  CurrentYear     PIC 9(4).
   02  CurrentMonth    PIC 99.
   02  CurrentDay      PIC 99.

* YYDDD
01 DayOfYear.
   02  FILLER          PIC 9(4).
   02  YearDay         PIC 9(3).


* HHMMSSss   s = S/100
01 CurrentTime.
   02  CurrentHour     PIC 99.
   02  CurrentMinute   PIC 99.
   02  FILLER          PIC 9(4).


PROCEDURE DIVISION.
Begin.
   DISPLAY "Enter student details using template below".
   DISPLAY "Enter - ID,Surname,Initials,CourseCode,Gender"
   DISPLAY "SSSSSSSNNNNNNNNIICCCCG".
   ACCEPT  StudentDetails.
   ACCEPT  CurrentDate FROM DATE YYYYMMDD.
   ACCEPT  DayOfYear FROM DAY YYYYDDD.
   ACCEPT  CurrentTime FROM TIME.
   DISPLAY "Name is ", Initials SPACE Surname.
   DISPLAY "Date is " CurrentDay SPACE CurrentMonth 
           SPACE CurrentYear.
   DISPLAY "Today is day " YearDay " of the year".
   DISPLAY "The time is " CurrentHour ":" CurrentMinute.
   STOP RUN.
                                                   

 

 

Results of running ACCEPT.CBL

Enter student details using template below
Enter - ID,Surname,Initials,CourseCode,Gender
SSSSSSSNNNNNNNNIICCCCG
9923453Power   NSLM51F
Name is NS Power
Date is 01 03 1999
Today is day 060 of the year
The time is 14:41

 

Assignment using the MOVE verb

Introduction

In �strongly typed� languages like Modula-2, Pascal or ADA the assignment operation is simple because assignment is only allowed between data 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 basically only three data types;

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

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

In COBOL, assignment is achieved using the MOVE verb.

The MOVE verb

MOVE Source$#il TO Destination$#i ...

As we can see from the syntax metalanguage above, the MOVE copies data from the source identifier or literal to one or more destination identifiers.

Although this sounds simple, the actual operation of the MOVE is somewhat more complicated and is governed by a number of rules.

MOVE rules
In most other programming languages, data is assigned from the source item on the right to the destination item on the left (e.g. Qty = 10;) but in COBOL the MOVE assigns data from left to right. The source item is on the left of the word TO and the receiving item(s) is on the right.

The source and destination identifiers can be group or elementary data-items.

When data is moved into an item, the contents of the item are completely replaced.

If the number of characters in the source data-item is less than the number in the destination item, the rest of the destination item is filled with zeros or spaces.

If the source data-item is larger than the destination item, the characters that cannot fit into the destination item will be 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 items, 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 and will be rejected by the compiler. The valid and invalid MOVE combinations are shown in the diagram below:

 

MOVE examples

Arithmetic in COBOL

Introduction

Most procedural programming languages perform computations by assigning the result of an arithmetic expression or a function to a variable. In COBOL the COMPUTE verb is used to evaluate arithmetic expressions, but there are also specific commands for adding, subtracting, multiplying and dividing.

Data Movement

In a MOVE operation data is moved from a source item on the left to the destination item(s) on the right. Data movement is from left to right. The same direction of data movement can be observed in the COBOL arithmetic verbs.

All the arithmetic verbs, except the COMPUTE, assign the result of the calculation to the rightmost data-items.

General Rules

        

        

 

All the arithmetic verbs move the result of a calculation into a receiving data-item according to the rules for a numeric move; that is, with alignment along the assumed decimal point and with zero-filling or truncation as necessary.

 

All arithmetic verbs must use numeric literals or numeric data-items (PIC 9) that contain numeric data. There is one exception. Identifiers that appear to the right of the word GIVING may refer to numeric data-items that contain editing symbols.

 

When the GIVING phrase is used, the data-item following the word GIVING is the receiving field of the calculation but it is not one of the statement operands (does not contribute to the result). The original values of all the items before the word GIVING are left intact.

 

If the GIVING phrase is not used, the data-item(s) after the word TO, FROM, BY or INTO both contribute to the result and are receiving field for it.

 

The maximum size of each operand is 18 digits.

The ROUNDED option

All the arithmetic verbs allow the ROUNDED phrase.

The ROUNDED phrase takes effect when, after decimal point alignment, the result calculated must be truncated on the right hand side. The option adds 1 to the receiving item when the leftmost truncated digit has an absolute value of 5 or greater.

ROUNDED examples
Receiving Field
Actual Result
Truncated Result
Rounded Result

PIC 9(3)V9

123.25 123.2 123.3
PIC 9(3)V9 123.247 123.2 123.2
PIC 9(3) 123.25 123 123

 

 ON SIZE ERROR

When a computation is performed it is possible for the result to be too large or too small to be contained in the receiving field. When this occurs, there will be truncation of the result. The ON SIZE ERROR phrase detects this condition.

ON SIZE ERROR notes
All the arithmetic verbs allow the ON SIZE ERROR phrase.

A size error condition exists when, after decimal point alignment, the result is truncated on either the left or the right hand side.

If an arithmetic statement has a ROUNDED phrase then a size error only occurs if there is truncation on the left-hand side (most significant digits) because if we specify the ROUNDED option we indicate that we know there will be truncation on the right and are specifying rounding to deal with it.

Division by 0 always causes a SIZE ERROR.

ON SIZE ERROR examples

 

Receiving Field
Actual Result
Truncated Result
Size Error?
PIC 9(3)V9   245.96
   245.9
YES
PIC 9(3)V9
  3245.9
   245.9
YES
PIC 9(3)
  324
   324
NO
PIC 9(3)
  5324
   324
YES
PIC 9(3)V9 not Rounded
  523.35
   523.3
YES
PIC 9(3)V9 Rounded   523.35    523.4
NO
PIC 9(3)V9 Rounded
  3523.35
   523.4
YES

 ADD verb

If the GIVING phrase is used, everything before the word GIVING is added together and the combined result is moved into each of the Result#i items.

If the GIVING phrase is not used, everything before the word TO is added together and the combined result is then added to each of the ValueResult#i items in turn.

SUBTRACT verb

If the GIVING phrase is used, everything before the word FROM is added together and the combined result is subtracted from the Value#il item after the word FROM and the result is moved into each of the Result#i items.

If the GIVING phrase is not used everything before the word FROM is added together and the combined result is then subtracted from each of the ValueResult#i items after the word FROM in turn.

 

MULTIPLY verb

 

If the GIVING phrase is used, then the item to the left of the word BY is multiplied by the Value#i item to the right of the word BY and the result is moved into each of the Result#i items.

If the GIVING phrase is not used, then the Value#il to the left of the word BY is multiplied by each of the ValueResult#i items. The result of each calculation is placed in the ValueResult#i involved in the calculation.

 

DIVIDE verb

The Divide has two main formats. One produces a remainder and the other does not.

Format1

img4.gif

 

In the GIVING phrase is used, the Value#il to the left of BY or INTO is divided by or into the Value#il to the right of BY or INTO and the result of the calculation in moved into each of the Result#i items in turn.

If the GIVING phrase is not used, the item to the left of the word INTO is divided into each of the ValueResult#i items in turn. The result of each calculation is placed in the ValueResult#i involved in the calculation.

Format2

img5.gif

 

COMPUTE verb

img6.gif

The COMPUTE assigns the result of an arithmetic expression to a data-item. The arithmetic expression is evaluated according to the normal arithmetic rules. That is, the expression is normally evaluated from left to right but bracketing and the precedence rules shown below can change the order of evaluation.

Precedence

Symbol

Meaning

1.

**

Power

2.

*

multiply

/

divide

3.

+

add

-

subtract

Note that unlike some other programming languages COBOL provides the ** expression symbol to represent raising to a power.