You are on page 1of 26

COBOL PROGRAMMING LAB MANUAL III SEMESTER M.C.

PROGRAM LIST
1. Beginners Programs - Simple programs using ACCEPT, DISPLAY and some arithmetic verbs. Discount Calculation 2. Selection and Iteration - Selection (IF, EVALUATE) and Iteration (PERFORM) example programs. Count of Students based on their Gender. 3. Sequential Files - Programs that demonstrate how to process sequential files. Employee Pay Report Calculation. 4. Sorting and Merging - Examples that use INPUT Procedures and the SORT and MERGE verbs Students Marks Processing. 5. COBOL Tables - Example programs using tables. Income Tax Calculation. 6. CALLing sub-programs - Example programs that Demonstrate contained, and external, sub-programs. Purchase Requirement Report Preparation. 7. The COBOL Report Writer - Example programs using the COBOL Report Writer. Report on Yahoo.com Web Site. 8. Master and Transaction Files - Example programs that show how to process Master and Transaction files. Stock Maintenance. 9. String handling - Example programs that show how to use Reference Modification, INSPECT and UNSTRING. Cable Operator Schemes. 10. Simple Project Using all the commands of COBOL. Banking Simulation System.

Aims To provide a brief introduction to the programming language COBOL. To provide a context in which its uses might be understood. To provide an introduction to the major structures present in a COBOL program.

Objectives By the end of this lab you should 1. 2. 3. 4. 5. 6. 7. Know what the acronym COBOL stands for. Be aware of the significance of COBOL in the marketplace. Understand some of the reasons for COBOL's success. Be able to understand COBOL Meta language syntax diagrams. Be aware of the COBOL coding rules Understand the structure of COBOL programs Understand the purpose of the IDENTIFICATION, ENVIRONMENT, DATA and PROCEDURE divisions.

Introduction COBOL is a high-level programming language first developed by the CODASYL Committee (Conference on Data Systems Languages) in 1960. Since then, responsibility for developing new COBOL standards has been assumed by the American National Standards Institute (ANSI). Three ANSI standards for COBOL have been produced: in 1968, 1974 and 1985. A new COBOL standard introducing object-oriented programming to COBOL, is due within the next few years. The word COBOL is an acronym that stands for COmmon Business Oriented Language. As the the expanded acronym indicates, COBOL is designed for developing business, typically file-oriented, applications. It is not designed for writing systems programs. For instance you would not develop an operating system or a compiler using COBOL.

Writing Programs using COBOL COBOL coding rules


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.

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. 2. 3. 4. They must contain at least one character, but not more than 30 characters. They must contain at least one alphabetic character. They must not begin or end with a hyphen. 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.

The structure of COBOL programs


COBOL programs are hierarchical in structure. Each element of the hierarchy consists of one or more subordinate elements. The hierarchy consists of Divisions, Sections, Paragraphs, Sentences and Statements. A Division may contain one or more Sections, a Section one or more Paragraphs, a Paragraph one or more Sentences and a Sentence one or more Statements. We can represent the COBOL hierarchy using the COBOL meta language as follows;

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 Eg.1 SelectUnpaidBills SECTION. Eg. 2 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

DIVISIONS IN COBOL
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:
IDENTIFICATION DIVISION. PROGRAM-ID. SequenceProgram. AUTHOR. xxxx.

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 WORKINGSTORAGE 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. xxxxx. 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.

How to execute a COBOL Program?


Step 1 : Edit the COBOL program using DOSs EDIT / Windows Notepad and save it with .COB extension. Step 2: Compile it with the following command at command prompt: C:\COBOL> COBOL filename.cob;

Step 3: Now to execute the COBOL program use the following command. C:\COBOL> RUNCOB filename;

The O/P will look as below:

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

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 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 HIGHVALUES, LOW-VALUES and LOW-VALUES.

Variable Declaration 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 X A V The digit nine is used to indicate the occurrence of a digit at the corresponding position in the picture. The character X is used to indicate the occurrence of any character from the character set at the corresponding position in the picture. 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. 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. The character S indicates the presence of a sign and can only appear at the beginning of a picture.

Recurring symbols may be specified by using a 'repeat' factor inside brackets. For instance:
PIC 9(6) PIC 9(6)V99 PICTURE X(10) PIC S9(4)V9(4) is is is is equivalent equivalent equivalent equivalent to to to to PICTURE 999999 PIC 999999V99 PIC XXXXXXXXXX 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 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 01 NetPay 01 CustomerName 01 CustDiscount PIC 9(5)V99 VALUE ZEROS. PIC 9(5)V99 VALUE ZEROS. PIC X(20) VALUE SPACES. 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 02 StudentName. 03 FirstName 03 MiddleInitial 03 Surname 02 DateOfBirth. 03 DayOfBirth 03 MonthOfBirth 03 YearOfBirth 02 CourseCode PIC 9(7). PIC X(10). PIC X. PIC X(15). PIC 99. PIC 99. PIC 9(4). PIC X(4).

Record-B

01 StudentDetails. 05 StudentId 05 StudentName. 07 FirstName 07 MiddleInitial 07 Surname 05 DateOfBirth. 07 DayOfBirth 07 MonthOfBirth 07 YearOfBirth 05 CourseCode

PIC 9(7). PIC X(10). PIC X. PIC X(15). PIC 99. PIC 99. PIC 9(4). PIC X(4).

Some observations on Record-A It is useful to examine Record-A above and to answer the following questions: Q1. Q2. Q3. Q4. What is the size (in characters) of Record-A? What is the size of the data-item StudentName? What is the size of DateOfBirth? 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.

Basic User Input and Output 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. The DISPLAY verb

In the COBOL syntax diagrams ( the COBOL metalanguage) upper case words are keywords. If underlined, they are mandatory. { } brackets mean that one of the options must be selected [ ] brackets mean that the item is optional ellipses (...) mean that the item may be repeated at the programmers discretion.
The symbols used in the syntax diagram identifiers have the following significance:$ signifies a string item, # is numeric item, i indicates that the item can be a variable identifier l indicates that the item can be a literal.

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.
IDENTIFICATION DIVISION. PROGRAM-ID. AcceptAndDisplay. AUTHOR. 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 02 CurrentMonth 02 CurrentDay * YYDDD 01 DayOfYear.

PIC 9(4). PIC 99. PIC 99.

02 02

FILLER YearDay

PIC 9(4). 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

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


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. 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

Arithmetic in COBOL 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. 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
ROUNDED

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 PIC 9(3)V9 245.96 245.9 PIC 9(3)V9 3245.9 245.9 PIC 9(3) 324 324 PIC 9(3) 5324 324 PIC 9(3)V9 not Rounded 523.35 PIC 9(3)V9 Rounded 523.35 523.4 PIC 9(3)V9 Rounded 3523.35 523.4

Truncated Result
YES YES NO YES

Size Error?

523.3
NO YES

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

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

In this format the Val#il to the left of BY or INTO is divided by or into the Val#il to the right of BY or INTO. The quotient part of the computation is assigned to Quot#i and the remainder is assigned to Rem#i. COMPUTE verb

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 1. 2. Symbol ** * / 3. + Meaning Power multiply divide add subtract

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

You might also like