You are on page 1of 98

COBOL Programming Tutorial

COBOL QUICK START / REFERENCE

CHAPTER-1 CHAPTER-2 CHAPTER-3 CHAPTER-5 CHAPTER-6 CHAPTER-7 CHAPTER-8 CHAPTER-9

Cobol History Cobol Program Structure Cobol Sample Program Cobol Cobol Cobol Cobol Identification Division Environment Division Data Division Procedure Division

Cobol Data Items Cobol Editing Characters Cobol Elementary Group Data Items COBOL COBOL Cobol Cobol Cobol Cobol Cobol COBOL COBOL COBOL COBOL COBOL COBOL COBOL verbs Initialize Verb Move Verb Add Verb Subtract Verb Multiply Verb Divide Verb Conditional Expressions IF THEN ELSE GO TO PERFORM STRING UNSTRING DATE FUNCTIONS

CHAPTER-10

CHAPTER-11 CHAPTER-12 CHAPTER-13 CHAPTER-14 CHAPTER-15 CHAPTER-16 CHAPTER-17 CHAPTER-18 CHAPTER-19 CHAPTER-20 CHAPTER-21 CHAPTER-22 CHAPTER-23 CHAPTER-24 CHAPTER-25 CHAPTER-26

COBOL REDEFINES COBOL INSPECT COBOL EVALUATE COBOL OCCURS COBOL SEARCH COBOL SEARCH ALL COBOL COPY COBOL INITIALIZE COBOL COMP, COMP-1,COMP-2,COMP-3 COBOL FILE HANDLING part-1 COBOL FILE HANDLING part-2 COBOL INDEXED FILES COBOL RELATIVE FILES

COBOL COMPILERS

COBOL HISTORY COBOL (Common Business Oriented Language) was one of the earliest highlevel programming languages. COBOL was developed in 1959 by the Conference on Data Systems Languages (CODASYL). This committee was a formed by a joint effort of industry, major universities, and the United States Government. Government printing office, has printed the COBOL specifications as Cobol60 in 1960. COBOL was developed within a six month period, and yet is still in use over 40 years later. Since 1960, the American National Standards Institute (ANSI) was responsible for developing new COBOL standards.

Legacy COBOL programs are in use globally in governmental and military agencies, in commercial enterprises. 95% financial and insurance business is on COBOL in US In 1997, the Gartner Group reported that 80% of the world's business ran on COBOL with over 200 billion lines of code in existence and with an estimated 5 billion lines of new code annually.

COBOL Program structure COBOL compiler accepts the source code in a standard format. There are 80 character positions on each line of source code.

Sequence Number number

-> (Optional) use these positions to give sequence to the lines of source code. Use * for commenting the line. this position are Other values can be used

Indicator -> in

slash(/) and hyphen(-). ( Position 8 to

Area A 72 )

&

Area B

->

Contains COBOL source code.

Identification -> positions.

COBOL compiler will ignore the data in these

There are four Divisions in every COBOL programs. IDENTIFICATION DIVISION This division contains the information to identify the program. There are seven paragraph headers in this division. PROGRAM-ID is mandatory, rest all headers are optional. ENVIRONMENT DIVISION Environment Division describe the physical characteristics of input-ouput data sources used by the program. The Environment Division consists of two sections of which both are optional. (Configuration Section & Input-Output Section ) DATA DIVISION All data items used in the program must be defined in Data Division. There are 3 important sections in this divisions. FILE SECTION, WORKING-STORAGE

SECTION & LINKAGE SECTION. PROCEDURE DIVISION This is the place where , programmer needs to implement the program logic. Sample Cobol Program on Mainframe Screen This program sum up the values of WS-B & WS-C data-items and store the result in WS-A data-item and display the all data item values to the spool.

COBOL compiler accepts the source code in a standard format. There are 80 character positions on each line of source code.

Sequence Number number

-> (Optional) use these positions to give sequence to the lines of source code. Use * for commenting the line. this position are Other values can be used

Indicator -> in

slash(/) and hyphen(-). ( Position 8 to

Area A 72 )

&

Area B

->

Contains COBOL source code.

Identification -> positions.

COBOL compiler will ignore the data in these

There are four Divisions in every COBOL programs. IDENTIFICATION DIVISION This division contains the information to identify the program. There are seven paragraph headers in this division. PROGRAM-ID is mandatory, rest all headers are optional. ENVIRONMENT DIVISION Environment Division describe the physical characteristics of input-ouput data sources used by the program. The Environment Division consists of two sections of which both are optional. (Configuration Section & Input-Output Section ) DATA DIVISION

All data items used in the program must be defined in Data Division. There are 3 important sections in this divisions. FILE SECTION, WORKING-STORAGE SECTION & LINKAGE SECTION. PROCEDURE DIVISION This is the place where , programmer needs to implement the program logic. COBOL Identification Division

IDENTIFICATION DIVISION Syntax of IDENTIFICATION DIVISION.

First two lines are required for all COBOL programs. Rest all paragraphs are optional. PROGRAM-ID. <-- Need to provide the program name here Ex. PROGRAM-ID. COBOL1. COBOL Environment Division

ENVIRONMENT DIVISION This division contains two optional SECTIONS. 1. 2. CONFIGURATION SECTION. Specifies the characteristics of your computer system. INPUT-OUTPUT SECTION. Relates file names used in the program to the external file names.

CONFIGURATION SECTION Describe the computer. We are not providing more info on this SECTION as many shops dont use this SECTION.

INPUT-OUTPUT SECTION

In COBOL programs, we can process either sequential files OR VSAM files. Use the FILE-CONTROL paragraph to describe about your program files, associate them with external files where they physically reside. Specify the information to efficiently transfer the data between program and files.

INPUTFL1 in SELECT statement is called physical file. This is the way how program know the name of the actual file to be used. Run JCL ( JCL which executes the program) contains the actual file name to be used. To relate that file with the file in the program, physical file name will be used. INPUTFILE in SELECT is called logical file name. Program uses this name while accessing the file. COBOL DATA DIVISION

DATA DIVISION

DATA DIVISION contains 3 important sections. (1) FILE SECTION (2) WORKING-STORAGE SECTION (3) LINKAGE-SECTION (1) FILE SECTION For Every file used in the program, we should have a entry in this section. Define the structure of the record of each file. We will explain about this section more in COBOL-FILES chapter. Below picture gives us the relation between FILE SECTION , FILE-CONTROL/INPUT-SECTION SECTION & JCL file entries.

(2) WORKING-STORAGE SECTION All the data items used in the program should define in WORKING STORAGE SECTION ( If those fields not belong to FILE SECTION or LINKAGE SECTION )

(3) LINKAGE SECTION When program designed to receive data from runJCL or calling programs, appropriate data items need to be defined in this section. Thru the data items defined in this section, program will get data from other programs/jobs. Below picture shows how data passed to LINKAGE SECTION data items from other program.

Data in WS-NAME data-item in MAINPROG program will be passed to LK-NAME of LINKAGE SECTION in COBOL1 program. COBOL PROCEDURE DIVISION

PROCEDURE DIVISION This division contains the actual program logic. Program logic can be divided into sections and paragraphs. One Section contains One or more paragraphs. One paragraph contains one or more number of sentences. A sentence is a series of one or more COBOL statements ending with a period. A Satement starts with COBOL verb. Example MOVE A TO B COMPUTE C = B + D.

In above example sentence starting with COBOL verb MOVE and it also contains another verb COMPUTE. This sentence ended by a period. This sentence contains two statements. One is MOVE A TO B, Second Statement is COMPUTE C = B + D. Below example shows the syntax of PROCEDURE DIVISION. PROCEDURE DIVISION. ... < user-defined-section-name SECTION> < user-defined-para-name>. ... ]....

....

Without section, we can code paragraph. In most programs, the need of SECTION wont arise. Section & Paragraph Names are userdefined names. Starts in Area A. Ends with a period. In case of section name, userdefine name followed with SECTION word as showed in above example. Paragraph body ends when another para name or section name apears or end of the procedure division. Example 100-FIRST-OPEN-PARA. ... ... 100-FIRST-LOGIC-PARA. ... ... 100-FIRST-CLOSE-PARA. ... ... COBOL DATA ITEMS DATA ITEMS

Any high level programming language have variable names for each data point used in the program. In COBOL, data represented using dataitems (variables). Now let us discuss about how we can declare the dataitems (variables) in COBOL.

Let us learn what is the meaning of 999 in above example. 9 represents numeric data, three occurrence of 9 represents size of dataitem. 9(3) equals to 999. It can store 3 numeric digits of data. In Next Page we will see different types of code characters available in COBOL and their meaning.

Initialization of data items in working-storage section happens using VALUE clause. VALUE clause need to code after picture clause as shown below.

EDITING CHARACTERS

Editing characters for Integer/Numeric Data Edit characters are used to edit the numeric data before printing in the reports. For example, if you want to display the amount along with $ sign, we can do that using these editing character. We can suppress the leading zeros in numeric data before printing. Let us see more details in the next page.

Editing characters for Integer/Numeric Data

ELEMENTARY GROUP DATA ITEMS

ELEMENTARY GROUP DATA ITEMS An elementary data item is a data item which does not have any subordinate items and it has PICTURE clause. A data item which has subordinate items is called Group Item. Group Item are defined using level numbers ( 01 to 49 ). Below picture explain, difference between elementary item and group item.

Elementary data items can be defined with any of the level numbers 49, 77.

01

To represent relation between group and elementary items, level numbers are used in COBOL. Available level number are 01 to 49. Below example shows, how we can define a group item for record shown in previous page.

Till now, we have seen how we can define elementary data items and group data items. Where we need to code these data items? We need to code these group and elementary items either in FILE SECTION ( if we are using files in the program) or in WORKING-STORAGE SECTION.

Data items defined in FILE SECTION & WORKING-STORAGE SECTION can be used in PROCEDURE DIVISION program logic. COBOL VERBS

COBOL VERBS Now let us discuss more about statements in cobol. As we already noted, Statement starts with a COBOL verb. To code a statement or a sentence you need to know cobol verbs. In this page you can see important cobol verbs. in next chapters, we will discuss about these verbs in detail. Data manipulation/arithmetic verbs. INITIALIZE MOVE ADD SUBTRACT MULTIPLY DIVIDE COMPUTE

I-O verbs ACCEPT DISPLAY String handling verbs STRING UNSTRING INSPECT File handling verbs OPEN CLOSE READ WRITE REWRITE START DELETE Program branching Verbs CALL EXIT EXIT PROGRAM GO TO PERFORM STOP STOP RUN COBOL VERBS - INITIALIZE

INITIALIZE

INITIALIZE verb initializes values in a data item to default value. Numeric data items initialized with ZEROS. Alphabetic character codes initilized with spaces. It wont initialize FILLER.

Example - Initializing elementary data item. INITIALIZE WS-A PICTURE 9(4) X(3) XX99 A(4) WS-A. WS-A AFTER 0000 <- SPACES <- SPACES <- SPACES

WS-A BEFORE 6847 12E WE48 WELS

Example - Initializing group data item. 01 CUSTOMER-RECORD. 05 Customer-Name. 10 FirstName 10 MiddleName 10 LastName 05 Customer-DOB. 10 Month 10 FILLER 10 Day 10 FILLER 10 Year

PIC PIC PIC PIC PIC PIC PIC PIC

X(06). X(1). X(05). 99. X VALUE '/'. 99. X VALUE '/'. 99.

values

After executing following statement, it will initialize all to its default values. INITIALIZE CUSTOMER-RECORD. FirstName, MiddleName & LastName are initialized with SPACES.

Month

, Day & Year are initialized with zeros. Since FILLER wont get initialized by INITIALIZE verb, we have used VALUE clause which will initialize FILLER When program execution started.

TIP : Using VALUE clause, we can initialize data items. But it works only once

when program execution started, it will initialize the data item with whatever value specified with VALUE clause. Example - 01 WS-Month PIC 99 VALUE 11.

When program execution started WS-Month data item contains value 11. COBOL VERBS - MOVE

MOVE Verb MOVE literal-1/sending-data-item-1 TO receiving-data-item-1.

MOVE is a Cobol verb, when there is a need for transfering value from one dataitem to another data item, using MOVE verb we can achieve that task. In above syntax, value from sending-field-1 will be moved to receiving-field-1. Sending-filed-1 can a data item OR a literal (string). Example for move a literal to a numeric data item. 01 WS-A .... MOVE 345 PIC TO 999 VALUE 000. WS-A.

Before execution of above statement WS-A contains 000 as a value. After execution of above statement WS-A contains 345. Example - Move a 01 WS-NAME PIC alphanumeric literal to alpha numeric data item. X(4) VALUE 'JOHN'.

... MOVE

'JACOB'

TO

WS-NAME.

Before execution WS-NAME contains value JOHN Afer execution of MOVE statement, WS-NAME contains JACO. If you observe only 4 letters from the string JACOB got transfered to WS-NAME because WS-NAME defined with length of 4 bytes.In alphabetic OR alphanumeric moves, Receiving fields receive the letters from left to right as shown below. That is the reason WS-NAME contains JACO If the receiving field is a numeric data item, data transfer happens from right to left. 01 WS-A PIC 999 01 WS-B PIC 99 ... MOVE WS-A TO WS-B. VALUE VALUE 890. 22.

If numeric data item has any decimal part in it. numeric value after the decimal will be moved to receiving field from left right. i.e, 1st digist after decimal movement happens first, then 2nd byte, etc... COBOL VERBS - ADD

MOVE ADD ADD verb.

Syntax 1 ADD { literal-1 / data-item-1 } .. Syntax 2 ADD { literal-1 / data-item-1 } ..

TO GIVING

target-data-item-1 .. target-data-item-1 ..

ADD verb adds one or more numeric values and store the value into a target data item. Let us see some examples. ADD 10 TO WS-A. Before execution WS-A value is 5, WS-A value will be 15. ADD WS-A WS-B GIVING WS-C.

after excution of above statement

Before execution WS-A value 100 WS-B value 150 WS-C value 786 After execution of above ADD statement, value in data items are shown below. WS-A WS-B WS-C ADD value value value 100 150 250

<-

sum of WS-A, WS-B moved to WS-C

WS-A WS-B GIVING WS-C WS-D WS-E

values in WS-A WS-B will be summed up and the result will be stored in WS-C, WS-D & WS-E. COBOL VERBS - SUBTRACT

SUBTRACT Verb Syntax 1 SUBTRACT { literal-1 / data-item-1 } .. FROM data-item-2 ..

Syntax 2 SUBTRACT { literal-1 / data-item-1 } .. item-2 }

FROM GIVING

{ literal-2/datadata-item-3 ..

Rules - 1. All the values before the word FROM, summed up and subtracted from each data-item/literl after word FROM 2. If GIVING is used, the result will be stored in the dataitems provided after the word GIVING. 3. If GIVING is not used, data-items provided after FROM will be used to store the results. Let us see some examples. Let us assume WS-A contains value 200 WS-B contains value 100 SUBTRACT 10 FROM WS-A.

10 will be subtracted from WS-A and the result will be stored in WSA. i.e, after excution of above statement WS-A contains 190. SUBTRACT 10 FROM WS-A GIVING WS-B.

10 will be subtracted from WS-A and the result will be stored in WSB. Please note there wont be any change in the value of WS-A. WS-A is used in the calcualtion, but the value in WS-A data item wont get changed. SUBTRACT 10 11 12 FROM WS-A GIVING WS-B.

Numbes 10,11,12 will be summed up and subtracted from WS-A value , result will be stored in WS-B. No change to WS-A value. SUBTRACT 10 20 30 FROM WS-A WS-B WS-C.

Numbers 10,20,30 will be summed up and the result value subtracted from WS-A, WS-B, WS-C and stored in the same data items. i.e., summed up value 10+20+30 = 60 , subtracted from WS-A, result will be stored in WS-A,60 subtracted from WS-B and the result will be stored in WS-B. 60 subtracted from WS-C and the result will be stored in WS-C.

COBOL VERBS - MULTIPLY

MULTIPLY Verb MULTIPLY verb. MULTIPLY statement multiplies numeric items. Format 1. MULTIPLY Format 2. MULTIPLY item-2 > < literal-1 / data-item-1 > GIVING data-item-3 ... BY < literal-2 / data< literal-1 / data-item-1 > BY data-item-2 ...

Examples (a) MULTIPLY WS-A BY WS-B. In above example, values in WS-A & WS-B will be multiplied and the result will be stored in WS-B. (b) MULTIPLY WS-A BY WS-B GIVING WS-C. In the example (b), values in WS-A & WS-B will be multiplied and the result will be stored in WS-C. (C) MULTIPLY WS-A BY WS-B GIVING WS-C WS-D. In the example (c), values in WS-A & WS-B will be multiplied and the result will be stored in WS-C , WS-D. COBOL VERBS - DIVIDE

DIVIDE Verb DIVIDE statement divide one number by another and store the result. Format 1. DIVIDE < literal-1 / data-item-1 > Format 2. DIVIDE item-2 > < literal-1 / data-item-1 > GIVING INTO < literal-2 / data-

INTO

data-item-1...

data-item-3... REMAINDER data-item-4...

Examples (a) DIVIDE WS-A INTO WS-B. WS-B value is divided

Above example is equals to WS-B = WS-B / WS-A. by WS-A and the result will be stored in WS-B. (b) DIVIDE WS-A INTO WS-B GIVING WS-C.

Above example is equals to WS-C = WS-B / WS-A. by WS-A and the result will be stored in WS-C. No change to WS-B, WS-A values. (c) DIVIDE WS-A INTO WS-B

WS-B value is divided

GIVING WS-C REMAINDER WS-D.

This statement very similar to example (b), except using REMAINDER word. after dividing WS-B by WS-A remainder value will be stored in WS-D. WS-A value is WS-B value is 100 350 <--- This value will be moved to WS-C.

100 ) 350 ( 3 300

---50 ----

<--- Remainder, this value will be moved to WS-D.

Using BY instead of INTO.... we can use INTO instead of BY in the above format2. that values/data-items used for calcualtion needs to be exchanged to get the same result. But, make sure

example (b) can be rewrite using word BY , to get same result in WS-C, need to swap WS-B, WS-A places. i.e, state should look like DIVIDE WS-B BY WS-A GIVING WS-C. equals WS-C = WS-B / WS-A.

COBOL VERBS - COMPUTE

COMPUTE Verb All the arthemetic, that we can done using verb ADD, SUBTRACT, MULTIPLY, DIVIDE verbs can be done using COMPUTE statement. In COMPUTE statement, we need to use following operators to do arthemetic.

operator + ** /

Meaning Add Subtract Exponentiation Divide

Multiplication

Format. COMPUTE < data-item-1> [ROUNDED] ... = arithmetic-expression [ ON SIZE ERROR < imperative statement-1 ] .. [ NOT ON SIZE ERROR < imperative-statement-2> ] .. Example 1 - COMPUTE WS-A = WS-B + WS-C - WS-D. Values in WS-B , WS-C will be added , WS-D value subtracted from that value and store the final result in WS-A. data-items WS-A changed WS-B WS-C WS-D values before exectuion 300 800 100 050 values after execution 850 800 100 050 <---

It is very important to know the order of evaluation, i.e.., In which order operations are performed in COMPUT statement. Below table , explains us, the order of evalution. Priority 1 Priority 2 operator Priority 3 operator ** * or + or

/ -

( If both appeared , first appeared executed first, from left to right ) ( If both appeared , first appeared executed first, from left to right )

If parentheses appear in the COMPUTE statement, it will override above sequence priority. Operations within parentheses are performed first. Statement WS-A + 10 first and the Order of evaluation Exponentiation ( 10 ** 2) executed

** 2

(WS-A + 10 ) ** 2 exponentiation follows.

result 100 will be added to WS-A Addition executed first and

ROUNDED This option is available with all arithmetic VERBs and it is optional. COMPUTE WS-A = 23.456 + 20.034

When we sum values 23.456 and 20.034 we get the result 40.490. But in this case WS-A picture clause is 99v9 means it can store only 1 decimal position, after executing above statement WS-A contains the value of 40.4 value 90 will get truncated. More desirable value is 40.5 in this case. rounded to nearest value. This can be acheived thru the use of ROUNDED option.

COMPUTE WS-A ROUNDED = 23.456 + 20.034 after execution of above statement WS-A contains value of 40.5

ON SIZE ERROR Let take some example to understand this option. 01 01 01 WS-A WS-B WS-C WS-A PIC PIC PIC = WS-B + WS-C. 9(3) VALUE 400. 9(3) VALUE 800. 9(3) VALUE 300.

COMPUTE

Above statement, add the value in WS-B and WS-C and store that value in WS-A. After execution of above statement WS-A contains the value of 100, instead of 1100. Because WS-A can hold only upto 3 bytes. Please note that, program wont get abended because this overflow/truncation condition. But value moved to WS-A is not correct one. To aviod these kind of size errors, best procedure is make sure receiving field has defined with

large enough size to accommodate the result. But sometimes, programmer may not know the input max number/forget to define the receiving fields with enough sizes. It is a good practice to use ON SIZE ERROR to catch such errors.

ON SIZE ERROR option can be used with following arithmetic statements. ADD ... ON SIZE ERROR ... . SUBTRACT ... ON SIZE ERROR ... . MULTIPLY ... ON SIZE ERROR ... . DIVIDE ... ON SIZE ERROR ... . COMPUTE ... ON SIZE ERROR ... .

COMPUTE WS-A = WS-B + WS-C ON SIZE ERROR

MOVE ZEROES TO WS-A.

In above example, If WS-A cannot accomodate the result then ZEROES will be moved to WS-A.

A size error can occurs in the following ways. - When receiving field is not large enough to accommodate the result. - When division by zero occurs If ON SIZE ERROR option becomes true, statements after this option will get executed. These statement needs to be ended either by period OR scope terminator i.e, in case of ADD, scope terminator is END-ADD. TIP : Always make sure receiving field has large enough to accommodate the result.

Conditional Expressions

Conditional Expressions Statements in COBOL program executed one after another. In programming, many times, Based on some condition, program needs to run one or more sets of statements. If condition is true, one set of statements get excuted. If condition is false another set of statements will get executed. Condition(s) are used in IF, EVALUATE, PERFORM and SEARCH statements. A condition can be any one of the folllowing : Simple conditions (1) Class condition (2) Condition-name condition (3) Relation condition (4) Sign condition (5) Negated simple condition (6) Combined conditions

(1) Class condition class condition determines whether the identifier contains numeric value OR alphanumeric value. Below is the format of class condition [IS] [NOT] < NUMERIC / ALPHABETIC / ALPHABETIC-LOWER / ALPHABETIC-UPPER > This there are many these kind data condition is very useful to minimize the program errors. chances that program may receive corrupted data. To handle of errors, we can use this condition.

If we want to check whether the identifier contains the numeric data or not, before doing arthmetic operation on it. use the Class codition as below

using IF statement.

IF ELSE

WS-AMT IS NUMERIC ADD WS-AMT TO WS-BANLANCE

MOVE ZEROS TO WS-AMT PERFORM ERROR-PARA. END-IF. In above code, we are using WS-AMT, only when it cotain valid numeric data otherwise we are moving ZEROS to that identifier and calling error para. other options. ALPHABETIC - is used to check identifier contains all alphabetic letters or not ( i.e., A-Z, a-z and blank ) ALPHABETIC-LOWER - To check identifier contains only lower alphabetic letters or not. i.e., a-z and blank. ALPHABETIC-UPPER - To check identifier contains only upper alphabetic letters or not. i.e., A-Z and blank.

(2) condition-name condition.

(important) It

condition-name is a identifier defined with level number 88. has only VALUE clause, it does not contain any picture clause, but it must always be associated to a data name called the conditional variable. Format 88 condition-name literal-1 [ literal-2 ] [, literal-3 [ literal-4] ... ]

Example 01 WS-AGE PIC 99. <--- conditional variable 88 INFANT VALUE 0. 88 BABY VALUE 1,2. 88 CHILD VALUE 3 THRU 12.

88

TEEN-AGER VALUE 13 THRU 19.

In the above example we have defined 4 condition-name's associated with one data name WS-NAME. if WS-AGE contains value 0 (ZERO). INFANT will become true , since we have defined this condition-name with value 0. If WS-AGE contains values 1 OR 2, Second condition name BABY will become true,since we have defined BABY condition-name with value 1 and 2. Same rule applied to other condition-names. How we can use this in PROCEDURE DIVISION? See below example... IF INFANT is true, statement(s) after IF statement will be executed. i.e., WS-AGE contains value 0 (ZER0), then INFANT will become true. IF INFANT MOVE 20 TO WS-SIGNAL PERFORM 200-INFANT-PARA END-IF. Same code can be written as below.... IF WS-AGE = 0 MOVE 20 TO WS-SIGNAL PERFORM 200-INFANT-PARA END-IF

(3) Relation Condition Relatioh condition compares two operands either of which can be an idenftifier, literal, arithmetic expression. Format 1 Operand 1 Operand 2

The Relational operator specifies the type of comparison to be made as shown in below table.

Relational operator IS GREATER THAN IS NOT GREATER THAN IS LESS THAN IS NOT LESS THAN IS EQUAL TO IS NOT EQUAL TO IS GREATER THAN OR EQUAL TO IS LESS THAN OR EQUAL TO

Can be written as IS > IS NOT > IS < IS NOT < IS = IS NOT = IS >= IS <=

Meaning of operator Greater than Not greater than Less than Not less than Equal to Not equal to Is greater than or equal to Is less than or equal to

Numeric operand comparison - If two operands can be compared regardless of sizes and USAGE. Non-Numeric operand comparison - Comparison starts from left most character in both the fields ( operand-1 and operand-2) and it proceeds to right. - Comparison happens based on the EBCDIC/ASCII collating sequence of character set OR the character set specified in object-computer paragraph. - If two fields are not equal sizes, comparison happens as though the shorter field extended to right with spaces to make operands equal in sizes. Numeric and Non-Numeric comparison - When Numeric and Non-numeric comparison happens, both operands USAGE must be same. - Non-numeric comparison rules apply

(4) Sign Condition The sign condition determines whether the given numeric value is grater than the ZERO (or) less than the ZERO (or) equal to ZERO.

Format 1 operand-1 [IS] [NOT]

- Operand-1 must be defined as a numeric identifier. - IS POSITIVE condition will become true, if the operand-1 value grater than ZERO - IS NEGATIVE condition will become true, if the operand-1 value less than ZERO - IS ZERO condition will become true, if the operand-1 contains ZERO

(5) Negated simple condition We can negate the simple condition by using keyword NOT. If the condition is true, by using NOT with the condition, overall boolean value of that condition will become false. If the simple condition is flase, by using NOT with the condition, overall boolean value of that condition will become true. Ex. IF A = B COMPUTE C = A ** 2 END-IF

if A & B contains the same value, COMPUTE statement will get executed. if we use NOT with the condition, COMPUTE wont get executed, when A & B contains the same value. IF NOT A = B COMPUTE C = A ** 2 END-IF

(6) Combined conditions Combined conditions contains two or more conditions connected using logical operators AND or OR. Format

condition-1

condition-2

condition-3 ]...

Below table gives the results of using logical operators AND & OR between two conditions COND1 & COND2. COND1 True True False False COND2 True False True False COND1 AND COND2 True False False False COND1 OR COND2 True True True False

Ex.

IF

(WS-A = WS-B) (WS-C = WS-D)

AND

COMPUTE WS-FINAL-AMT = WS-A + WS-C END-IF In above IF condition, if both conditions are true, then COMPUTE statement inside IF will get executed.

IF THEN ELSE statement

IF THEN ELSE END-IF statement Format IF condition-1 THEN Statements-1 .. [ELSE statements-2 .. ]

[END-IF]. - condition-1 is any of the conditions discussed in previoius pages - Statements-1 OR Statements-2 contains one or more COBOL statements - END-IF is the scope terminator. IF statement ends with this scope terminator Note : Instead of END-IF, we can use period as scope terminator. Structured programming rules recommends to use END-IF rather than period (.) - using THEN keyword is optional condition associated with IF statement , becomes true then all statements represented by Statements-1 are get executed. Condition associated with IF statement , becomes false then all statements represented by Statements-2 are get executed. Below picture represents what we discussed.

Example.

IF

WS-A > ZERO AND WS-B > ZERO THEN COMPUTE POSITIVE-AMT = WS-A + WS-B END-IF

In the above example, COMPUTE statement execute only when the condition associated with IF statement becomes true. i.e., WS-A & WS-B should contains positive values.

Example 2.

'

IF WS-A > ZER0 AND WS-B > ZERO THEN COMPUTE POSITIVE-AMT = WS-A + WS-B ELSE DISPLAY ' One of the input amount are not positive DISPLAY 'WS-A value ', WS-A DISPLAY 'WS-B value ', WS-B END-IF.

In this example, we have use ELSE keyword. If the condition associated with IF statement is true then the COMPUTE statement will get executed. If the condition is false, the statements after ELSE keyword will get executed. Below picture represents what we discussed above.

NEXT SENTENCE NEXT SENTENCE can be used in the place of either Statements-1 (THEN part) or Statements-2 (ELSE part) in IF statement. - if there is no action required either in THEN part OR ELSE part of IF statement we can use this NEXT SENTENCE - It will transfer control to next statement after the nearest period - Please make note that control wont pass to the next statement of END-IF, in this case. NEXT SENTENCE only check for closest period and execute the statements after that. Example MOVE 100 TO WS-A. MOVE 200 TO WS-B. MOVE 300 TO WS-C. IF WS-A > ZER0 AND WS-B > ZERO THEN NEXT SENTENCE ELSE DISPLAY ' One of the input amount are not positive ' DISPLAY 'WS-A value ', WS-A DISPLAY 'WS-B value ', WS-B END-IF ADD WS-A TO WS-C.

DISPLAY 'WS-C value', WS-C. Simple Test - Tell me what value will be displayed for the WS-C (last display statement in the above example) ? Ans : 300 OK, let me explain, why the above example displayed 300 instead of 400. If you observe there is no period after END-IF, period is there after ADD statement. Since the condition associated with IF statement is true, NEXT SENTENCE tranfered the control to the statement after closest following period, then DISPLAY statement displayed the WS-C value ADD statement did not get executed. Below picture shows the same what we discussed till now.

If you have a period after END-IF, WS-C value will be 400. because ADD statement will get executed in this case. Quite interesting, isn't it? Normally we may face the interview question on differences between CONTINUE (cobol 85) and NEXT SENTENCE (cobol 74). CONTINUE is dummy statement, control will continue as if there are no statements, i.e., it wont do any control transfers. In above example, if you have CONTINUE statement instead of NEXT SENTENCE , o/p will be 400.

Nested IF statements

it.

One IF statement can contain one or more IF statements within As shown below. IF condition-1 IF condition-2 Statements-1 ELSE Statements-2 END-IF ELSE IF condition-3 Statements-3 ELSE Statements-4 END-IF END-IF

- In nested IF conditions, each END-IF paired with the preceding IF. - It is suggested to use END-IF as scope terminator instead of period - In COBOL 74 we dont have END-IF scope terminator, need to use ELSE NEXT SENTENCE as and when required for proper pairing of ELSE part with IF statement. ( In COBOL 85 we have END-IF, so it is suggested not to use period as scope terminator in nested IF conditions for better readability and to reduce errors )

GO TO Statement

GO TO statement GO TO statement permanently transfers control from one part of program to other part of program.

Format. GO TO Paragraph-name.

Example PROCEDURE DIVISION. MAIN-PARA. DISPLAY 'MAINPARA STARTS HERE'. GO TO PARA-1. DISPLAY 'A VALUE ', A. STOP RUN. PARA-1. COMPUTE A = B + C.

In above exmaple, control first executes the DISPLAY statement to display the string ' MAINPARA STARTS HERE' , then control executes GO TO statement, now control will go to PARA-1 and executes COMPUTE statement. that's it. control wont come back to next statement after GO TO, because control permanently transfered to PARA-1 - Structured programming languages techniques suggest to avoid using GO TO ,

use PERFORM instead - Programmer may face more logic errors with GO TO compare than PERFORM - Readability of programs goes down, if we use more GO TO statements in the program

PERFORM Statement

PERFORM Statement Simple form of PERFORM acts very similar to GO TO statement, except that after execution of paragraph control will return back to the next statement of PERFORM statement. Format - 1 PERFORM procedure-name-1

Example 1 Below picture represents the difference between GO TO and PERFORM statements.

In above example, when we use PERFORM in the place of GO TO statement, after execution of PARA-1, control return back to the next statement of PERFORM and continued the execution.

Example 2 PERFORM PARA-1 THRU PARA-2

PARA-1 & PARA-2 are paragraph names. Execution of PERFORM statement causes control transfers to the first statement of PARA-1. control executes all the statements from the first statement

of PARA-1 to last statement of PARA-2 and the control return to the next executable statement of PERFORM statement. if there are any other paragraphs between PARA-1 and PARA-2, all those statements are included for execution.

PERFORM with TIMES phrase Format - 2 PERFORM procedure-name-1 data-item-1/literal-1 TIMES

This is very similar to what we discussed in 1st format of PERFORM, except that, here we can specify , how many times we want to execute same set of commands.

Example -

PERFORM

PARA-1

THRU PARA-2

10 TIMES.

All the statements in the scope of PARA-1 thru PARA-2 are get executed 10 times. Control then passes to the next executable statement following PERFORM statement

PERFORM with UNTIL phrase Format - 3 PERFORM procedure-name-1 UNTIL condition-1

In this format all the statments come under scope of procedurename-1 & procedure-name-2 are get executed till condition-1 becomes true. It is very similar to WHILE statement in other programming languages.

- TEST BEFORE is the default one. condition-1 will be tested before execution of statements. equalent to DO WHILE statement in other programming langauges. - If TEST AFTER is used, condition-1 will be tested after one execution of statements. This is equalent to DO UNTIL statement in other programming languages. In either case, if condition-1 is true, control is transfered to next executable statement after PERFORM statement.

PERFORM with VARYING phrase Format - 4 PERFORM procedure-name-1 [TESTBEFORE/TESTAFTER] VARYING [ AFTER [ AFTER d- -> data-item i- -> index-name l- -> literal FROM FROM FROM BY BY [THRU/THROUGH procedure-name-2] BY UNTIL condition-1

AFTER codition-2 ] AFTER codition-3 ] ...

This format is little complex to understand for new learners. Let us try to understand what exactly means of this syntax. It is very similar to Format-3 ( PERFORM... UNTIL ), except in this format it allows us to increase one or more data-item values automatically. Example 1 WS-I > 10 PERFORM PARA-1 VARIYING WS-I FROM 1 BY 2 UNTIL

In above example , all statements in PARA-1 are executed till the codition associated with UNTIL becomes true. For first iteration WS-I contains the value of 1 ( as it is specified after FROM ), for second iteration WS-I value increase by 2 ( as it is specified after BY keyword) and condition will be tested, if it false statements in PARA-1 will get executed and control come back to PERFORM,

Now WS-I value increased again by 2 and condition will be tested, if it is false, statements in PARA-1 will get executed again. This loop continues till the condition becomes true.

PERFORM with VARYING , AFTER phrases

Example 2 I > 10 J > 20

PERFORM PARA-1 VARIYING

WS-I FROM 1 BY

UNTIL WS-

AFTER WS-J FROM 1 BY 3 UNTIL WS-

In this example, in addition to WS-I, WS-J value also get changed. For every valid value in WS-I, WS-J value start from 1 till WS-J > 20 becomes true. PERFORM statement execution ends only when WS-I > 10 becomes true.

STRING

STRING

The STRING verb concatenates the partial or complete contents of two or more strings or literals into one single data item. Below example illustrates how the string is used. String Example: 01 WS-DATA-ITEM1 PIC X(10) THIS IS .

01

WS-DATA-ITEM2

PIC X(20)

STRING FIRST.

STRING

WS-DATA-ITEM1 DELIMITED BY SIZE. WS-DATA-ITEM2 DELIMITED BY SPACES EXAMPLE. DELIMITED BY SIZE INTO WS-DESTINATION

This example will concatenate the strings WS-DATA-ITEM1 and WS-DATAITEM2 into WS-DESTINATION. In above example WS-DATA-ITEM1 is delimited by size,so complete string content will be moved to destination string(WS-DESTINATION). WS-DATA-ITEM2 is delimited by SPACES, partial content (characters up to first space) will be moved. And complete literal (i.e. EXAMPLE. ) will be moved. Now WS-DESTINATION will contain THIS IS STRING EXAMPLE.

WITH POINTER is optional, value associated with it (Pointer-integer) determines

the starting character position for insertion into the destination string, and pointer-integer must be an integer item. ON OVERFLOW is optional, this clause specifies what needs to be done when overflow condition occurred. Overflow condition occurs in following conditions. The pointerinteger is not pointing to a character position within the destination string when the STRING executes. i.e.less than 1 or exceeding the length of destination string. If all source strings together are not accommodated in destination string then overflow occurs. DELIMITED BY phrase specifies the content of source string to be transferred. DELIMITED BY [SPACES, Data item or literal] -> Transfers the data till sepcificed delimeter found DELIMITED BY SIZE, Transfers complete string.

Data movement from a particular source string ends when either; 1. The end of the source string is reached 2. The end of the destination string is reached 3. The delimiter is detected. The STRING statement ends when either; 1. All the source strings have been processed. 2. The destination string is full. 3. The pointer points outside the string.

STRING Example: 01 WS-DATA-ITEM1 01 WS-DATA-ITEM2 01 WS-DATA-ITEM3 CONCATENATION. 01 WS-POINTER 01 PIC X(20) PIC X(20) PIC X(25) PIC 9(02) VALUE THIS STATEMENT. VALUE IS EXAMPLE #2 AND. VALUE FOR STRING VALUE 3.

WS-DESTINATION PIC X(35).

STRING WS-DATA-ITEM 1 DELIMITED BY SPACES SPACE DELIMITED BY SIZE WS-DATA-ITEM 2 DELIMITED BY #

SPACE DELIMITED BY SIZE WS-DATA-ITEM 3 DELIMITED BY SIZE INTO WS-DESTINATION WITH POINTER WS-POINTER ON OVERFLOW DISPLAY Overflow condition occurred END-STRING In Above example result will be transfered into destination string from 3rd character position (WITH POINTER option). WS-DATA-ITEM1 is delimited by spaces, so characters up to first space (i.e. THIS) will be inserted into WS-DESTINATION, starting from 3 character position (WS-POINTER value is 3). After all data transfer, WSPOINTER will be 7 (next insertion position). WS-DATA-ITEM2 is delimited by delimiter #, so characters will be moved to destination string till it encounters delimiter # (i.e. IS EXAMPLE ). WS-POINTER will be 18. WS-DATA-ITEM3 is delimited by SIZE, so all characters will be moved to destination string. WS-POINTER will be 36. WS-POINTER is exceeding length of destination string (35), overflow condition is satisfied, so DISPLAY statement will be executed

Difference between DELIMITED BY SIZE and DELIMITED BY SPACE DELIMITED BY SIZE will add whole of the source string to destination string. DELIMITED BY SPACE will add part of source string until first space encountered.

For example Input string contains value -

This is Example string

If you want full string in the output field, use BY SIZE option as shown below. DELIMITED BY SIZE -> This is Example String If you want only first word from the sentence, use BY SPACE option as shown below. DELIMITED BY SPACE -> This

UNSTRING

UNSTRING The UNSTRING verb is used to divide a string into sub-strings The UNSTRING copies characters from the source string, to the destination strings, until a delimiter encountered that terminates data transfer. When data transfer ends for a particular destination string, the next destination string will become the receiving area.

The following example shows how UNSTRING is used. Example: UNSTRING userid@company.com DELIMITED BY @ OR . INTO WS-USER-ID WS-COMPANY WS-DOMAIN END-NSTRING

In this example unstrings the literal userid@company.com into different strings WS-USER-ID, WS-COMPANY and WS-DOMAIN based on delimiters (i.e. @ and .). Characters from source string (i.e. userid@company.com) until delimiter @ will be moved to WS-USER-ID, after that characters until delimiter . will be moved to WS-COMPANY, remaining characters in source string will be moved to WS-DOMAIN.

Delimiter - Character or set of characters in the source string that terminates data transfer to a particular string. We can specify one or more delimiters if anyone delimiter encountered in source string, the data will be transferred to next destination string. Hold-delimiter Holds the delimiter that caused the termination of data transfer to associated destination string. Char-counter Holds the no of characters transferred into associated destination string. Pointer-integer Points to the position in the source string from which the next character will be taken. Destination-counter Holds the count of no of destination strings affected by

UNSTRING verb. - If the DELIMITED BY phrase is not used, then DELIMITER IN and COUNT IN phrases must not be specified. - When the ALL phrase is used, contiguous delimiters are treated as one delimiter. If the ALL is not used, contiguous delimiters will act as separate delimiters and result in spaces being sent to some of the destination strings.

Example -1: UNSTRING source-string DELIMITED BY INTO destination-string1 Destination-string2 Destination-string3 END-UNSTRING /

Input: Output:

Source-string = 19/11/2010 Destination-string1 > 19 Destination-string2 -> 11 Destination-String3 -> 2010

Above UNSTRING example moves source data into destination delimited by / accordingly.

Example -2 : UNSTRING source-string DELIMITED BY SPACES INTO destination-string1 COUNT IN char-counter1 destination-string2 COUNT IN char-counter2 destination-string3 COUNT IN char-counter3 destination-string4 COUNT IN char-counter4 WITH POINTER TALLYING IN ON OVERFLOW NOT ON OVERFLOW END-UNSTRING / OR # OR ALL

DELIMITER IN hold-delimiter1 DELIMITER IN hold-delimiter2 DELIMITER IN hold-delimiter3 DELIMITER IN hold-delimiter4

pointer-integer destination-count DISPLAY Overflow occurred DISPLAY No overflow

Input:

Source-string = +TODAYSDATEIS Pointer-integer = 02

19//11-2010

Output: Once the above statement executed destination variables hold these values. Destination-string1 Destination-string2 Destination-string3 Destination-string4 -> -> -> -> TODAYSDATEIS "19 (Spaces) "11-2010

Unstring will start from position 2 in source-string because of value in WITH POINTER option. DATE FUNCTIONS

DATE FUNCTIONS 1. CURRENT-DATE is COBOL intrinsic function to get current date, time and difference between current location time and Greenwich Mean Time. MOVE FUNCTION CURRENT-DATE TO WS-CURRENT-DATE-DATA This function returns a 20-character alphanumeric field in the below format 01 WS-CURRENT-DATE-DATA. 05 WS-CURRENT-DATE. 10 WS-CURRENT-YEAR

PIC 9(04).

10 WS-CURRENT-MONTH PIC 9(02). 10 WS-CURRENT-DAY PIC 9(02). 05 WS-CURRENT-TIME. 10 WS-CURRENT-HOURS PIC 9(02). 10 WS-CURRENT-MINUTE PIC 9(02). 10 WS-CURRENT-SECOND PIC 9(02). 10 WS-CURRENT-MILLISECONDS PIC 9(02). 05 WS-DIFF-FROM-GMT PIC S9(04). WS-CURRENT-DATE-DATA contains : 2010111917542857+0800

2. Other COBOL date intrinsic function. a) Converting from Gregorian dates to integer date. -date). COMPUTE integer-date = FUNCTION INTEGER-OF-DATE (Gregorian be in form YYYYMMDD. is a 7-digit integer 0 < MM < 13; 0 < DD < 32 for the specified month and year

Gregorian-date must The function result Note: 1600 < YYYY < 9999; (provided that day is valid combination).

b) Convert from Integer to Gregorian formats. COMPUTE Gregorian-date = FUNCTION DATE-OF-INTEGER (integerdate) The function result Gregorian-date is an eight-digit integer in the form YYYYMMDD.

c) Convert from Julian to Integer formats COMPUTE integer-date = FUNCTION INTEGER-OF-DAY (Julian-date) Julian-date must be in The function result is Note: 1600 < YYYY < 9999 and 0 (provided the day is valid for the form YYYYDDD, a 7-digit integer. < DDD < 367 the specified year)

d) Convert from Integer to Julian formats COMPUTE Julian-date = FUNCTION DAY-OF-INTEGER (integer-date)

1600, in

The Julian-date is a seven-digit integer in the form YYYYDDD. Integer-date represents a number of days after December 31, the Gregorian calendar. All these functions deal with converting between Gregorian

dates or is

Julian dates and integer format date. This integer format date number of days from fixed date

Example : Converting Gregorian format date 20101202 to Julian format date. COMPUTE integer-date = FUNCTION INTEGER-OF-DATE (Gregorian -date). This converts 20101202(Gregorian date) to 0149720(integer format date). COMPUTE Julian-date = FUNCTION DAY-OF-INTEGER (integer-date). This converts 0149720(integer format date) to 2010336(Julian format date YYYDD)

using above date functions, one can get add or subtract days from current date. It is easy with these functions.

Example-2: Calculate date after 10 days from Today. MOVE FUNCTION CURRENT-DATE TO WS-CURRENT-DATE-DATA. This move statement moves current timestamp (20-bytes) to WSCURRENT-DATE-DATA. Since we need only current date, we will take 8 bytes from WSCURRENT-DATE-DATA. COMPUTE ws-integer = FUNCTION INEGER-OF-DATE (WS-CURRENT-DATEDATA(1:8)) This converts 20101202 to integer form 0149720 ( i.e. no of days from fixed date) ADD 10 TO ws-integer This calculates the integer form date of future date.

it will add 10 days to ws-integer. COMPUTE ws-future-date = FUNCTION DATE-OF-INTEGER (ws-integer). Convert integer form date (i.e. 149730) to date format i.e. 20101222 COBOL REDEFINES

COBOL REDEFINES

The REDEFINES clause allows the same memory area to be described by different data items. In program if we are sure that 2 or more date names are not in use at same time then we go for redefines clause.

01 WS-NAME. 05 WS_FST-NAME 05 WS_FST-NAME 01 WS-TOTAL-NAME

PIC X(05) PIC X(05) REDEFINES

VALUE John. VALUE Mike. WS-NAME PIC X(10).

In above example WS-TOTAL-NAME will use same memory area allocated to WS-NAME. So Ws-TOTAL-NAME will have John Mike 1. 2. 3. 4. Level numbers of WS-DATA-NAME1 and WS-DATA-NAME2 should be same. REDEFINES clause cannot be used for level numbers 66 and 88. REDEFINES may not be used in a level 01 entry in the File Section. Number of characters need not be the same for WS-DATA-NAME1 and WS-DATA-NAME2. Compiler generates warning if number of characters in WS-DATA-NAME2 is greater than WS-DATA-NAME2. 5. Several data items can redefine the same data item.

6. Data items redefining the storage of a data item must immediately follow the description of that data item. Difference between REDEFINES and RENAMES: RENAMES clause is used for regrouping elementary data items and gives one name to it. REDEFINES clause allow you to use different data descriptions entries to describe same memory area INSPECT

INSPECT INSPECT verb allows to count and/or replace a character or a group of characters. INSPECT has options TALLYING, REPLACING & CONVERTING. INSPECT with TALLYING option This form counts/tally a character or a group of characters in source string. INSPECT Examples: Source-string = AABAbbACABA 1. INSPECT source-string TALLYING tally-counter FOR CHARACTERS BEFORE INITIAL C In this example tally counter will have count of all characters before first occurrence of C in source-string. Tally-counter will be 7. AABAbbACABA 2. INSPECT source-string TALLYING tally-counter FOR ALL A In this example tally counter will have count of all occurrences of A in source-string. Tally-counter will be 6. AABAbbACABA

3. INSPECT source-string TALLYING tally-counter FOR ALL A AFTER INITIAL B In this example tally counter will have no of occurrences of A after first occurrence of B. Tally-counter will be 4. AABAbbACABA

4. INSPECT source-string TALLYING tally-counter FOR LEADING A In this example tally counter will have no of leading As. Tally-counter will be 2. AABAbbACABA 5. Source-string = " SSET" If we need to get string without spaces, trim the string. we can use following logic. INSPECT FUNCTION REVERSE (Source-string) TALLYING space-count FOR LEADING SPACES. COMPUTE length-of-string = 6 - space-count. Move Source-string(space-count+1 : length-of-string ) TO ws-targetstring. Above INSPECT command get the no of leading spaces from the string. after executing the INSPECT command space-count variable contains 2. In compute statement, space-count subtracted from length of Source-string. value 4 will be stored in length-of-string. In move statement, Using referece modification, moved actual string to ws-target-string. removed spaces.

INSPECT with REPLACING option This form replaces a character or group of characters Example: Source-string = AABAbbACABA 1. INSPECT source-string REPLACING CHARACTERS BY # BEFOR INITIAL C. In above example all characters before first occurrence of C in source-string are replaced by #. Input : AABAbbACABA

Output: -#######CABA.

2.

INSPECT source-string

REPLACING ALL A BY #

In above example all occurrences of A in source-string are replaced by #. Input : AABAbbACABA

Output: - ##B#bb#C#B#. TIPS : With CHARACTERS phrase only one character size of replacing string should be specified. And also delimiter (C) must be of one character. Replacing string and replaced string must be of same size if we use phrases ALL, LEADING and FIRST.

INSPECT with TALLYING and REPLACING options This form counts/tally a character or group of characters and replaces a character or group of characters. Example: Source-string = AABAbbACAB 1. INSPECT source-string TALLYING tally-counter FOR ALL A AFTER INITIAL B REPLACING ALL A BY # AFTER INITIAL B In above example all occurrences of A after first occurrence of B in source-string are counted and replaced by #. Tally-counter Source-string will be 3 will be AAB#bb#C#B.

INSPECT with CONVERTING option This form converts characters from one sequence string to characters from equal size other sequence string on one to one mapping basis. These two sequence strings must be of same size.

Example: Source-string = AABAbbACAB 1. INSPECT source-string CONVERTING BXCY TO 1234

In above example converts the characters B, X, C, Y to 1, 2, 3, and 4 respectively. Input : AABAbbACAB Output: AA1AbbA3A1 Equivalent INSPECT with REPLACING option INSPECT source-string REPLACING ALL ALL ALL ALL B X C Y BY BY BY BY 1 2 3 4

Difference between CONVERTING and REPLACING options in INSPECT Source-string = AABAbbACAB INSPECT source-string CONVERTING AB TO 12 Output: - 1121bb1C12 INSPECT source-string REPLACING AB TO 12 Output:- A12AbbAC12 In example 1, all occurrences of characters A and B are replaced by characters 1 and 2 respectively. In example2, all occurrences of string AB is replaced by string 12.

EVALUATE

EVALUATE

We can use EVALUATE instead of set of nested IF statements to test several conditions. We can use EVALUATE to implement case structure or decision table. Example1 : EVALUATE WS-INDICATOR WHEN A DISPLAY This is Alphabetic filed WHEN N DISPLAY This is Numeric filed WHEN X DISPLAY This is Alpha numeric filed WHEN OTHER DISPLAY Invalid indicator END-EVALUATE This example evaluates WS-INDICATOR if WS-INDICATOR is A displays This is Alphabetic field, if WS-INDICATOR is N displays This is Numeric filed, if WS-INDICATOR is X displays This is Alpha numeric filed. If WS-INDICATOR is not A or N or X then it displays Invalid indicator. EVALUATE Exmaple 2 : IF operand1 = operand4 AND operand2 = operand5 Statements block1 ELSE IF operand1 >= operand6 AND operand1 <= operand7 AND operand2 = operand8 Statements block2 ELSE Statements block3 END-IF END-IF. We can use following EVALUATE statement instead of above nested IF. EVALUTE operand1 ALSO operand2 WHEN operand4 ALSO opernad5 Statements block1 WHEN operand6 THRU operand7 Statements block2 WHEN OTHER Statements block3 END-EVALUATE

ALSO

operand8

Evaluate Example 3: EVALUATE TRUE ALSO WS-GENDER ALSO WS_AGE WHEN WS-INCOME >= 10000 AND < 500000 MOVE 13.5 TO WS-RATE WHEN WS-INCOME >= 10000 AND < 500000 MOVE 12.0 TO WS-RATE WHEN OTHER MOVE 0 END-EVALUATE. This example is an example of decision table, calculates tax rate based on income, age and sex. First WHEN clause will satisfy if condition on income (>= 10000 and < 500000) is true, gender is M and age is in range of 20 to 60, if it is true, then MOVE statement after first when will get executed, and control come out of EVALUATE. If first WHEN condition becomes false, then control goes to second WHEN condition and check the condition, whether that is true or false, if it is true, it will execute MOVE statement after the second WHEN condition. if second WHEN condition is false, then control will go to the MOVE statement coded after WHEN OTHER, here it wont check for true or false. OCCURS DEPENDING ON TO WS-RATE ALSO ALSO M F ALSO ALSO 20 THRU 60 20 THRU 60

OCCURS DEPENDING ON

Using OCCURS clause we can define tables/arrays in cobol. For example if you want to store monthly profits for the year, you need to define 12 data items for each month 01 01 . 01 WS-PROFIT-JAN WS-PROFIT-FEB WS-PROFIT-DEC PIC 9(05)V99. PIC 9(05)V99. PIC 9(05)V99.

Instead of declaring multiple data items we can specify field once and declare that it repeats 12 times, one for each month. 01 WS-PROFIT PIC 9(05)V99 OCCURS 12 TIMES.

WS-PROFIT(1) contain 1st month profit. WS-PROFIT(2) contain 2nd month profit. .. WS-PROFIT(12) contain 12th month profit. Accessing array elements using numbers is called subscripting. (ie, WS-PROFIT(1) , here 1 is used to refer 1st element in array , WS-PROFIT(2), here 2 is used to refer 2nd element in array..). Subscripting is a method of providing table references through the use of integer numbers as shown in below example.

The OCCURS can also be used at group level. Example: 01 WS-EMP-DATA OCCURS 20 TIMES. 05 WS-EMP-ID PIC X(05). 05 WS-EMP-NAME PIC X(15).

In the above example OCCURS is at group level so entire group (employee id and employee name) occurs 20 times. Table data can also be arranged in ascending or descending order depending on data items specified. And we can also specify indexes that can be used with a table. For example employee data can be arranged in employee id ascending order, and with index WS-INDEX. 01 WS-EMP-DATA OCCURS 20 TIMES ASCENDING KEY WS-EMP-ID INDEXED BY WS-INDEX. 05 WS-EMP-ID PIC X(05). 05 WS-EMP-NAME PIC X(15).

OCCURS.

DEPENDING ON:

Variable length tables can be specified using OCCURS DEPENDING ON clause. This allows tables to occur variable no of times depending on the value of some other field.

Example: 01 01 WS-EMP-COUNT WS-EMP-DATA 05 WS-EMP-ID 05 WS-EMP-NAME PIC 9(03). OCCURS 1 TO 100 TIMES DEPENDING ON WS-EMP-COUNT PIC X(05). PIC X(15).

In above example WS-EMP-DATA is variable length table. WS-EMP-DATA can have 1 to 100 employee records. The actual number of employee records depends on WS-EMP-COUNT value. Size of the table depends on the number of table occurrences, i.e. WS-EMP-COUNT. Minimum size occupied is 20 bytes and maximum is

2000 bytes.

SEARCH.. WHEN..

SEARCH.. AT END

The SEARCH statement is used to locate or search for an element in a one-dimensional Table. SEARCH Table name [AT END imperative statements] WHEN condition 1[imperative statements] [END SEARCH] The following rules apply to the SEARCH statement. 1. The SEARCH statement can be applied to a Table only if it is indexed using INDEXED BY phrase. 2. Before using the SEARCH statement, the index must be initialized using a SET statement. 3. If the SEARCH statement terminates without finding the particular element in the Table, then the index has an unpredictable value. 4. The SEARCH statement cannot be used to find multiple matches. 5. The SEARCH statement does a sequential or serial search of the table. 6. If search reaches end of array then at end statement will be executed.

SEARCH Example : 01 WT-FIELDS. 05 WT-CODE-CTRL OCCURS 100 TIMES INDEXED BY WT-CODE-CTRL-INDEX. 10 WT-CODE-VALUE PIC X(03). 10 WT-CODE-DESC PIC X(03).

SET WT-CODE-CTRL-INDEX TO 1. SEARCH WT-CODE-CTRL AT END DISPLAY SEARCH ELEMENET NOT FOUND IN TABLE WT-CODEWHEN WT-BILLER-CODE (WT-CODE-CTRL-INDEX) = 121 DISPLAY WT-CODE-DESC (WT-CODE-CTRL-INDEX) END-SEARCH. SEARCH ALL

CTRL

SEARCH ALL

Search all is similar to binary search. Binary search is a way of searching for element [array] within group of elements. Binary search works by comparing an input value to the middle element of the array. Elements within array must be sorted in either ascending or descending order before binary search and Binary search trying to match search element with the middle element. If the search element is equals to middle element, search process end there. If the search element is greater than middle element then array is divided into 2 equal parts and search will happen in second half. If element is less than middle element then it again search within first half. Whether it selected first half or second half, it again select the middle element in that part and continue this process until either element is found or there are no elements to search.

Binary Search Algorithm / half-interval search If table is contain N even number of elements then middle number is identified as N/2. If that N number is odd then middle number is identified as (N+1)/2. If we are trying to find an element 14 within set of numbers then the following process happens to find element. 18, 14, 1, 6, 9, 8, 3 Step 1: All elements must be in sorted order. 1, 3, 6, 8, 9, 14, 18 TIP : SEARCH ALL dont do this. we need to use ascending keyword while defining array using OCCURS clause. Step 2: Find middle element. In this group we have 7 elements. accoridng to binary search rules we need to calcualte middle element by using formula N-1/2. So, in our array, middle element is 8. Step 3: Binary search match 14 with middle element 8 and finds 14 > 8 so divides this group into 2 equal groups Group 1: 1, 3, 6 Groups 2: 9, 14, 18

Binary search compares second half middle element 14 with 14. Search found the element. Search all stops the search here. When the Table entries are arranged in sequence by some field, such as EMP-ID, the most efficient type of lookup is a binary search. The SEARCH ALL statement provides a means for doing the same. TIP : If array is large (100+) it is good practice to go for search all. If array is small then go for search.

Syntax: SEARCH ALL Tablename [AT END imperative statements WHEN data name 1 IS EQUAL TO [identifier 2 or literal 1 or arithmetic expression 1] [AND data name 2 IS EQUAL TO [identifier 2 or literal 1 or arithmetic expression 1]

IMPERATIVE STATEMENT [END SEARCH]

1. 2. 3. 4. 5.

The condition following the word WHEN can only test for equality. The condition has to be equality. Only one WHEN clause can be used. Table must be sorted order. The OCCURS item and its index, which define the Table argument, must appear to the left of the equal to sign. 6. Does not require SET statement prior to SEARCH ALL.

SERACH ALL Example : 01 WT-FIELDS. 05 WT-CODE-CTRL

OCCURS 100 TIMES INDEXED BY WT-CODE-CTRL-INDEX ASCENDING KEY IS WT-CODE-VALUE 10 WT-CODE-VALUE PIC X(03). 10 WT-CODE-DESC PIC X(03).

SEARCH ALL WT-CODE-CTRL AT END DISPLAY SEARCH ELEMENET NOT FOUND IN TABLE WT-CODECTRL WHEN WT-BILLER-CODE (WT-CODE-CTRL-INDEX) = 121 DISPLAY WT-CODE-DESC (WT-CODE-CTRL-INDEX) END-SEARCH. COPY

COPY

COPY Statement is compiler directive statement. This places

the prewritten text in a COBOL program during compilation time. COPY statement in COBOL is Replaced at compile time, while other statements are executed at runtime. When a COPY statement is used in COBOL program, the source text is copied into the program from copy file/library before the program is compiled. This statement can appear in source program anywhere a character can appear. All COPY statements will be processed before source program compilation. For example COPYFILE contains following text 01 WS-COPYFIELD PIC 9(02) VALUE ZEROES. And we can include the above text in program using COPY statement. The resulting text in program will appear as follows in listing file. DATA DIVISION. WORKING-STORAGE SECTION. *COPY COPYFILE. 01 WS-COPYFIELD 01 WS-INPUT

PIC 9(02) VALUE ZEROES. PIC X(01).

If COPY statement is specified with SUPPRESS option, text in COPYFILE will not be displayed in listing file. If COPY is specified with REPLACING option, the text in COPYFILE will be replaced first, and then it will be copied into program. We can use REPLACING option to replace the string COPYFIELD with WS- COPYFIELD For example COPYFILE contains following text 01 COPYFIELD PIC 9(02) VALUE ZEROES.

After compilation, listing will contain WS-COPYFIELD value included DATA DIVISION. WORKING-STORAGE SECTION. *COPY COPYFILE REPLACING COPYFIELD BY WS-COPYFIELD. <-- Commented out. 01 WS-COPYFIELD PIC 9(02) VALUE ZEROES. <-- New record inserted. .. 01 WS-INPUT PIC X(01). ..

We can also use REPLACING option to replace part of string, i.e. :TAG:

with WS For example COPYFILE contains following text 01 :TAG:-COPYFIELD PIC 9(02) VALUE ZEROES.

During compilation process, COPY statement will be commented out and data from copy book will be inserted into the program. DATA DIVISION. WORKING-STORAGE SECTION. *COPY COPYFILE REPLACING ==:TAG:== BY ==WS==. <-- Commented out 01 WS-COPYFIELD PIC 9(02) VALUE ZEROES. <-- Newly inserted row .. 01 WS-INPUT PIC X(01). .. Operands in REPLACING option can be pseudo text, identifier or literal. Pseudo text is group of characters bounded by, but not included delimiters (==). Both delimiter characters must appear on one line. COPY statements can be nested. However, o Nested COPY statements cannot contain the REPLACING phrase, and a COPY statement with the REPLACING phrase cannot contain nested COPY statements. o Nested COPY statement cannot cause recursion But it is not advisbale to use nested COPY statements, as it will impact readability of the program. ------------- Article 2 -------------------------------------------------COPY : In many programs usually files or Piece of code are accessed by more than one Program in the system. In addition, record structures and routines such as date validation routine are generally used by several programs. In these situations, it is important to ensure that each program has the same file description, record structure or code. Maintaining several copies of the same thing leads to errors and is also time consuming. Each time you modify one copy, you also need to modify all the other copies and each modification is an opportunity to introduce errors. To address all these issues, COBOL provides the COPY statement.

The COPY statement inserts the code from specified copybook in copy library into the source program during compilation. Thus, unlike all other COBOL statements which gets executed during runtime, the COPY statement gets executed during the compile time. In addition to merely inserting a copybook from a copy library, the COPY statement can also modify the text as it is being inserted, by replacing words contained in the copybook. To facilitate, we must use the REPLACING BY clause. A COPY statement can be placed anywhere in the source program where a character string can be used.

For example: COBOL program IDENTIFICATION DIVISION. PROGRAM-ID. COPYPRM. ENVIRONMENT DIVISION. DATA DIVISION. WORKING-STORAGE SECTION. * * 77 WS-NAME PIC X(26)

COPY F040860 PROCEDURE DIVISION. .. ..

F040860 is copy book which stored in V2145.COBOL.COYBOOK It structure is 01 WS-RECORD. 05 WS-NUMBER 05 WS-NAME 05 WS-LOB

PIC 9(09). PIC X(10). PIC X(03).

Here in COBOL program after compilation, COBOL program contains this Code. During compilation process, compiler replaces COPY statement with the copybook content. IDENTIFICATION DIVISION.

PROGRAM-ID. COPYPRM. ENVIRONMENT DIVISION. DATA DIVISION. WORKING-STORAGE SECTION. 77 WS-NAME * *COPY F040860 commented out 01 WS-RECORD. 05 WS-NUMBER 05 WS-NAME 05 WS-LOB * PROCEDURE DIVISION. .. .. PIC X(26) <-PIC 9(09). PIC X(10). PIc X(03). <-<-<-<-Attention, Newly Newly Newly Newly inserted inserted inserted inserted

COPY

INITIALIZE The INITIALIZE statement sets selected categories of data fields to predetermined values; it is functionally equivalent to one or more MOVE statements. INITIALIZE perform no action on FILLER areas and also OCCURS DEPENDING ON clause untouched. INITIALIZE Moves spaces to alphabetic, alphanumeric, and alphanumeric-edited items and zeros to numeric items. 01 WS-RECORD. 05 WS-NUMBER 05 WS-NAME 05 WS-LOB

PIC 9(09). PIC X(10). PIC X(03).

INITIALIZE WS-RECORD. This Moves zeros to WS-NUMBER and Spaces to WS-NAME and WS-LOB. INITIALIZE REPLACING: To move data with a specific constants instead of Zeros and spaces.

Example Program : INITIALIZE WS-RECORD REPLACING NUMERIC DATA BY 3 ALPHANUMERIC DATA BY X. This above statement Moves 3 TO WS-NUMBER AND X is being moved to WS-NAME and WS-LOB. COMP COMP-1 COMP-2 COMP-3

COMP COMP-1 COMP-2 COMP-3

COMP: Normally, a computer can store data in more than one internal form. In COBOL, a programmer is allowed to specify the internal form of the data item so as to facilitate its use in the most efficient manner. There are only two general forms of internal representation namely COMPUTATIONAL and DISPLAY. Only numeric data items can be specified as USAGE IS COMPUTATIONAL and the name itself suggests a data item specified as USAGE IS COMPUTATIONAL can take part in arithmetic operations more efficiently and any data item can be specified as USAGE IS DISPLAY. If we omit Usage clause compiler assume DISPLAY as default. In COMP usage Data is stored as Pure Binary format internally. Depending on the size of the data item, it can be stored either in a half-word (2 bytes with range 32,768 to +32767) or fullword (4 bytes with range 2,147,483,648 to 2,147,483,647). The PICTURE Clause of a COMPUTATIONAL data item should not contain any character other than 9 or S. Example :

01 WS--DS-HDR-LEN

PIC S9(02)

COMP.

Which occupies 2 bytes and data stored as Pure binary format internally. Data name length 9(01) to 9(04) 9(05) to 9(09) S9(10) to S9(18) COMP-1: In this case the data item will be represented in one word in the floating point form the number is actually represented in hexadecimal format and is suitable for arithmetic operations. The PICTURE Clause cannot be specified for COMP-1 items. COMP-1 takes 4 bytes of storage. COMP-2: This is same as COMP-1, except that the data is represented internally in two words. The advantage is that this increases the precision of the data, which means that more significant digits are available. Similar to COMP-1, The PICTURE Clause cannot be specified for COMP-2 items also. COMP-1 takes 8 bytes of storage. Length in COBOL 2 bytes 4 bytes 8 bytes

COMP-2 is more precision than COMP-1.

Interview Question : Why COMP-1, COMP-2 dont have PIC clause ? PIC creates relation between data name and data type. Whereas here data is numeric and length is predefined as one word floating for COMP-1 and double word floating for COMP-3. So no relation is required using PIC clause.

COMP-3: In this case the data is represented in the decimal form, but one digit takes half a byte. The sign is stored separately as the rightmost half a byte character. Find Comp-3 storage in bytes: Length of variable/2, if this is not pure number then it takes immediate next number of bytes. For example S9(06) : which takes 4 bytes.

for sign (S) and variable length is 6 which takes 3 bytes. total is 3 so its immediate number is 4. Additional added byte is called slack byte.

COMP-3 Picture clause S9(1) COMP-3 S9(2) COMP-3 S9(3) COMP-3 S9(4) COMP-3 S9(5) COMP-3 S9(6) COMP-3 S9(7) COMP-3 S9(8) COMP-3 S9(9) COMP-3 S9(10) COMP-3 S9(11) COMP-3 S9(12) COMP-3 S9(13) COMP-3 S9(14) COMP-3 S9(15) COMP-3 S9(16) COMP-3 S9(17) COMP-3 S9(18) COMP-3

Number of bytes occupied by the field 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10

1. The USAGE Clause can be specified on data items defined with any level number. 2. The USAGE of a group item is valid for all its sub items.

Question : How to read COMP-3 value in a sequential file? You need to use HEX ON commmand to see COMP-3 values in PS When you use this command it will show two lines per each record. You need to read the comp-3 value from left, top to bottom (in two lines) and then move to second character read top to bottom. COMP-3 Example : +87634 will be displayed as

864 73C -4567 will be displayed as 057 46D last characters represents sign. if last character is C or F, that denotes a positive sign. If last character is D , that denotes a negative sign.

Question : Conversion of comp-3 to character Displaying COMP-3 characters: Before displaying COMP-3 Move the data to usage display variable then display. If it holds Sign then Use SIGN LEADING SEPARATE which uses one extra byte for sign and sign will be displayed separately. 01 01 WS-NUMBER PIC S9(03) COMP-3. WS-NUMBER1 PIC S9(03) SIGN LEADING SEPARATE.

MOVE WS-NUMBWER TO WS-NUMBER1 DISPLAY WS-NUMBER1 displays data properly.

Question : Can i Move LOW-VALUES TO COMP-3 variable? Moving LOW-VALUES is not possible. This will give compiler error.

File Handling in Cobol

File Handling in COBOL File: A file is a collection of data related to a set of entities and typically exists on a magnetic tape or a disk. We refer file as PS in Mainframe environment. In file data is organized as records. Each record is divided into set of fields. For example data related to employee file which consists of employee ID, employee name, employee Account. 01 WS-EMP-REC. 02 WS-EMP-ID 02 WS-EMP-NAME 02 WS-EMP-ACCT

PIC X(07). PIC X(20). PIC X(06).

In this above file data is organized as multiple records each consists of 33 bytes. Data name WS-EMP-REC is referred as record. WS-EMP-ID, WS-EMP-NAME and WS-EMP-ACCT is referred as Fields. Cumulative size of all fields is considered as record length. A file can be classified as fixed or variable length files. In fixed length file, size of all records must be same but in variable length file record length can be vary upon some fields which are not common. The above referred WS-EMP-REC is an example for fixed length file. Files are further classified into 3 types. 1. SEQUENTIAL ORGANIZATION 2. INDEX SEQUENTIAL ORGANIZATION 3. RELATIVE ORGANIZATION Sequential organization: In mainframe environment we have 2 types of sequential files. 1. 2. Flat file (NON-VSAM Sequential file) Entry sequential data set (VSAM ESDS)

Both type of files created using different type of Storage organization. Sequential files: The records are stored in the file in the

same order in which they are entered. Here, the records can be accessed only sequentially. To process any record, one has to read all its preceding records. Further, records cannot be inserted or deleted. Sequential files are simplest to handle, they are highly inflexible as they do not facilitate insertion and deletion of records. File opened with Extend Mode appends the writing records at the end of the file. In COBOL program there is no much difference between these two types. If you are accessing ESDS VSAM file, then in COBOL program should coded like this. SELECT FILE ASSIGN TO AS-DDNAME. Actually DD name matches with JCL DD Name. But in COBOL Program DDNAMEs should be prefixed with AS- (In case of VSAM ESDS file) . If you are not doing that then an S213 ABEND might occur when attempting to open data set. INDEX SEQUENTIAL ORGANIZATION: Records in this file are stored based on a key field which is part of record and this is also called as index. Records in this file are accessible in sequential , dynamic & random mode. An index sequential file is conceptually made up of two files, a data file and an index file. Though the records are stored in the order in which they are entered, a sorted index is maintained which relates the key value to the position of the record in the file and hence provides a way to access the records both sequentially and randomly.

RELATIVE ORGANIZATION: This file is divided into fixed number of slots each slot has one record. This is identified as relative record number. The access method stores and retrieves a record, based on its relative record number. Records can be accessed as sequentially or randomly or dynamically. This relative files faster access compared to other 2 organizations. But if some of the intermediate records are missing, they occupy space.

File declaration in COBOL Program: To make use of files in COBOL program starts in FILE-CONTROL in ENVIRONMENT DIVISION. SELECT [OPTIONAL]logical-file-name ASSIGN TO physical-file-name. [; RESERVE integer {AREA, AREAS}] [; ORGANIZATION IS SEQUENTIAL] [; ACCESS MODE IS SEQUENTIAL] [; FILE STATUS IS data-name]

For example... SELECT EMPFILE ASSIGN TO EMPFILEO. Here in COBOL Program we refer this file as EMPFILE but physically there is no file exists with this name. For any kind of operation against the file inside the program, make sure you use Logical name only i.e. EMPFILE. Above sentence EMPFILEO is a mapping that connects from logical file to physical file. It means whatever operations we do in COBOL program against the logical file EMPFILE those will be reflected on Physical file.

In JCL...This file is referred as //EMPFILEO DD DSN=DG11.CAPHYD.EMPHYD

Physically data stored in DG11.CAPHYD.EMPHYD in system. Operations against EMPFILE will be reflected in DG11.CAPHYD.EMPHYD. You must specify SELECT OPTIONAL for those input files that are not necessarily present each time the object program is executed. Files with OPTIONAL option can be opened using INPUT,I-O, EXTEND mode.

RESERVE integer {AREA, AREAS} RESERVE 2 AREAS this instructs system about allocation of buffers while processing large files stored on disk or tapes, it is inefficient to read or write single record at a time. Instead, the usual practice is to group a number of consecutive records to form what is known as a physical record or a block the number of records in a block is termed as the blocking factor. There are two advantages of blocking logical records into a physical record. Firstly, it results in saving the I/O time required for processing a file and secondly it results in saving the storage space for a file. For example to search for a record file has to read sequentially, if each record is reading from Disk at a time which is time consuming in order to speed the access of records, a couple records are read from DISK and keep in intermediate storage called buffer. For sequential access allocation of large block sizes faster the access. For random access a small block size faster the access of records. ORGANIZATION IS SEQUENTIAL:

It describes the file organization. For sequential files ORGANIZATION IS SEQUENTIAL For Indexed files ORGANIZATION IS INDEXED. For relative files ORGANIZATION IS RELATIVE. ACCESS MODE IS SEQUENTIAL: This sentence identifies the in which mode the file is going to be accessed. For sequential access For random access For Dynamic access ACCESS MODE IS SEQUENTIAL ACCESS MODE IS RANDOM ACCESS MODE IS DYNAMIC

Dynamic access is a combination of random and sequential access.

FILE STATUS IS data-name: File status is used to identify the status of each operation that is performed against the file. For instance. FILE STATUS IS WS-STATUS. This WS-STATUS data name declares explicitly in Working storage section. 01 WS-STATUS PIC X(02).

After performing each operation on file it is good practice to check the file status code whether the operation was successful or not, based on this appropriate action is performed. In file handling 00 is identified as successful execution. FILE STATUE 00 10 22 23 Meaning operation sucessful End of record Duplicate key Record Not Found

For more file status code click here

File record description is declared in FILE SECTION. In file section FD EMPFILE [; RECORD CONTAINS integer-1 CHARACTERS] [; BLOCK CONTAINS integer-2 {RECORDS, CHARACTERS}] [; DATA {RECORD IS, RECORDS ARE} data-name-1 [, data-name-2] . . .]

01 WS-EMP-REC. 02 WS-EMP-ID 02 WS-EMP-NAME 02 WS-EMP-ACCT

PIC X(07). PIC X(20). PIC X(06).

FD is abbreviated from FILE DESCRIPTION. The RECORD CONTAINS clause specifies the size of the logical records. Here RECORD CONTAINS 33 CHARCTERS The BLOCK CONTAINS clause specifies the size of the physical records. If the records in the file are not blocked, BLOCK CONTAINS clause can be omitted. When it is omitted, the compiler assumes that records are not blocked. Even if each physical record contains only one complete logical record, coding BLOCK CONTAINS 1 RECORD would result in fixed blocked records. The DATA RECORD clause specifies the record names defined for the file. Here DATA RECORD IS WS-EMP-REC.

File Processing

File Processing All file processing operations are held in procedure division. File Operations: OPEN READ WRITE REWRITE CLOSE OPEN EMPFILE:

OPEN {INPUT, OUTPUT, EXTEND, I-O} file-name-1 [, file-name-2] . . . The OPEN statement initiates the processing of files. The successful execution of an OPEN statement determines the availability of the file for processing. The successful execution of the OPEN statement makes the associated record area available to the program; it does not obtain or release the first data record. If the FILE STATUS clause is specified in the FILE-CONTROL entry, the associated operation status is updated when the OPEN statement is executed. A sequential file can be opened in one of the following four modes. INPUT, OUTPUT, EXTEND and I-O. A file can be opened in the INPUT mode only if it already exists. Such a file becomes an input file from which records can be read sequentially. When a file is to be created for the first time, it must be opened in the OUTPUT mode. File can be written in this mode. The EXTEND mode also opens a file for writing, but the file pointer is positioned after the end of the last record. Thus any records written will get appended to the file. A file is opened in the I-O mode when it needs to be updated. This mode provides both reading and rewriting of records.

CLOSE EMPFILE: This statement terminates processing CLOSE Statement is optional and STOP File if it is not explicitly closed. termination of link between Physical READ EMPFILE: If a file is opened in INPUT or I-O mode then a READ statement make available Next logical record for processing. The primary function of the READ statement is to fetch records from a file and place the file pointer at an appropriate position after READ; it performs certain checks to ensure proper execution of the program. READ EMPFILE END-READ AT END imperative statement. of file. In COBOL-85 this RUN automatically closes the This CLOSE statement means file and logical file.

If the file reached end of the file and if program tries to read a record then AT END condition satisfy and imperative statement will performed.

If INTO condition specified like READ EMPFILE INTO WS-RECORD. Here WS-RECORD is data division data name. Program read the file and places record into WS-RECORD. WRITE statement: WRITE CAPGEMINI-REC FROM WS-RECORD END-WRITE. File opened in OUTPUT or EXTEND mode then we can use WRITE statement to write records into the file. If from is used then the data in WS-RECORD is moved to record and writing take place. If FROM is omitted then Data moved to record name will be written into file. If we are reading file we refer file name in READ statement, where as while writing we refer record name with WRITE command.

REWRITE statement: REWRITE command is used to update a record in a file. If file is opened in I-O mode then only we can use REWRITE command on that file. This REWRITE is not available in Sequential file. Before using REWRITE command, corresponding record should be read. A Sample COBOL Program that READ a Sequential files and Write into another file.

Sample:
IDENTIFICATION DIVISION. PROGRAM-ID. TESTCOBL. AUTHOR. TESTTEST. DATE-WRITTEN. 19-NOV-2010. DATE-COMPILED. ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT WS-INFILE ASSIGN TO INPIWS01 FILE STATUS IS WS-INFILE-SW. DATA DIVISION. FILE SECTION. FD WS-INFILE. 01 INP-EMP-REC. 05 INP-EMPID 05 INP-EMPID 05 INP-EMP-NAME

PIC X(08). PIC X(08). PIC X(15).

05 INP-EMP-LOB 05 FILLER

PIC X(10). PIC X(47).

WORKING-STORAGE SECTION. 01 WS-INFILE-SW PIC X(02) VALUE SPACES. 88 WS-INFILE-SUCESS VALUE '00'. 88 WS-INFILE-EOF VALUE '10'. 01 WS-INP-EMP-REC. 05 WS-INP-EMPID PIC X(08). 05 WS-INP-EMP-NAME PIC X(15). 05 WS-INP-EMP-LOB PIC X(10). 05 FILLER PIC X(47). 01 WS-EOF-SW PIC X(01) VALUE 'N'. 88 WS-EOF-NO VALUE 'N'. 88 WS-EOF-YES VALUE 'Y'. PROCEDURE DIVISION. A1000-MAIN-PARA. PERFORM A2000-OPEN-PARA THRU A200-EXIT. PERFORM A3000-INPUT-PARA THRU A300-EXIT. PERFORM A4000-INSERT-PARA THRU A400-EXIT. PERFORM A5000-CLOSE-PARA THRU A500-EXIT. STOP RUN. A100-EXIT. EXIT. A2000-OPEN-PARA. INITIALIZE WS-INFILE-SW WS-INP-EMP-REC OPEN OUTPUT WS-INFILE IF WS-INFILE-SUCESS DISPLAY "FILE OPEN SUCCESSFUL" ELSE DISPLAY "FILE OPENING ERROR" GO TO A100-EXIT END-IF. A200-EXIT. EXIT. A3000-INPUT-PARA. ACCEPT WS-INP-EMPID. ACCEPT WS-INP-EMP-NAME. ACCEPT WS-INP-EMP-LOB. DISPLAY WS-INP-EMPID WS-INP-EMP-NAME . A300-EXIT. EXIT. A4000-INSERT-PARA. WRITE INP-EMP-REC FROM WS-INP-EMP-REC. A400-EXIT. EXIT. A5000-CLOSE-PARA. CLOSE WS-INFILE. A500-EXIT. EXIT. WS-EOF-SW.

WS-INP-EMP-LOB

INDEXED File Processing

INDEXED File Processing INDEX SEQUENTIAL ORGANIZATION: Records in this file are stored based on a key field which is part of record and this is also called as index. Records in this file are accessible in sequential , dynamic & random mode. An index sequential file is conceptually made up of two files, a data file and an index file. INDEXED FILE PROCESSING: SELECT logical-file-name ASSIGN TO physical-file-name [ORGANIZATION IS INDEXED] [ACCESS MODE IS {SEQUENTIAL, RANDOM, DYNAMIC}] [RECORD KEY IS data-name-1] [ALTERNATE RECORD KEY is data-name-2 [WITH DUPLICATES]] [FILE STATUS IS data-name-2] Records in this file are stored based on a key field which is part of record and this is also called as index and this organization is called INDEXED. Here RECORD KEY clause specifies the index based on which the file is sequenced. The data-name-1 must be an alphanumeric field within the record description for the file. In case there are multiple record descriptions, the key field from any of the descriptions can be used. Index sequential file is sorted and maintained on the primary key, the records can also be accessed using the ALTERNATE KEY. Further, the ALTERNATE KEY data item may also find duplicate entries for records. To incorporate this, specify WITH DUPLICATES option.

READ Statement

READ File name [NEXT RECORD] INTO data-name [KEY is data-name] [INVALID KEY imperative statements] Here, the data-name in the KEY phrase key or one of the alternate keys. The fied when an index sequential file is INVALID KEY condition arises when the in the file. must be either the primary option NEXT RECORD is specibeing read sequentially specified key is not found

WRITE statement: If a file is opened in the OUTPUT mode, then the WRITE statement releases the records to the file in the ascending order of the record key values regardless of the access mode. ACCESS mode SEQUENTIAL is specified and the file is opened OUTPUT and the value of the primary key is not greater than that of the previous record. The file is opened in the OUTPUT or I-O modes and the value of the primary record key is equal to that of an already existing record. WRITE record-name [FROM data-name] {INVALID KEY imperative statements}

REWRITE statement: REWRITE statement requires that the file must be opened in the I-O mode and if the SEQUENTIAL ACCESS mode is specified, the value of the RECORD KEY being replaced must be equal to that of the record last read from the file. The INVALID KEY condition arises in the following situations. The access mode is sequential and the value contained in the RECORD KEY of the record to be replaced is not equal to the value of the RECORD KEY data item of the last-retrieved record from the file. The value of an ALTERNATE RECORD KEY data item for which DUPLICATES is not specified is equal to that of a record already in the file. Format: REWRITE record-name [FROM data-name] {INVALID KEY imperative statements}

DELETE statement: To delete a record from an index sequential file, the file must be opened in the I-O mode. If the access mode is sequential, then the INVALID KEY phrase should not be specified. Instead, the last I/O statement executed on the file must be a successful READ statement for the record specified. IF the access mode is RANDOM or DYNAMIC, then the record to be deleted is determined by the value of the RECORD KEY. In this case the INVALID KEY phrase should be specified. The INVALID KEY condition arises if the specified is not found in the file. DELETE file-name RECORD {INVALID KEY imperative statements}

START statement: The START statement provides positioning the file pointer at a specific location within an index Sequential file for subsequent sequential record retrieval. The access mode must be SEQUENTIAL or DYNAMIC and the file must be opened in the INPUT or I-O modes. Further, if the KEY phrase is specified, the file pointer is positioned at the logical record in the file whose key field satisfies the comparison and if it is omitted, then KEY IS EQUAL (to the RECORD KEY) is implied. If the comparison is not satisfied by any record in the file, an invalid key condition exists; the position of the file position indicator is undefined and (if specified) the INVALID KEY imperative-statement is executed. START file-name [KEY is {=, <, >} data-name] [INVALID KEY imperative statements] click here to see the sample indexed cobol program

How to define VSAM file. How to write records into VSAM file.
//B19895J JOB DEFINEC,'GSS', // CLASS=X,MSGCLASS=T,NOTIFY=&SYSUID //VIDCOPY EXEC PGM=IDCAMS //SYSPRINT DD SYSOUT=* //SYSIN DD * DEFINE CLUSTER( NAME(B19895.VSAM.CLST) VOL (TSU151) -

FREESPACE (10 10) RECSZ (20 20) CISZ(200) KEYS(5 0) INDEXED) DATA (NAME(B19895.VSAM.CLST.DATA))INDEX( NAME(B19895.VSAM.CLST.INDEX)) /* //B19895J JOB COMPILE,'GSS', // CLASS=X,MSGCLASS=T,NOTIFY=&SYSUID, // TIME=(0001,00) //JOBLIB DD DSN=PC1G0.PDS.GRD1HK.UTESTB.AP.V011.LOADLIB,DISP=SHR //TEST EXEC PGM=TSTCOBL //SYSIN DD * 34462VASANTA KUMRTDI /* //INFILE DD DSN=B19895.VSAM.CLST,DISP=MOD // IDENTIFICATION DIVISION. PROGRAM-ID. TESTCOBL. AUTHOR. TESTTEST. DATE-WRITTEN. 19-NOV-2010. DATE-COMPILED. ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT WS-INFILE ASSIGN TO INFILE ORGANIZATION IS INDEXED ACCESS MODE IS RANDOM RECORD KEY IS INP-EMPID FILE STATUS IS WS-INFILE-SW. DATA DIVISION. FILE SECTION. FD WS-INFILE. 01 INP-EMP-REC. 05 INP-EMPID 05 INP-EMPNAME 05 INP-EMP-LOB

PIC X(05). PIC X(12). PIC X(03).

WORKING-STORAGE SECTION. 01 WS-INFILE-SW PIC X(02) VALUE SPACES. 88 WS-INFILE-SUCESS VALUE '00'. 88 WS-INFILE-EOF VALUE '10'. 01 WS-INP-EMP-REC PIC X(20). 01 WS-EOF-SW PIC X(01) VALUE 'N'. 88 WS-EOF-NO VALUE 'N'. 88 WS-EOF-YES VALUE 'Y'.

PROCEDURE DIVISION. A1000-MAIN-PARA. PERFORM A2000-OPEN-PARA THRU A200-EXIT. PERFORM A3000-INPUT-PARA THRU A300-EXIT. PERFORM A4000-INSERT-PARA THRU A400-EXIT. PERFORM A5000-CLOSE-PARA THRU A500-EXIT. STOP RUN. A100-EXIT. EXIT. A2000-OPEN-PARA. INITIALIZE WS-INFILE-SW WS-INP-EMP-REC OPEN OUTPUT WS-INFILE. IF WS-INFILE-SUCESS DISPLAY "FILE OPEN SUCCESSFUL" ELSE DISPLAY "FILE OPENING ERROR" GO TO A100-EXIT END-IF. A200-EXIT. EXIT. A3000-INPUT-PARA. ACCEPT WS-INP-EMP-REC. DISPLAY WS-INP-EMP-REC. . A300-EXIT. EXIT. A4000-INSERT-PARA. WRITE INP-EMP-REC FROM WS-INP-EMP-REC. A400-EXIT. EXIT. A5000-CLOSE-PARA. CLOSE WS-INFILE. . A500-EXIT. EXIT. RELATIVE File Processing WS-EOF-SW.

RELATIVE File Processing RELATIVE ORGANIZATION: This file is divided into fixed number of slots each slot has one record. This is identified as relative record number. The access method stores and retrieves a record, based on its relative record number. Records can be accessed as sequentially or randomly or dynamically. This relative files faster access compared to other 2 organizations. File description entries for a Relative file: SELECT logical-file-name ASSIGN TO physical-file-name [RESERVE integer {AREA, AREAS}] [ORGANIZATION IS RELATIVE] [ACCESS MODE IS {SEQUENTIAL {RANDOM, DYNAMIC}, RELATIVE KEY is dataname-1}] [FILE STATUS IS data-name-2] Here records are stored based on unique record number which is not part of record is called relative organization. Here, RELATIVE KEY must be specified when the access mode is RANDOM or DYNAMIC. The dataname-1 is called the relative key data item and it indicates the field that contains the relative record number. This dataname-1 is not part of record description. The programmer must place an appropriate value in the relative key data item while accessing a record randomly. READ file-name RECORD [INTO identifier] [; AT END imperative statements] [END-READ] This format is applicable to SEQUENTIAL ACCESS MODE. If the RELATIVE KEY phrase is also specified with the ACCESS MODE SEQUENTIAL clause, then upon the successful completion of the READ statement, the relative record number of the accessed record is placed in the relative key data item. Format 2: READ file-name RECORD [INTO identifier] [; INVALID KEY imperative statements] This format is applicable when ACCESS MODE is either RANDOM or DYNAMIC. In this case the record to be read is identified from the contents of the RELATIVE KEY data item. The INVALID KEY case arises when the READ is unsuccessful.

Format 3: READ file-name [NEXT] RECORD [INTO identifier] [; INVALID KEY imperative statements]

This format is applicable when the ACCESS MODE is DYNAMIC and the records are to read sequentially. Here the NEXT RECORD is identified according to the following rules. The READ NEXT statement is the first statement to be executed after the OPEN statement, Then the NEXT RECORD is the first record itself. The READ NEXT statement follows a successful execution of another READ NEXT on the same file; the NEXT RECORD is the record following the one previously read record.

WRITE statement: If a file is opened in the OUTPUT mode, then the WRITE statement releases the records to the file in the ascending order of the record key values regardless of the access mode. The INVALID KEY condition arises for an index sequential file in the following situations. Format: WRITE record-name [FROM data-name] {INVALID KEY imperative statements} {NOT INALID KEY imperative statements} [END-WRITE]

REWRITE statement: The REWRITE statement requires that the file must be opened in the I-O mode and if the SEQUENTIAL ACCESS MODE is specified, the value of the RECORD KEY being replaced must be equal to that of the record last read from the file. The INVALID key condition arises in the following situations. The access mode is sequential and the value contained in the RECORD KEY of the record to be replaced does not equal the value of the RECORD KEY data item of the last-retrieved record from the file. The value of an ALTERNATE RECORD KEY data item for which DUPLICATES is not specified is equal to that of a record already in the file. Format: REWRITE record-name [FROM data-name]

{INVALID KEY imperative statements}

DELETE statement: If access mode is sequential, then the INVALID KEY phrase should not be specified. Instead, the last I/O statement executed on the file must be a successful READ statement for the record specified. IF the access mode is RANDOM or DYNAMIC, then the record to be deleted is determined by the value of the RECORD KEY. In this case the INVALID KEY phrase should be specified. The INVALID KEY condition arises if the specified is not found in the file. Format: DELETE file-name RECORD {INVALID KEY imperative statements} {NOT INVALID KEY imperative statements} [END-REWRITE]

START statement: The START statement enables the programmer to position the relative file at some specified point so that subsequent sequential operations on the file can start from this point instead of the beginning. They KEY IS phrase indicates how the file is to be positioned. The data-name in this phrase must be the data-name in the RELATIVE KEY phrase of the SELECT . . . ASSIGN clause. When the EQUAL TO or NOT LESS THAN condition is specified, the file is positioned at the point indicated by the relative key-data item. When the GREATER THAN condition is specified, the file is positioned at the next relative position of the position indicated by the RELATIVE KEY data item.

START file-name Key is OPERATOR data name [; INVALID KEY imperative statements] Below is sample COBOL program using relative file click here to see the sample RRDS cobol program

How to define RRDS file. How to write records into VSAM RRDS file.
//B19895J JOB DEFINEC,'GSS',

// CLASS=X,MSGCLASS=T,NOTIFY=&SYSUID //VIDCOPY EXEC PGM=IDCAMS //SYSPRINT DD SYSOUT=* //SYSIN DD * DEFINE CLUSTER( NAME(B19895.VSAM.RRCL) VOL (TSU151) CYLINDERS (1 2) CISZ(200) NUMBERED RECORDSIZE (20 20)) DATA (NAME(B19895.VSAM.RRDS.DATA))INDEX( NAME(B19895.VSAM.RRDS.INDEX)) /*

IDENTIFICATION DIVISION. PROGRAM-ID. TESTCOBL. AUTHOR. TESTTEST. DATE-WRITTEN. 19-NOV-2010. DATE-COMPILED. ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT WS-INFILE ASSIGN TO INFILE ORGANIZATION IS RELATIVE ACCESS MODE IS RANDOM RELATIVE KEY IS RELKEY FILE STATUS IS WS-INFILE-SW. DATA DIVISION. FILE SECTION. FD WS-INFILE. 01 INP-EMP-REC. 05 INP-EMPID PIC X(05). 05 INP-EMPNAME PIC X(12). 05 INP-EMP-LOB PIC X(03). WORKING-STORAGE SECTION. 01 WS-INFILE-SW PIC X(02) VALUE SPACES. 88 WS-INFILE-SUCESS VALUE '00'. 88 WS-INFILE-EOF VALUE '10'. 01 WS-INP-EMP-REC PIC X(20). 01 RELKEY PIC 9(02). PROCEDURE DIVISION. A1000-MAIN-PARA. PERFORM A2000-OPEN-PARA THRU A200-EXIT. PERFORM A3000-INPUT-PARA THRU A300-EXIT. PERFORM A4000-INSERT-PARA THRU A400-EXIT. PERFORM A5000-CLOSE-PARA THRU A500-EXIT. STOP RUN. A100-EXIT. EXIT.

A2000-OPEN-PARA. INITIALIZE WS-INFILE-SW WS-INP-EMP-REC. OPEN OUTPUT WS-INFILE. IF WS-INFILE-SUCESS DISPLAY "FILE OPEN SUCCESSFUL" ELSE DISPLAY "FILE OPENING ERROR" GO TO A100-EXIT END-IF. A200-EXIT. EXIT. A3000-INPUT-PARA. ACCEPT WS-INP-EMP-REC. DISPLAY WS-INP-EMP-REC. . A300-EXIT. EXIT. A4000-INSERT-PARA. WRITE INP-EMP-REC FROM WS-INP-EMP-REC. A400-EXIT. EXIT. A5000-CLOSE-PARA. CLOSE WS-INFILE. . A500-EXIT. EXIT.

FREE COBOL COMPILERS

zCOBOL cOmpiler zCOBOL is an open source portable mainframe COBOL compiler available as part of the z390 open source portable mainframe assembler for Windows or Linux starting with z390 v1.5.00. You can download z390 and zcobol in InstallShield format for Windows for file image format for Linux from www.z390.org. You will also need the J2SE Java runtime which you can download from Sun Developer Network. The latest release of zcobol v1.5.01 has been regression tested with J2SE 6 update 16. Be sure to remove any old obsolete versions of J2SE such as 1.4 or 1.5 which may

zcobol

conflict with current version.

Once you have installed z390 with

and J2SE runtime, then you can start the z390 GUI interface or command line interface and enter the following command to compile, link, and execute the COBOL hello world demo on Windows or Linux:

TinyCOBOL Compiler TinyCOBOL is a COBOL compiler being developed by members of the free software community. The compiler was tiny, and accept only a subset of COBOL 74 standard, but could easily be expanded to full compliance. There were no "MOVE CORRESPONDING" nor "ALTER" statements.

Cobol For GCC - a GNU project - Free Software Foundation COBOL For GCC is a project to produce a free COBOL compiler compliant with the COBOL 85 Standard, integrated into the GNU Compiler Collection (GCC).

COBOL12 compiler COBOL12 is a 16-bit COBOL compiler that runs under DOS or Windows. The compiler was originally based on Ansi74, but has undergone many changes since its inception. It does not include some features such as SORT and STRING, but it has many non-standard features included.

Cevela MX COBOL 3.0 compiler User friendly simple and compact compiler in MS Windows environment for small tasks and training of basic programming skills in Cobol language. It is based on ANSI-74 COBOL with some features from ANSI-85 (initialize, end-if, endperform) and ISO 1989:2002 (scereen section). It's output is source in C which can be very easy

compiled and linked to EXE-form with automatic following free historical Borland TC 2.01 compiler packet. There are no supplemented C-libraries and no C-language knowledge necessary.

COMMERCIAL COBOL COMPILERS

Microfocus COBOL

( Free cobol compiler trail )

You need to fill a form to get Microfocus cobol compiler trail version for windows. VerY good GUI avaiable with this tool.

IBM COBOL Compiler for Windows COBOL for Windows, V7.6 is a cost-effective alternative for customers of third-party applications requiring COBOL compilers. COBOL compiler: For customers of third-party applications for developing and deploying COBOL applications on Microsoft Windows

Fujitsu COBOL Compiler Fujitsu used to provide an early version (V3) of their COBOL compiler for free. It worked well but didn't have many features that were introduced in later versions so it didn't threaten sales for business use. That version, created in the early '90s, no longer works on today's computers and versions of Windows and is no longer supported. It has not made sense to offer more recent versions in this way. Today Fujitsu NetCOBOL compilers are only sold at their full retail price - a price that is set by the value delivered for business use. This price is usually beyond the reach of most students and academic institutions.

You might also like