Top Banner
COBOL is a high-level programming language first developed by the CODASYL Committee (Conference on Data Systems Languages) in 1960. Since then, responsibility for developing new COBOL standards has been assumed by the American National Standards Institute (ANSI). Three ANSI standards for COBOL have been produced: in 1968, 1974 and 1985. A new COBOL standard introducing object-oriented programming to COBOL, is due within the next few years. The word COBOL is an acronym that stands for COmmon Business Oriented Language. As the the expanded acronym indicates, COBOL is designed for developing business, typically file-oriented, applications. It is not designed for writing systems programs. For instance you would not develop an operating system or a compiler using COBOL. For over four decades COBOL has been the dominant programming language in the business computing domain. In that time it it has seen off the challenges of a number of other languages such as PL1, Algol68, Pascal, Modula, Ada, C, C++. All these languages have found a niche but none has yet displaced COBOL. Two recent challengers though, Java and Visual Basic, are proving to be serious contenders. COBOL's dominance in underlined by the reports from the Gartner group. In 1997 they estimated that there were about 300 billion lines of computer code in use in the world. Of that they estimated that about 80% (240 billion lines) were in COBOL and 20% (60 billion lines) were written in all the other computer languages combined [Brown]. In 1999 they reported that over 50% of all new mission-critical applications were still being done in COBOL and their recent estimates indicate that through 2004-2005 15% of all new applications (5 billion lines) will be developed in COBOL while 80% of all deployed applications will include extensions to existing legacy (usually COBOL) programs. Gartner estimates for 2002 are that there are about two million COBOL programmers world-wide compared to about about one million Java
83
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: cobol

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

For over four decades COBOL has been the dominant programming language inthe business computing domain. In that time it it has seen off thechallenges of a number of other languages such as PL1, Algol68, Pascal,Modula, Ada, C, C++. All these languages have found a niche but none hasyet displaced COBOL. Two recent challengers though, Java and Visual Basic,are proving to be serious contenders.COBOL's dominance in underlined by the reports from the Gartner group.In 1997 they estimated that there were about 300 billion lines of computercode in use in the world. Of that they estimated that about 80% (240billion lines) were in COBOL and 20% (60 billion lines) were written inall the other computer languages combined [Brown].In 1999 they reported that over 50% of all new mission-criticalapplications were still being done in COBOL and their recent estimatesindicate that through 2004-2005 15% of all new applications (5 billionlines) will be developed in COBOL while 80% of all deployed applicationswill include extensions to existing legacy (usually COBOL) programs.Gartner estimates for 2002 are that there are about two million COBOLprogrammers world-wide compared to about about one million Javaprogrammers and one million C++ programmers.

COBOL is self-documentingOne of the design goals for COBOL was to make it possible fornon-programmers such as supervisors, managers and users, to read andunderstand COBOL code. As a result, COBOL contains such English-likestructural elements as verbs, clauses, sentences, sections and divisions.As it happens, this design goal was not realized. Managers and usersnowadays do not read COBOL programs. Computer programs are just toocomplex for most laymen to understand them, however familiar the syntacticelements. But the design goal and its effect on COBOL syntax has had oneimportant side-effect. It has made COBOL the most readable, understandableand self-documenting programming language in use today. It has also madeit the most verbose.It is easy for programmers unused to the business programming paradigm,where programming with a view to ease of maintenance is very important, todismiss the advantage that COBOL's readability imparts. Not only does this

Page 2: cobol

readability generally assist the maintenance process but the older aprogram gets the more valuable this readability becomes.When programs are new, both the in-program comments and the externaldocumentation accurately reflect the program code. But over time, as moreand more revisions are applied to the code, it gets out of step with thedocumentation until the documentation is actually a hindrance tomaintenance rather than a help. The self-documenting nature of COBOL meansthat this problem is not as severe with COBOL programs as it is with otherlanguagesReaders who are familiar with C or C++ or Java might want to consider howdifficult it becomes to maintain programs written in these languages. Cprograms that you have written yourself are difficult enough to understandwhen you come back to them six months later. Consider how much moredifficult it would be to understand a program that had been writtenfifteen years previously, by someone else, and which had since beenamended and added to by so many others that the documentation no longeraccurately reflects the program code. This is a nightmare still awaitingmaintenance programmers of the futureCOBOL is simpleCOBOL is a simple language (no pointers, no user defined functions, nouser defined types) with a limited scope of function. It encourages asimple straightforward programming style. Curiously enough though, despiteits limitations, COBOL has proven itself to be well suited to its targetedproblem domain (business computing). Most COBOL programs operate in adomain where the program complexity lies in the business rules that haveto be encoded rather than in the sophistication of the data structures oralgorithms required. And in cases where sophisticated algorithms arerequired COBOL usually meets the need with an appropriate verb such as theSORT and the SEARCH.

B.C.A. (Regular) SEMESTER - I Effective from 2007-08 onwardsCORE-1 COBOL PROGRAMMING

Subject Description: This subject deals the programming concepts using COBOL language.Goal: To learn about COBOL programming language.Objective: On successful completion of this subject the students should have skills for writing programs for business applications and file handling concepts.

- - - - -UNIT-I: Introduction to COBOL: COBOL words - Literals - Structure of COBOL Program - COBOLCoding Sheet-IDENTIFICATION DIVISION- ENVIRONMENT DIVISION – DATA DIVISION –Editing and Non-editing Picture Clauses – Level Numbers – VALUE and FILLER Clause.UNIT-II: PROCEDURE DIVISION – Data Movement Verb – Arithmetic Verbs : Add, Subtract, Multiply, Divide, Compute – Input/Output Statement: Accept, Display Control Verbs: GOTO – GOTODepending on – Stop Run – CORRESPONDING Option - ROUNDED option - ON SIZE ERROR option - Simple Programs Using Above Verbs.UNIT-III: Conditional Statements: If Statement – Nested if statement – Sign Condition – Class Condition- Condition Name – Compound Condition- PERFORM Statements, More about DATA Division: RENAMES-REDEFINES – Simple Programs Using the above Verbs.

Page 3: cobol

UNIT-IV: Files in COBOL: Sequential – Relative – Indexed Sequential - Random files – File description and Record description entries - Input/Output Verbs: Open, read, write, rewrite, Close, Delete – Sort Verb – Simple Programs using above Verbs.UNIT-V: Table Handling: Occurs Clause – Two and Multi-Dimensional Tables – Occurs. Indexed by Clause – SET Verb – START and SEARCH Verb – Random Files-Keys & Their Importance – INVALID KEY Clause – SCREEN SECTION - Simple Programs using above Verbs.

TEXT BOOK:1. COBOL PROGRAMMING, M.K. ROY & D.GHOSH DASTIDAR, 2nd ed, TMH.REFERENCE BOOKS:1. COBOL programming – V. Rajaraman, PHI Pub.2. Introduction To Cobol Programming – Dr. R. Krishnamoorthy, JJ Publications.3. Structured COBOL – Welburn, TMH, 4th Edition.

PRACTICAL LIST

1. Write a COBOL Program to find the sum of individual digits of a 10-digit number until a single digit is produced.

2. Write a COBOL Program to accept the inputs Student Name, Marks for 5 subjects and declarethe result as PASS, if the student gets minimum of 10 marks in each subject, otherwise declareas FAIL.

3. Write a COBOL Program to accept the given date (DDMMYY) and display the result in thefollowing specified format: 030498 as 3rd APR 1998.

4. Write a COBOL Program to display the given three digit number into words using OCCURSclause. (Example: 342 as THREE HUNDRED AND FORTY TWO).

5. Write a COBOL Program to create a student data file STUDENT.DAT, using the followingfields: ROLL-NO, NAME, AGE, YEAR-IN-COLLEGE, SEX, MARKS for 5 subjects.

6. Write a COBOL Program to create the following two files, using the student data fileSTUDENT.DAT (created by Program 5):FILE-1.DAT: List of male students who are studying third yearFILE-2.DAT: List of female students who are studying first year(Use MOVE CORRESPONDING option).

7. Write a COBOL Program to sort the student data file STUDENT.DAT (created by Program 5) in the ascending order of the fields SEX, YEAR-IN-COLLEGE and ROLL-NO (use SORTverb) into SORT.DAT file.

8. Write a COBOL Program to create an Indexed Sequential File EMPLOYEE.DAT for theEmployees of an Organization using the fields: ROLL-NO, NAME, DOB, SEX, BASIC-PAYand DESIGNATION.

Page 4: cobol

9. Write a COBOL Program to update the BASIC-PAY of each employee in the employee data file EMPLOYEE.DAT (created by Program 8) by incrementing 25% of BASIC-PAY.

10. Write a COBOL Program to find the number of male employees whose BASIC-PAY > 4000and number of female employees whose BASIC-PAY < 3000 using the employee data fileEMPLOYEE.DAT (created by Program 8).

11. Write a COBOL Program to create an Inventory data file INVENT.DAT by using the following fields: ITEM-CODE, DESCRIPTION, OPEN-STOCK, PURCHASES, SALES, SAFETYLEVEL and CLOSE-STOCK.

12. Write a COBOL Program to prepare Re-Order Level Statement by using the inventory data file INVENT.DAT (created by Program 11), if the CLOSE-STOCK is less than SAFETY-LEVEL.

1 PROGRAM FOR ADD CORRESPONDINGWrite a simple program to demonstrate Add Corresponding.

IDENTIFICATION DIVISION.PROGRAM-ID.ENVIRONMENT DIVISION.DATA DIVISION.WORKING-STORAGE SECTION.01 REC-1.

02 SNO PIC 9(2) VALUE 11.02 MARK1 PIC 9(2) VALUE 1.

01 REC-2.05 SNO PIC 9(2) VALUE 10.05 MARK2 PIC 9(2) VALUE 2.

PROCEDURE DIVISION.P-1.

DISPLAY(1 1) ERASE.DISPLAY(3 5) MARK1 OF REC-1.ADD CORR REC-1 TO REC-2.DISPLAY(5 5) MARK2 OF REC-2.DISPLAY (10 5) SNO OF REC-2.STOP RUN.

2 PROGRAM FOR MOVE CORRESPONDINGWrite a simple program to demonstrate Move Corresponding.

IDENTIFICATION DIVISION.PROGRAM-ID.ENVIRONMENT DIVISION.DATA DIVISION.WORKING-STORAGE SECTION.

Page 5: cobol

01 REC-1.02 SNO PIC 9(2) VALUE 11.02 NAME PIC X(4) VALUE "RAVI".

01 REC-2.05 SNO PIC Z(2).05 F PIC X(10) VALUE SPACES.05 NAME PIC X(4).05 F PIC X(10) VALUE SPACES.

PROCEDURE DIVISION.P-1.

DISPLAY(1 1) ERASE.MOVE CORR REC-1 TO REC-2.

DISPLAY REC-2.STOP RUN.3 PROGRAM FOR CONDITION NAMESWrite a simple program to demonstrate Condition names usage.

IDENTIFICATION DIVISION.PROGRAM-ID.ENVIRONMENT DIVISION.DATA DIVISION.WORKING-STORAGE SECTION.01 MS PIC 9(2).

88 S VALUE 0 THRU 9 .88 M VALUE 10 THRU 99.

PROCEDURE DIVISION.P-1.

DISPLAY(1 1) ERASE.DISPLAY(5 5) "ENTER MARRIAGE STATUS : ".DISPLAY(7 5) " 0 TO 9 .... SINGLE PERSON ".DISPLAY(8 5) " 10 TO 99 .... MARRIED PERSON".ACCEPT MS.IF S DISPLAY(10 5) "SINGLE".IF M DISPLAY(10 5) "MARRIED".STOP RUN.

4 PROGRAM USING OCCURS CLAUSEWrite a simple program to demonstrate Occurs Clause. Get the employee details for 3persons and calculate the total salary.

IDENTIFICATION DIVISION.PROGRAM-ID. EMP-OCCURS.ENVIRONMENT DIVISION.DATA DIVISION.WORKING-STORAGE SECTION.01 EMP-REC.

02 EMP-DET OCCURS 3 TIMES.05 EMP-NAME PIC X(20).05 EMP-SAL PIC 9(5)V9(2).

01 HEAD-1 PIC X(80) VALUE ALL "-".01 HEAD-2.

Page 6: cobol

02 F PIC X(15) VALUE SPACES.02 F PIC X(20) VALUE "NAME".02 F PIC X(15) VALUE SPACES.02 F PIC X(10) VALUE "SALARY".02 F PIC X(20) VALUE SPACES.

01 HEAD-3.02 F PIC X(15) VALUE SPACES.02 E-NAME PIC X(20).02 F PIC X(15) VALUE SPACES.02 E-SAL PIC Z(5).Z(2).02 F PIC X(22) VALUE SPACES.

01 I PIC 9 VALUE 1.01 TOT-SAL PIC 9(6)V9(2) VALUE 0.01 E-TOT-SAL PIC Z(6).Z(2).PROCEDURE DIVISION.PARA-1.

DISPLAY(1 1) ERASE.DISPLAY(3 5) "ENTER DATA FOR 3 EMPLOYEES...".PERFORM GET-PARA 3 TIMES.DISPLAY HEAD-1.DISPLAY HEAD-2.DISPLAY HEAD-1.MOVE 1 TO I.

PERFORM DISP-PARA UNTIL I > 3.DISPLAY HEAD-1.MOVE TOT-SAL TO E-TOT-SAL.DISPLAY "TOTAL SALARY = " E-TOT-SAL.DISPLAY " ".STOP RUN.

GET-PARA.DISPLAY(1 1) ERASE.DISPLAY(5 5) "NAME : ".ACCEPT EMP-NAME(I).DISPLAY(10 5) "SALARY : ".ACCEPT EMP-SAL(I).ADD 1 TO I.

DISP-PARA.MOVE EMP-NAME(I) TO E-NAME.MOVE EMP-SAL(I) TO E-SAL.COMPUTE TOT-SAL = TOT-SAL + EMP-SAL(I).DISPLAY HEAD-3.ADD 1 TO I.

5. Write a program to maintain the stu-file for which a record has just 2 fields, namely,rno(Roll Number) and name(Student Name). Give the provisions to add, modify, delete therecords in the file.

IDENTIFICATION DIVISION.PROGRAM-ID.ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.

Page 7: cobol

FILE-CONTROL.SELECT STU-FILE ASSIGN TO DISKORGANIZATION IS INDEXEDACCESS MODE IS RANDOMRECORD KEY IS RNOFILE STATUS IS FS.

DATA DIVISION.FILE SECTION.FD STU-FILE

LABEL RECORDS ARE STANDARDVALUE OF FILE-ID IS "STU.DAT".

01 STU-REC.02 RNO PIC 9(3).02 NAME PIC X(20).

WORKING-STORAGE SECTION.01 FS PIC X(2) VALUE SPACES.01 ANS PIC X VALUE SPACE.01 CH PIC 9 VALUE 0.PROCEDURE DIVISION.OPEN-PARA.

OPEN I-O STU-FILE.IF FS = "30"OPEN OUTPUT STU-FILECLOSE STU-FILEOPEN I-O STU-FILE.

P-1.DISPLAY(1 1) ERASE.DISPLAY(3 5) "MAIN MENU".DISPLAY(5 5) "1 TO ADD".DISPLAY(7 5) "2 TO MODIFY".DISPLAY(9 5) "3 TO DELETE".DISPLAY(11 5) "4 TO EXIT".DISPLAY(13 5) "YOUR CHOICE [1..4] : ".ACCEPT CH.IF CH < 0 OR CH > 4 GO TO P-1.GO TO ADD-PARA MODI-PARA DEL-PARA EXIT-PARADEPENDING ON CH.

ADD-PARA.DISPLAY(1 1) ERASE.DISPLAY(3 5) "RNO : ".ACCEPT RNO.DISPLAY(5 5) "NAME : ".ACCEPT NAME.WRITE STU-REC INVALID KEY DISPLAY(15 5) "ERROR!".DISPLAY(20 5) "CONTINUE ADD RECORDS [Y/N] : ".ACCEPT ANS.IF ANS = "Y" GO TO ADD-PARA ELSE GO TO P-1.

MODI-PARA.DISPLAY(1 1) ERASE.DISPLAY(3 5) "ENTER ROLL NO TO MODIFY".

Page 8: cobol

ACCEPT RNO.READ STU-FILE KEY IS RNOINVALID KEY DISPLAY(13 5) "NO RECORD FOUND"GO TO C-PARA.DISPLAY(5 5) "RNO = " RNO.DISPLAY(7 5) "NAME = " NAME.DISPLAY(9 5) "SURE TO MODIFY [Y/N] : ".ACCEPT ANS.IF ANS = 'Y'DISPLAY(1 1) ERASEDISPLAY(5 5) "NAME : "ACCEPT NAMEREWRITE STU-REC.

C-PARA.DISPLAY(15 5) "CONTINUE MODIFICATION [Y/N] : ".

ACCEPT ANS.IF ANS = 'Y' GO TO MODI-PARA ELSE GO TO P-1.DEL-PARA.

DISPLAY(1 1) ERASE.DISPLAY(3 5) "ENTER ROLL NO TO DELETE".ACCEPT RNO.READ STU-FILE KEY IS RNO

INVALID KEY DISPLAY(13 5) "NO RECORD FOUND"GO TO C-PARA1.

DISPLAY(5 5) "RNO = " R//NO.DISPLAY(7 5) "NAME = " NAME.DISPLAY(9 5) "SURE TO DELETE [Y/N] : ".ACCEPT ANS.IF ANS = 'Y'DELETE STU-FILE RECORD.

C-PARA1.DISPLAY(15 5) "CONTINUE DELETION [Y/N] : ".ACCEPT ANS.IF ANS = 'Y' GO TO DEL-PARA ELSE GO TO P-1.

EXIT-PARA.CLOSE STU-FILE.

6. Write a program to maintain the stu-file for which a record has just 2 fields, namely,rno(Roll Number) and name(Student Name). Give the provisions to add, modify, delete therecords in the file.

IDENTIFICATION DIVISION.PROGRAM-ID.ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL.

SELECT STU-FILE ASSIGN TO DISKORGANIZATION IS INDEXEDACCESS MODE IS RANDOMRECORD KEY IS RNO

FILE STATUS IS FS.

Page 9: cobol

DATA DIVISION.FILE SECTION.FD STU-FILE

LABEL RECORDS ARE STANDARDVALUE OF FILE-ID IS "STU.DAT".

01 STU-REC.02 RNO PIC 9(3).02 NAME PIC X(20).

WORKING-STORAGE SECTION.01 FS PIC X(2) VALUE SPACES.01 ANS PIC X VALUE SPACE.01 CH PIC 9 VALUE 0.PROCEDURE DIVISION.OPEN-PARA.

OPEN I-O STU-FILE.IF FS = "30"OPEN OUTPUT STU-FILECLOSE STU-FILEOPEN I-O STU-FILE.

P-1.DISPLAY(1 1) ERASE.DISPLAY(3 5) "MAIN MENU".DISPLAY(5 5) "1 TO ADD".DISPLAY(7 5) "2 TO MODIFY".DISPLAY(9 5) "3 TO DELETE".DISPLAY(11 5) "4 TO EXIT".DISPLAY(13 5) "YOUR CHOICE [1..4] : ".ACCEPT CH.IF CH < 0 OR CH > 4 GO TO P-1.GO TO ADD-PARA MODI-PARA DEL-PARA EXIT-PARADEPENDING ON CH.

ADD-PARA.DISPLAY(1 1) ERASE.DISPLAY(3 5) "RNO : ".ACCEPT RNO.DISPLAY(5 5) "NAME : ".ACCEPT NAME.WRITE STU-REC INVALID KEY DISPLAY(15 5) "ERROR!".DISPLAY(20 5) "CONTINUE ADD RECORDS [Y/N] : ".ACCEPT ANS.IF ANS = "Y" GO TO ADD-PARA ELSE GO TO P-1.

MODI-PARA.DISPLAY(1 1) ERASE.DISPLAY(3 5) "ENTER ROLL NO TO MODIFY".ACCEPT RNO.READ STU-FILE KEY IS RNOINVALID KEY DISPLAY(13 5) "NO RECORD FOUND"GO TO C-PARA.DISPLAY(5 5) "RNO = " RNO.DISPLAY(7 5) "NAME = " NAME.

Page 10: cobol

DISPLAY(9 5) "SURE TO MODIFY [Y/N] : ".ACCEPT ANS.IF ANS = 'Y'DISPLAY(1 1) ERASEDISPLAY(5 5) "NAME : "ACCEPT NAMEREWRITE STU-REC.

C-PARA.DISPLAY(15 5) "CONTINUE MODIFICATION [Y/N] : ".ACCEPT ANS.IF ANS = 'Y' GO TO MODI-PARA ELSE GO TO P-1.

DEL-PARA.DISPLAY(1 1) ERASE.DISPLAY(3 5) "ENTER ROLL NO TO DELETE".ACCEPT RNO.READ STU-FILE KEY IS RNOINVALID KEY DISPLAY(13 5) "NO RECORD FOUND"GO TO C-PARA1.DISPLAY(5 5) "RNO = " RNO.DISPLAY(7 5) "NAME = " NAME.DISPLAY(9 5) "SURE TO DELETE [Y/N] : ".ACCEPT ANS.IF ANS = 'Y'DELETE STU-FILE RECORD.

C-PARA1.DISPLAY(15 5) "CONTINUE DELETION [Y/N] : ".ACCEPT ANS.IF ANS = 'Y' GO TO DEL-PARA ELSE GO TO P-1.

EXIT-PARA.CLOSE STU-FILE.STOP RUN.

7 PROGRAM TO FIND INTEREST ON BANK DEPOSITSWrite a program to find interest on deposits The criteria is given below :______________________________________________Principal Years of Deposit IntRate______________________________________________>=5000 >= 3 10%>=5000 < 3 8%<5000 Any 7%______________________________________________IDENTIFICATION DIVISION.PROGRAM-ID.ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL.

SELECT BANKFILE ASSIGN TO DISKORGANIZATION IS LINE SEQUENTIAL.

DATA DIVISION.FILE SECTION.FD BANKFILE

Page 11: cobol

LABEL RECORDS ARE STANDARDVALUE OF FILE-ID IS "BANK.DAT".

01 BANKREC.02 DNO PIC 9(5).02 DNAME PIC X(21).02 P PIC 9(4)V9(2).02 N PIC 9(2).

WORKING-STORAGE SECTION.01 ANS PIC X VALUE SPACE.01 TOT PIC 9(6)V9(2) VALUE 0.01 INT PIC 9(6)V9(2) VALUE 0.01 KEY-IN PIC X VALUE SPACE.01 R PIC 9(2) VALUE 0.01 HEAD-1 PIC X(80) VALUE ALL '-'.01 HEAD-2.

02 F PIC X(8) VALUE "DEPS NO".02 F PIC X(3) VALUE SPACES.02 F PIC X(10) VALUE "DEPS NAME".02 F PIC X(5) VALUE SPACES.02 F PIC X(8) VALUE "DEPOSIT".02 F PIC X(5) VALUE SPACES.02 F PIC X(8) VALUE "PERIOD".02 F PIC X(5) VALUE SPACES.02 F PIC X(5) VALUE "RATE".02 F PIC X(5) VALUE SPACES.02 F PIC X(8) VALUE "INTEREST".02 F PIC X(10) VALUE " NETT".

01 HEAD-3.02 E-DNO PIC Z(5).02 E-DNAME PIC X(26).02 E-P PIC Z(4).Z(2).02 F PIC X(5) VALUE SPACES.02 E-N PIC Z(2).02 F PIC X(5) VALUE SPACES.02 E-R PIC Z(2).02 F PIC X(3) VALUE SPACES.02 E-INT PIC Z(4).Z(2).02 F PIC X(3) VALUE SPACES.02 E-TOT PIC Z(6).Z(2).

PROCEDURE DIVISION.P-1.

OPEN OUTPUT BANKFILE.PERFORM G-W-PARA UNTIL ANS = 'N' OR 'N'.CLOSE BANKFILE.OPEN INPUT BANKFILE.DISPLAY(1 1) ERASE.DISPLAY HEAD-1.DISPLAY HEAD-2.DISPLAY HEAD-1.

READ-PARA.

Page 12: cobol

READ BANKFILE AT END GO TO CLOSE-PARA.IF ( P NOT < 5000 AND N NOT < 3 )MOVE 10 TO RCOMPUTE TOT = P * (1 + R / 100) ** N.IF ( P NOT < 5000 AND N < 3)MOVE 8 TO RCOMPUTE TOT = P * (1 + R / 100) ** N.IF ( P < 5000)MOVE 7 TO RCOMPUTE TOT = P * (1 + R / 100) ** N.MOVE TOT TO E-TOT.COMPUTE INT = TOT - P.MOVE INT TO E-INT.MOVE DNO TO E-DNO.MOVE DNAME TO E-DNAME.MOVE P TO E-P.MOVE N TO E-N.MOVE R TO E-R.DISPLAY HEAD-3.GO TO READ-PARA.

CLOSE-PARA.DISPLAY HEAD-1.CLOSE BANKFILE.STOP RUN.

G-W-PARA.DISPLAY(1 1) ERASE.DISPLAY(3 5) "DEP NO : ".ACCEPT DNO.DISPLAY(5 5) "DEP NAME : ".ACCEPT DNAME.DISPLAY(7 5) "AMOUNT : ".ACCEPT P.DISPLAY(9 5) "YEARS : ".ACCEPT N.WRITE BANKREC.DISPLAY(15 5) "ADD MORE [Y/N] : ".ACCEPT ANS.

8 PROGRAM FOR INVENTORYWrite a program to update the inventory file. Consider 2 files,namely, invfile andtranfile. Invfile has 3 fields pno,name,qty. Tranfile has 3 fileds tpno,trcode,tqty. By readingtranfile records if trcode=1 then update the qty with qty+tqty in invfile. If trcode=2 thenupdate the qty with qty-tqty in invfile.

IDENTIFICATION DIVISION.PROGRAM-ID.ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL.

SELECT INVFILE ASSIGN TO DISKORGANIZATION IS INDEXED

Page 13: cobol

ACCESS MODE IS DYNAMICRECORD KEY IS PNOFILE STATUS IS FS.

SELECT TRANFILE ASSIGN TO DISKORGANIZATION IS LINE SEQUENTIAL.DATA DIVISION.FILE SECTION.FD INVFILE

LABEL RECORDS ARE STANDARDVALUE OF FILE-ID IS "INV.DAT".

01 INVREC.02 PNO PIC 9(5).02 NAME PIC X(5).02 QTY PIC 9(5).

FD TRANFILELABEL RECORDS ARE STANDARDVALUE OF FILE-ID IS "TRAN.DAT".

01 TRANREC.02 TPNO PIC 9(5).02 TRCODE PIC 9.02 TQTY PIC 9(5).

WORKING-STORAGE SECTION.01 ANS PIC X VALUE SPACE.01 FS PIC X(2) VALUE SPACES.01 KEY-IN PIC X VALUE SPACE.PROCEDURE DIVISION.P-1.

OPEN I-O INVFILE.IF FS = "30"OPEN OUTPUT INVFILECLOSE INVFILEOPEN I-O INVFILE.PERFORM G-W-INV UNTIL ANS = 'N' OR 'N'.MOVE SPACE TO ANS.OPEN OUTPUT TRANFILE.PERFORM G-W-TRAN UNTIL ANS = 'N' OR 'N'.CLOSE TRANFILE.OPEN INPUT TRANFILE.

READ-PARA.READ TRANFILE AT END GO TO CLOSE-PARA.MOVE TPNO TO PNO.READ INVFILE KEY IS PNO INVALID KEYDISPLAY(5 5) "NO RECORD FOUND FOR" ; PNOACCEPT KEY-INGO TO READ-PARA.IF TRCODE = 1ADD TQTY TO QTYREWRITE INVREC.IF TRCODE = 2SUBTRACT TQTY FROM QTY

Page 14: cobol

REWRITE INVREC.GO TO READ-PARA.

CLOSE-PARA.CLOSE INVFILE TRANFILE.OP-PARA.OPEN INPUT INVFILE.

R-PARA.READ INVFILE NEXT RECORD AT END GO TO CL-PARA.DISPLAY(1 1) ERASE.DISPLAY(3 5) "PART NO: " PNO.DISPLAY(5 5) "NAME : " NAME.DISPLAY(7 5) "QTY : " QTY.ACCEPT KEY-IN.GO TO R-PARA.

CL-PARA.CLOSE INVFILE.STOP RUN.

G-W-TRAN.DISPLAY(1 1) ERASE.DISPLAY(2 5) "TRAN DETAILS ....".DISPLAY(3 5) "PART NO: ".ACCEPT TPNO.DISPLAY(5 5) "TRANCODE : ".ACCEPT TRCODE.DISPLAY(7 5) "QUANTITY : ".ACCEPT TQTY.WRITE TRANREC.DISPLAY(12 5) "ADD MORE [Y/N] :".ACCEPT ANS.

G-W-INV.DISPLAY(1 1) ERASE.DISPLAY(2 5) "INVEN DETAILS....".DISPLAY(3 5) "PART NO: ".ACCEPT PNO.DISPLAY(5 5) "NAME : ".ACCEPT NAME.DISPLAY(7 5) "QUANTITY : ".ACCEPT QTY.WRITE INVREC INVALID KEY DISPLAY(10 5) "REC EXISTS!".DISPLAY(12 5) "ADD MORE [Y/N] :".ACCEPT ANS._

9 PROGRAM TO REWRITE PAY RATEWrite a program to modify the hourly-pay-rate based on the criteria given below:______________________________________Existing Hpr Increase in Hpr in Rs)______________________________________<=5 25%>5 but <= 20%>8 but <=12 15%>12 10%

Page 15: cobol

----------------------------------------------------------IDENTIFICATION DIVISION.PROGRAM-ID.ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL.

SELECT PAYFILE ASSIGN TO DISK.DATA DIVISION.FILE SECTION.FD PAYFILE

LABEL RECORDS ARE STANDARDVALUE OF FILE-ID IS "PAY.DAT".

01 PAYREC.02 IDNO PIC X(3)9(6).02 NAME PIC X(25).02 HPR PIC 99V99.02 MIS PIC X(42).

WORKING-STORAGE SECTION.01 ANS PIC X VALUE SPACE.01 HEAD-1 PIC X(80) VALUE ALL '-'.01 HEAD-2.

02 F PIC X(5) VALUE SPACES.02 F PIC X(5) VALUE "IDNO".02 F PIC X(5) VALUE SPACES.02 F PIC X(5) VALUE "NAME".02 F PIC X(5) VALUE SPACES.02 F PIC X(7) VALUE "NEWHPR".02 F PIC X(36) VALUE "MIS INFO".02 F PIC X(12) VALUE SPACES.

01 HEAD-3.02 E-IDNO PIC X(3)9(6).02 E-NAME PIC X(25).02 E-HPR PIC Z(2).Z(2).02 E-MIS PIC X(41).

PROCEDURE DIVISION.P-1.

OPEN EXTEND PAYFILE.PERFORM G-W-PARA UNTIL ANS = 'N' OR 'N'.CLOSE PAYFILE.OPEN I-O PAYFILE.

READ-PARA.READ PAYFILE AT END GO TO CLOSE-PARA.DISPLAY(1 1) ERASE.DISPLAY(3 5) "HPR = " HPR.ACCEPT ANS.IF ( HPR NOT GREATER 5 )COMPUTE HPR = HPR + HPR * 0.25.IF ( HPR > 5 AND HPR NOT GREATER 8 )COMPUTE HPR = HPR + HPR * 0.20.IF ( HPR > 8 AND HPR NOT GREATER 12 )

Page 16: cobol

COMPUTE HPR = HPR + HPR * 0.15.IF ( HPR > 12 )COMPUTE HPR = HPR + HPR * 0.10.REWRITE PAYREC.MOVE 0 TO HPR.GO TO READ-PARA.

CLOSE-PARA.DISPLAY HEAD-1.CLOSE PAYFILE.

DISP-PARA.OPEN INPUT PAYFILE.DISPLAY HEAD-1.DISPLAY HEAD-2.DISPLAY HEAD-1.

READ-PARA-1.READ PAYFILE AT END GO TO CLOSE-PARA-1.MOVE IDNO TO E-IDNO.MOVE NAME TO E-NAME.MOVE HPR TO E-HPR.MOVE MIS TO E-MIS.DISPLAY HEAD-3.GO TO READ-PARA-1.

CLOSE-PARA-1.DISPLAY HEAD-1.CLOSE PAYFILE.STOP RUN.

G-W-PARA.DISPLAY(1 1) ERASE.DISPLAY(3 5) "ID NO [ X(3) 9(6)] : ".ACCEPT IDNO.DISPLAY(5 5) "EMP NAME :".ACCEPT NAME.DISPLAY(7 5) " HRLY PAY RATE : ".ACCEPT HPR.DISPLAY(9 5) "MISCELL INFO : ".ACCEPT MIS.WRITE PAYREC.DISPLAY(15 5) "ADD MORE (Y/N) :".ACCEPT ANS.

10 PROGRAM FOR ELECTRICITY BILLAn electricity company supplies electricity to 4 types of customers coded 1,2,3 & 4.The rate schedule for customers is shown in one table as------------------------------------------------------------------------------Customer code 1 2 2 3 3 4Consumption All Below 1000& Below 5000& All 1000 above 5000 aboveRate/unit 0.50 0.40 0.50 0.30 0.50 0.30-----------------------------------------------------------------------------The customer record is:col:1-5 customer no.

Page 17: cobol

col:6-60 name & address.col:61-67 consumption in units.col:68 customer code.Read a customer record and print a bill using GOTO DEPENDING ON statement.IDENTIFICATION DIVISION.PROGRAM-ID.ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL.

SELECT EFILE ASSIGN TO DISKORGANIZATION IS LINE SEQUENTIAL.

DATA DIVISION.FILE SECTION.FD EFILE

LABEL RECORDS ARE STANDARDVALUE OF FILE-ID IS "E.DAT".

01 EREC.02 CCODE PIC 9.02 UNITS PIC 9(7).

WORKING-STORAGE SECTION.01 ANS PIC X VALUE SPACE.01 HEAD-1 PIC X(80) VALUE ALL '-'.01 AMT PIC 9(5)V9(2) VALUE 0.01 HEAD-2.

02 F PIC X(11) VALUE SPACES.02 F PIC X(6) VALUE "CSCODE".02 F PIC X(11) VALUE SPACES.02 F PIC X(5) VALUE "UNITS".02 F PIC X(11) VALUE SPACES.02 F PIC X(10) VALUE "AMOUNT".02 F PIC X(11) VALUE SPACES.

01 HEAD-3.02 F PIC X(5) VALUE SPACES.02 E-CCODE PIC Z.02 F PIC X(5) VALUE SPACES.02 E-UNITS PIC Z(7).02 F PIC X(10) VALUE SPACES.02 E-AMT PIC Z(5).Z(2).

SCREEN SECTION.01 B-SCREEN.

02 BLANK SCREEN.PROCEDURE DIVISION.P-1.

OPEN EXTEND EFILE.PERFORM G-W-PARA UNTIL ANS = 'N' OR 'N'.CLOSE EFILE.OPEN INPUT EFILE.DISPLAY HEAD-1.DISPLAY HEAD-2.DISPLAY HEAD-1.

Page 18: cobol

READ-PARA.READ EFILE AT END GO TO CLOSE-PARA.GO TO C1 C2 C3 C4 DEPENDING ON CCODE.

C1.COMPUTE AMT = UNITS * 0.50GO TO M-PARA.

C2.IF ( UNITS < 1000)COMPUTE AMT = UNITS * 0.40GO TO M-PARA.IF (UNITS NOT < 1000 )COMPUTE AMT = (UNITS - 999) * 0.5 + 999 * 0.40GO TO M-PARA.

C3.IF (UNITS < 5000)COMPUTE AMT = UNITS * 0.30GO TO M-PARAELSECOMPUTE AMT = (UNITS - 4999) * 0.5 + 4999 * 0.30GO TO M-PARA.

C4.COMPUTE AMT = UNITS * 0.30.

M-PARA.MOVE AMT TO E-AMT.MOVE CCODE TO E-CCODE.MOVE UNITS TO E-UNITS.DISPLAY HEAD-3.GO TO READ-PARA.

CLOSE-PARA.DISPLAY HEAD-1.CLOSE EFILE.STOP RUN.

G-W-PARA.DISPLAY B-SCREEN.DISPLAY(3 5) "CUS CODE: ".ACCEPT CCODE.DISPLAY (5 5) "UNITS : ".ACCEPT UNITS.WRITE EREC.DISPLAY(10 5) "CONTINUE [Y/N] : ".ACCEPT ANS.

11 PROGRAM TO CREATE 2 FILES USING AN EXISTING FILEA file contains the following records about a class.Fields Columns-------- -----------Serial No. 1-4Roll No. 5-10Name 11-30Age 31-32Sex 33

Page 19: cobol

Year in college 34Select records with the following characteristics and write them in 2 files.File-1: Records of all males over 18 years of age who are in the third year in the college.File-2: Records of all females under 19 years of age in the fourth year in the college.Use condition names for sex and year in college.IDENTIFICATION DIVISION.PROGRAM-ID.ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL.

SELECT COLLFILE ASSIGN TO DISKORGANIZATION IS LINE SEQUENTIAL.SELECT MALEFILE ASSIGN TO DISKORGANIZATION IS LINE SEQUENTIAL.SELECT FEMALEFILE ASSIGN TO DISKORGANIZATION IS LINE SEQUENTIAL.

DATA DIVISION.FILE SECTION.FD COLLFILE

LABEL RECORDS ARE STANDARDVALUE OF FILE-ID IS "COLL.DAT".

01 COLLREC.02 SNO PIC 9(4).02 RNO PIC 9(6).02 NAME PIC X(20).02 AGE PIC 9(2).02 SEX PIC 9.

88 MALE VALUE 1.88 FEMALE VALUE IS 2.

02 YR PIC 9.88 THIRD VALUE 3.88 FOURTH VALUE IS 4.

FD MALEFILELABEL RECORDS ARE STANDARDVALUE OF FILE-ID IS "MALE.DAT".

01 MALEREC PIC X(80).FD FEMALEFILE

LABEL RECORDS ARE STANDARDVALUE OF FILE-ID IS "FEMALE.DAT".

01 FEMALEREC PIC X(80).WORKING-STORAGE SECTION.01 ANS PIC X VALUE SPACE.PROCEDURE DIVISION.P-1.

DISPLAY(1 1) ERASE.OPEN OUTPUT COLLFILE.PERFORM G-W-PARA UNTIL ANS = 'N' OR 'N'.CLOSE COLLFILE.OPEN INPUT COLLFILE OUTPUT MALEFILE FEMALEFILE.

READ-PARA.

Page 20: cobol

READ COLLFILE AT END GO TO CLOSE-PARA.IF (MALE AND AGE > 18 AND THIRD)MOVE COLLREC TO MALERECWRITE MALEREC.IF(FEMALE AND AGE < 19 AND FOURTH)MOVE COLLREC TO FEMALERECWRITE FEMALEREC.GO TO READ-PARA.

CLOSE-PARA.CLOSE COLLFILE MALEFILE FEMALEFILE.STOP RUN.

G-W-PARA.DISPLAY(1 1) ERASE.DISPLAY(3 5) "SNO : ".ACCEPT SNO.DISPLAY(5 5) "RNO: ".ACCEPT RNO.DISPLAY(7 5) "NAME: ".ACCEPT NAME.DISPLAY(9 5) "AGE : ".ACCEPT AGE.DISPLAY(11 5) "SEX (1 - MALE ; 2 -FEMALE) : ".ACCEPT SEX.DISPLAY(13 5) "YEAR (3 - THIRD; 4 -FOURTH : ".ACCEPT YR.WRITE COLLREC.DISPLAY(20 5) "ADD MORE(Y/N) :".ACCEPT ANS.

OPERATING SYSTEMS

UNIT-I: Operating System Overview: Operating System Objectives and Functions – The Evolution of Operating Systems – Major Achievements – Developments Leading to Modern Operating Systems – Microsoft Windows Overview – Traditional UNIX Systems – Modern UNIX Systems – Linux 95.UNIT-II: OS-Functions and Structure: Different Services of Operating System – Operating System Structure – Booting. Information Management: The File System - Device Driver.UNIT-III: Process Management: What Is A Process? – Evolution of Multiprogramming – ContextSwitching – Process States – Process State Transitions – Operations on a Process.UNIT-IV: Memory Management: Introduction – Single Contiguous Memory Management – Fixed

Page 21: cobol

Partition Memory Management – Variable Partitions – Non-contiguous Allocation – Paging –Segmentation – Combined Systems – Virtual Memory Management Systems.UNIT-V: Distributed Processing, Client/Server and Clusters: Client/Server Computing –Distributed Message Passing- Remote Procedure Calls – Clusters –Windows Cluster – Sun Cluster –Beowulf And Linux Clusters.TEXTBOOKS:1. OPERATING SYSTEMS Internals and Design Principles – William Stallings, 5th edition,PHI.(UNIT-I: 2.1-2.8 UNIT-V: 14.1-14.7)2. OPERATING SYSTEMS – Achyut Godbole , 2nd edition, TMH.(UNIT II: 3.2, 3.7, 3.9, 4.2, 4.3 UNIT-III: 5.2-5.6, 5.9 UNIT-IV: 8.1-8.9)REFERENCE BOOKS:1. OPERATING SYSTEMS Concepts and Design – Milan Milankovic, 2nd edition, TMH.2. MODERN OPERATIING SYSTEMS – Andrew S. Tanenbaum, 2nd edition, PHI.3. OPERATING SYSTEM PRINCIPLES – Abraham Silberschatz, Peter Baer Galvin, Greg

Gagne, 7th Edition, Wiley India.

COBOL

COBOL is a high-level programming language first developed by the CODASYL Committee (Conference on Data Systems Languages) in 1960. Since then, responsibility for developing new COBOL standards has been assumed by the American National Standards Institute (ANSI).

Three ANSI standards for COBOL have been produced: in 1968, 1974 and 1985. A new COBOL standard introducing object-oriented programming to COBOL, is due within the next few years.

The word COBOL is an acronym that stands for COmmon Business Oriented Language. As the expanded acronym indicates, COBOL is designed for developing business, typically file-oriented, applications. It is not designed for writing systems programs. For instance you would not develop an operating system or a compiler using COBOL.

For over four decades COBOL has been the dominant programming language in the business computing domain. In that time it has seen off the challenges of a number of other languages such as PL1, Algol68, Pascal, Modula, Ada, C, C++. All these languages have found a niche but none has yet displaced COBOL. Two recent challengers though, Java and Visual Basic, are proving to be serious contenders.

COBOL's dominance in underlined by the reports from the Gartner group. In 1997 they estimated that there were about 300 billion lines of computer code in use in the world. Of that they estimated that about 80% (240 billion lines) were in COBOL and 20% (60 billion lines) were written in all the other computer languages combined [Brown]. In 1999 they reported that over 50% of all new mission-critical applications were still being done in COBOL and their recent estimates indicate that through 2004-2005 15% of all new applications (5 billion lines) will be developed in COBOL while 80% of all deployed applications will include extensions to existing legacy (usually COBOL) programs. Gartner estimates for 2002 are that there are about two million COBOL programmers world-wide compared to about about one million Java programmers and one million C++ programmers.

Introduction

COBOL is about as old as your parents, so just think how old it is in computer years. It is still an important language though, mainly because there are thousands and thousands of applications out there

Page 22: cobol

written in COBOL, and someone has got to fix them and add to them. There aren't as many jobs for COBOL as for C++ or JAVA, but then again, not a lot of people are learning COBOL anymore.

COBOL really isn't that difficult either, especially if you know other structured languages like Pascal and C. You can easily learn enough to sound intelligent in a day. There aren't many data-structures (actually, everything is really a record), and there are no notions of scope or parameter passing.

The Basics

A "hello world" program is as good a way as any to understand the structure of a COBOL program, so here it is:

IDENTIFICATION DIVISION

PROGRAM-ID HELLO-WORLD

ENVIRONMENT DIVISION

DATA DIVISION

PROCEDURE DIVISION

FIRST-PARA.

    DISPLAY "Hello World".

STOP RUN

This is quite a bit more complex than a similar program an Pascal or C

The first thing to notice are the four divisions :

IDENTIFICATION DIVISION : This is where you must enter the program name. You can also enter when and by whom it was written.

ENVIRONMENT DIVISION : This is where you define the files the program needs. You also used to put hardware information here, but that isn't really necessary anymore. 

DATA DIVISION : This is where you declare variables, records, files etc. It is similar to the top of a Pascal program.

PROCEDURE DIVISION : This is where you write the program. In the sample above this is all in one paragraph. A paragraph is a series of statements named by a label (FIRST-PARA in this case). There is no specific mark to the end of a paragraph.

Each statement begins with a word like DISPLAY that describes the action to be performed by the statement.

There are a couple of hundred reserved words in COBOL so I find it useful to put hyphens in user defined names like HELLO-WORLD.

Page 23: cobol

Screen Output

Screen output is always one of the first things you want to master with a new language. You have seen an example of screen output with the

  DISPLAY "Hello World".

statement. You can also use it to write digits:

 DISPLAY 300.

Or a combination:

 DISPLAY "The number is " 300.

The problem with number is that this technique only works for unsigned integers, a way around this is as follows:

 DISPLAY "-766.32".

To find out more about using floating-point and signed numbers, see the Arithmetic Operations section.

Also note that you can't make statements like :

 DISPLAY 2 + 3

You have to store the result of 2 + 3 in a variable first. See the Assigning Values to Variables section.

Data Declaration

The HELLO-WORLD program can be altered to demonstrate basic data declaration. In this program two string variables and one number variable are created and given initial values. These are then printed out.

IDENTIFICATION DIVISION

PROGRAM-ID HELLO-WORLD

ENVIRONMENT DIVISION

DATA DIVISION

WORKING-STORAGE SECTION.

01 WS_STRING-1    PIC X(20)

   VALUE "Hello World".

01 WS-STRING-2    PIC X(30)

   VALUE "This is program number ".

Page 24: cobol

01 WS-PROGRAM-NUMBER    PIC 9(2)

   VALUE 1.

PROCEDURE DIVISION

FIRST-PARA.

   DISPLAY WS-STRING-1.

   DISPLAY WS-STRING-2.

   DISPLAY WS-PROGRAM-NUMBER.

STOP RUN

The WORKING-STORAGE SECTION is used for declaring variables other than files and associated records. The 01 before each variable is its level number - the need for these becomes apparent when we deal with records. This is followed by the data name, and then a PIC clause. The PIC clause establishes the type and size of the variable. 'X' represents a character, '9' represents a number. The number following in brackets tells the size (for X(4) you could also write XXXX).

Keyboard Input

Keyboard input is simple. We can use the variable WE-PROGRAM-NUMBER from above to store a new program number:

DISPLAY "Enter the program number".

ACCEPT WS-PROGRAM-NUMBER.

This can only be used to obtain a single variable at a time.

Assigning Values to Variables

The two main keywords used for this are MOVE and COMPUTE. 

Continuing with our variable WS-PROGRAM-NUMBER from the Data Declaration section, we can assign a new value for it with the following structure in the PROCEDURE DIVISION section :

MOVE 5  TO  WS-PROGRAM-NUMBER.

We can give WS-STRING-1 a new value like this :

MOVE "Hello Everyone" TO WS-STRING-1.

There is a more advanced type of assignment that MOVE can't help us with. Given correctly declared variables, we can write the following in Pascal :

numA := numB * numC;

Page 25: cobol

The value of numA becomes the value of the expression numB * numC. To do this in Pascal we need to use the COMPUTE  keyword.

Suppose we have created two number variables in the DATA DIVISION section called WS-NUMBER-1 and WS-NUMBER-2. These have been given values, and we want to multiply them together and store the result in WS-PROGRAM-NUMBER. We can do this with the following code in the PROCEDURE DIVISION section :

COMPUTE WS-PROGRAM-NUMBER = WS-NUMBER-1 * WS-NUMBER-2.

You could also just use numbers :

COMPUTE WS-PROGRAM-NUMBER = 10 * 5.

Remember to be careful when assigning values to variables. COBOL won't check to see if the new value is appropriate for the variable in either size or type. In fact, it is worth pointing out here, COBOL has very little built in error checking, so be careful.

Arithmetic Operations

The COMPUTE keyword above introduced arithmetic. Bare in mind that there is no mod operator available, and division is done with /.

With division, numbers can be rounded up like this :

COMPUTE WS-NUMBER-1 ROUNDED = 37/10.

COBOL can also handle floating point numbers. Floating point numbers are declared like this in DATA DIVISION :

WS-NUMBER-10    PIC 99V99.

This number can hold values with two leading and two trailing spaces like 23.98.

A confusing aspect of this is that to enter a number like this with ASSIGN the user would have to enter 2398.

COBOL can also deal with signed numbers. Simply put an S at the front :

WS-NUMBER-10    PIC S99V99.

We could now give it the value -32.76.

There are also a collection of keywords that deal with arithmetic. Given the right declarations statements like these sometimes occur :

ADD WS-NUMBER-1 TO WS-NUMBER-2.

MULTIPLY WS-NUMBER-1 BY WS-NUMBER-2 GIVING WS-NUMBER-3.

Page 26: cobol

DIVIDE WS-NUMBER-1 INTO WS-NUMBER-2 GIVING WS-NUMBER-3 REMAINDER WS-NUMBER-4.

SUBTRACT WS-NUMBER-1 FROM WS-NUMBER-2 GIVING WS-NUMBER-3. 

This is all very silly, but COBOL is an old language. As you can see, the GIVING clause is optional.

There is an additional clause you may add to the end :

ADD WS-NUMBER-1 TO WS-NUMBER-2 

ON SIZE ERROR

    DISPLAY "Size error"

NOT SIZE ERROR

    DISPLAY WS-NUMBER-1

END-ADD

Proced ural Abstraction

Just like Pascal and C, COBOL allows you to split your code up into small procedures. This is what the PROCEDURE DIVISION portion of a program will resemble when the PERFORM keyword is used to split the code into separate procedures. In this example the procedures (with names like PARA-ONE) call each other in turn :

CONTROL-PARA.

.....................

PERFORM PARA-TWO.

DISPLAY "Paragraph two has been executed".

STOP RUN.

PARA-ONE.

.....................

PARA-TWO.

.....................

PERFORM PARA-THREE.

DISPLAY "Paragraph three has been executed"

Page 27: cobol

PARA-THREE.

DISPLAY "This is the last paragraph"

..................

Note that the paragraph names are arbitrary, and nothing explicitly marks the end of them. They can be called with PERFORM followed by their name. Also, unlike in Pascal, the code to be executed when the program begins is before the other procedures. Make sure the last statement in the first paragraph is STOP RUN or you will find yourself in a lot of trouble.

Sections

A whole group of paragraphs can be combined in a larger structure called a SECTION. A section can then be called with PERFORM, so in effect a section is like a sub-program.

SEC-ONE SECTION.

SEC-CONTROL.

................

PERFORM SEC-ONE-ONE.

..............

GO TO SEC-EXIT.

SEC-ONE-ONE.

.....................

SEC-EXIT.

EXIT.

This could then be called by :

PERFORM SECTION-ONE. Control is then passed to the first paragraph in SECTION-ONE, and doesn't return to the rest of the program until GO TO is executed. This is the equivalent of STOP RUN.

In case you were wondering, these aren't really procedures in the Pascal sense. You cannot pass them parameters, and they can't create their own independent variables - everything is global in COBOL.

Control Structures : Selection

COBOL has fewer structures for controlling program flow than other languages like C, but it does the job. 

Control Structures rely on conditionals to evaluate between alternatives. COBOL includes the following :

Page 28: cobol

<, >, >=, <=, =, NOT=

These are self explanatory, and they also have word form equivalents:

LESS, GREATER, GREATER OR EQUAL, LESS OR EQUAL, EQUAL, NOT EQUAL

There are also the three main logical operators :

AND, NOT, OR

Selection statements can now be made as follows :

IF  WS-NUMBER-1 > 100

THEN

    DISPLAY "Greater than 100".

   ...........

END IF.

We can also add an ELSE clause :

IF  WS-NUMBER-1 > 100

THEN

    DISPLAY "Greater than 100". 

ELSE

    DISPLAY "Not greater than 100"   

END IF.

You can also nest selection structures inside other selection structures, just remember to put the right number of END IF statements in.

There is also the equivalent of the Pascal Case statement. This one evaluates WS-NUMBER-1, and calls a different procedure for each possible value :

ACCEPT WS-NUMBER-1.

EVALUATE WS-NUMBER-1

    WHEN "1" PERFORM PARA-ONE

    WHEN "2" PERFORM PARA-TWO

Page 29: cobol

    WHEN "3" PERFORM PARA-THREE

    WHEN OTHER PERFORM PARA-FOUR

END-EVALUATE

You can also test to see if a piece of data is one of four class types :

ALPHABETIC, ALPHABETIC-UPPER, ALPHABETIC-LOWER, NUMERIC

So we can have statements like

IF WS-NUMBER-1 NUMERIC ......

Control Structures : Iteration

The Pascal While statement can be performed like this :

ACCEPT WS-NUMBER-1

PERFORM UNTIL WS-NUMBER-1 > 100

                        AND WS-NUMBER-1 < 1000

     DISPLAY "Still between 100 and 1000"

     ACCEPT WS-NUMBER-1

END-PERFORM

The Pascal For statement is implemented  like this :

 PERFORM TEST AFTER VARYING WS-INDEX FROM

        1 BY 1 UNTIL WS-INDEX = 10

    DISPLAY "WS-INDEX is now equal to " WS-INDEX

END-PERFORM

This is more complex than Pascal, but it is still pretty obvious what is going on - it starts at 1, increments by 1, and goes until 10.

Records

A record is a set of related information grouped together. They are extremely common in COBOL applications. Here is how one might be declared in COBOL to hold information about a person :

DATA DIVISION

Page 30: cobol

WORKING STORAGE SECTION

01 WS-PERSON-RECORD

    03 WS-NAME        PIC X(20)

    03 WS-ADDRESS  PIC X(40)

    03 WS-AGE            PIC 9(2)

01 WS-STRING          PIC X(80)

Note that the top line has no PIC clause - this is the group item. The others are the elementary items. 

We can now use this is various ways. Firstly, we can initialize it as empty like this :

MOVE SPACES TO WS-PERSON-RECORD

We can now put some values into the elements :

MOVE 22 TO WS-AGE

MOVE "Dane" TO WS-NAME

MOVE "New Zealand" TO WS-ADDRESS

MOVE WS-ADDRESS TO WS-STRING

DISPLAY WS-STRING.

This is also possible :

MOVE WS-PERSON-RECORD TO WS-STRING

DISPLAY WS-STRING

The data in a record is alphanumeric. Even if it is a number, though, arithmetic arguments can't be applied to it.

You can also nest records inside records :

01 WS-PERSON-RECORD

    03 WS-NAME                PIC X(20)

    03 WS-ADDRESS

        05 WS-STREET        PIC X(20)

        05 WS-CITY            PIC X(20)

Page 31: cobol

Note now that WS-ADDRESS doesn't have a PIC clause.

The reason the levels have been ordered 01, 03, 05 is simple. They could be ordered 01, 02, 03; but then if you wanted to insert a new level between 01 and 02, you would also have to change the value of 03.

Notice that you can directly reference a field, unlike in Pascal where you need to use A dot operator like  RecordName.FieldName. However, if a field name is used elsewhere for another purpose you need to give the record name :

MOVE SPACES TO WS-AGE IN WS-PERSON-RECORD

Sequential Files

A sequential file consists of a sequence of data items terminated by an end marker, and stored on a disk or some other permanent storage device.

To use a sequential file in COBOL you must make declarations in three of the four divisions.

Firstly, the following code is placed in the ENVIRONMENT DIVISION :

ENVIRONMENT DIVISION

INPUT-OUTPUT SECTION.

FILE-CONTROL.

    SELECT DATA-FILE-1

    ASSIGN TO DEVICE-NAME

    ORGANIZATION IS SEQUENTIAL

    ACCESS MODE IS SEQUENTIAL

Actually, the last two lines aren't needed since they are the default conditions for a sequential file.

Each file that is going to be used must have its own SELECT division.

With regards to DEVICE-NAME, this can vary, but usually DISK and PRINTER will be two of the options available.

Each file must also be defined in the DATA DIVISION section:

DATA DIVISION.

FILE SECTION.

FD DATA-FILE-1.

    01 PERSON-REC.

Page 32: cobol

        03 NAME            PIC X(20)

        03 ADDRESS      PIC X(30)

These records are defined just the same as those in the WORKING-STORAGE section.

Now we can use READ and WRITE to work with these files in the PROCEDURE DIVISION section, but first it must be opened in this section. This code opens the file and transfers the first record to the record area defiled in FILE SECTION :

PROCEDURE DIVISON.

PARA-1.

    OPEN INPUT DATA-FILE-1.

    READ DATA-FILE-1

        AT END

            MOVE "E" TO WS-END-OF-DATA-FILE.

To open a file for writing use the structure :

OPEN OUTPUT DATA-FILE-1.

The AT END clause is necessary : it tells the file what to do when it hits the end of the file. In this example a status variable is assigned to WS-END-OF-DATA-FILE. Naturally, this needs to be declared and initialized earlier like this :

WORKING-STORAGE SECTION.

    01 WS-END-OF-DATA-FILE        PIC X

                        VALUE "N".

It is also useful to add a condition name like this on the next line :

        88 END-OF-DATA-FILE        VALUE "E"

We can now test for the end of the file in a loop :

PROCEDURE DIVISION

PARA-1.

    OPEN INPUT DATA-FILE-1.

    READ DATA-FILE-1.

Page 33: cobol

        AT END

            MOVE "E" TO WS-END-OF-DATA-FILE

        NOT AT END

            ADD 1 TO RECORD-COUNT

    END READ

............

Given that RECORD-COUNT had been declared, it would count the number of records in the file.

We use the keyword WRITE to transfer data to a file. This code opens a file and writes a record :

PROCEDURE DIVISION.

PARA-1.

    OPEN OUTPUT DATA-FILE-1.

    MOVE "Dane" TO NAME

    MOVE "New Zealand" TO ADDRESS.

    WRITE PERSON-REC.

    CLOSE DATA-FILE-1.

............

Take into account though, that is DATA-FILE-1 already had data in it, a new file would be created, and the old data would be written over. Also note that unlike READ which accepted a file name as its parameter, WRITE accepts a record name. Also remember to CLOSE each file you open or bad things will happen.

WRITE also allows you to append records to an existing file. Simply declare the file as in the previous examples, and then open it with the following code :

    OPEN     EXTEND    DATA-FILE-1.

It is also possible to edit existing records in place by opening the file for input and output. This code searches the file for a record with a certain address, and then changes that address (note : RECORD-FOUND must first be declared in a similar fashion to WS-END-OF-DATA-FILE) :

PROCEDURE DIVISION.

PARA-1.

Page 34: cobol

        OPEN  I-O DATA-FILE-1.

        READ DATA-FILE-1

            AT END

                MOVE "E" TO WS-END-OF-DATA-FILE

                DISPLAY "DATA NOT FOUND"

        END-READ

        PERFORM UNTIL END-OF-DATA-FILE OR RECORD-FOUND

            IF ADDRESS = "New Zealand"

                THEN

                    MOVE "Australia" TO ADDRESS

                    REWRITE PERSON-REC

                    MOVE "Y" TO WS-RECORD-FOUND

            ELSE

                READ DATA-FILE-1

                AT END

                    MOVE "E" TO WS-END-OF-DATA-FILE

                    DISPLAY "DATA NOT FOUND"

                END-READ

            END-IF

        END-PERFORM

        CLOSE DATA-FILE-1

        STOP RUN.

COBOL also allows you to create indexed files.

Data Editing

Page 35: cobol

COBOL is mainly a language for creating data storage applications, so it has many built in facilities for data editing and report making. COBOL can handle these topics far better than other structured languages like Pascal and C.

A common situation in report writing is the need to write right aligned output like this

$200.50

$45,600.00

$20.00

$1,800,900.00

This would be very difficult in many languages, but COBOL can easily handle it. We simply create a data type like this :

    01 WS-CURRENCY-OUTPUT        PIC $$,$$$,$$9.99.

This is how the following numbers would be outputted :

2050            $20.50

3045000    $30,450.00

50             $0.50

As you can see, a number signaled by a "$" is only included if it's needed, and the output is right aligned.

Remember that these special data types are only used for output, you can't do arithmetic with them. 

You can also do the same thing with "+" and "-" signs :

PIC ++++++9.99

PIC ----9.9

This allows you to get rid of irrelevant zeros when you are outputting data.

Arrays        

Arrays aren't quite as natural to COBOL as they are to most other languages, but that is a sign of COBOL's age. Here is how an array might be created to store the salaries of ten employees :

01 WS-EMPLOYEE-REC

    03 WS-EMPLOYEE-SALARY    PIC 99999

        OCCURS 10 TIMES

Page 36: cobol

You may think it would make sense to declare all this at level 01, but the OCCURS clause cannot be used at level 01.

You can then use parenthesis to refer to a particular element in the array :

DISPLAY  WS-EMPLOYEE-SALARY(3)

This will print out the fifth element (as opposed to C, where it would print out the sixth element).

We can create a variable like WS-INDEX, and use it in place of the number :

DISPLAY  WS-EMPLOYEE-SALARY(WS-INDEX)

But we can't use expressions like :

DISPLAY  WS-EMPLOYEE-SALARY(WS-INDEX + 1)

The value of WS-INDEX would need to be incremented before hand.

It is also simple to declare an array of records. This code creates 20 records with three fields each :

01 EMPLOYEE-REC-TABLE

    03 WS-EMPLOYEES    OCCURS 50 TIMES.

            05 WS-NAME        PIC X(20)

            05 WS-ADDRESS  PIC X(40)

            05 WS-SALARY    PIC 99999

We can now refer to an entire record at a time with :

WS-EMPLOYEE(10)

Or to a single field of a record :

WS-ADDRESS(30)

We can also create multi-dimensional arrays :

01 WS-TABLE VALUE ZEROS.

    03 WS-MONTH

            OCCURS 12 TIMES

        05 WS-FIVE-HIGHEST-TEMPERATURES    PIC 999

            OCCURS 5 TIMES

Page 37: cobol

Note here the VALUE ZEROS. clause : this initializes all the elements to zero (including strings).

We can now access a specific element like this (which shows the 2nd highest temperature in May):

WS-TABLE(5, 2)

Or we could access all the temperatures for November like this :

WS-MONTH(11)

Indexed Files

Indexed Files have an advantage over sequential files in the sense that they can be accessed randomly. To find a record in a sequential file we need to look through all the records in order, but with an indexed file we can identify and retrieve records according to their unique key values.

This is how a file might be declared in the ENVIRONMENT DIVISION section :

ENVIRONMENT DIVISION.

INPUT-OUTPUT SECTION.

FILE-CONTROL.

        SELECT EMPLOYEE-FILE

        ASSIGN TO DISK

        ORGANIZATION IS INDEXED

        ACCESS MODE IS RANDOM

        RECORD KEY IS EMPLOYEE-NUMBER

        FILE STATUS IS EMPLOYEE-STATUS

The RECORD KEY is equivalent to a primary key in a relational database. Bare in mind that this cannot be changed once the record has been created.

The FILE STATUS clause is optional. It is must be declared as a two byte character in WORKING-STORAGE, and is used mainly for error handling.

The declaration in DATA DIVISION is the same as with sequential files, but remember to use the same key value as in ENVIRONMENT DIVISION :

DATA DIVISION.

FILE SECTION.

FD    EMPLOYEE-FILE.

Page 38: cobol

    01 EMPLOYEE-REC.

        03 EMPLOYEE-NUMBER        PIC X(6).

        03 EMPLOYEE-NAME             PIC X(20).

        03 EMPLOYEE-SALARY          PIC 9(5).

WORKING-STORAGE SECTION.

    01 EMPLOYEE-STATUS               PIC XX.

We can now move onto the PROCEDURE DIVISION section.

Firstly we must open the file for input and output :

OPEN    I-O    EMPLOYEE-FILE.

Also, remember to close it when you have finished :

CLOSE EMPLOYEE-FILE.

To work with the file we use the keywords READ, WRITE, DELETE and REWRITE.

If we want to read a file, we give the key value of the record we want, and if it exists it will be transferred into the file's record area :

        MOVE "AR8763" TO EMPLOYEE-NUMBER.

        READ EMPLOYEE-FILE

            INVALID KEY

                DISPLAY "No such file exists."

This is how we write a record to file, supposing the variables mentioned had been created in the WORKING-STORAGE section :

        MOVE "RW3425" TO WS-EMPLOYEE-NUMBER

        MOVE "JERRY SEINFELD" TO WS-EMPLOYEE-NAME.

        MOVE 56000 TO WS-EMPLOYEE-SALARY

        WRITE EMPLOYEE-REC FROM WS-EMPLOYEE-REC.

We have first put the values into an intermediary storage area, and then written the record to file in one go.

To modify a record we would usually do a READ followed by a REWRITE  :

Page 39: cobol

        MOVE "RW3425" TO WS-EMPLOYEE-NUMBER

        MOVE "KRAMER" TO WS-EMPLOYEE-NAME

        MOVE 65000 TO WS-EMPLOYEE-SALARY

        REWRITE EMPLOYEE-REC FROM WS-EMPLOYEE-REC

            INVALID KEY

                DISPLAY "Record doesn't exist."

This is how we could delete the record we just created (you would normally do a READ first to make sure you have the right record :

        MOVE "RW3425" TO EMPLOYEE-NUMBER

        DELETE EMPLOYEE-FILE

            INVALID KEY

                DISPLAY "That record doesn't exist."

    

1. This example program is almost the shortest COBOL program we can have. We could make it shorter still by leaving out the STOP RUN.

IDENTIFICATION DIVISION.PROGRAM-ID. ShortestProgram.PROCEDURE DIVISION.DisplayPrompt. DISPLAY "I did it". STOP RUN.

2. The program accepts a simple student record from the user and displays the individual fields. Also shows how the ACCEPT may be used to get and DISPLAY the system time and date.

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

* The YYYYMMDD in "ACCEPT CurrentDate FROM DATE YYYYMMDD." * is a format command that ensures that the date contains a * 4 digit year. If not used, the year supplied by the system will

Page 40: cobol

* only contain two digits which may cause a problem in the year 2000.

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

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

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

* HHMMSSss s = S/10001 CurrentTime. 02 CurrentHour PIC 99. 02 CurrentMinute PIC 99. 02 FILLER PIC 9(4).PROCEDURE DIVISION.Begin. DISPLAY "Enter student details using template below". DISPLAY "Enter - ID,Surname,Initials,CourseCode,Gender" DISPLAY "SSSSSSSNNNNNNNNIICCCCG". ACCEPT StudentDetails. ACCEPT CurrentDate FROM DATE YYYYMMDD. ACCEPT DayOfYear FROM DAY YYYYDDD. ACCEPT CurrentTime FROM TIME. DISPLAY "Name is ", Initials SPACE Surname. DISPLAY "Date is " CurrentDay SPACE CurrentMonth SPACE CurrentYear. DISPLAY "Today is day " YearDay " of the year". DISPLAY "The time is " CurrentHour ":" CurrentMinute. STOP RUN.

3. Accepts two single digit numbers from the user, multiplies them together and displays the result.

IDENTIFICATION DIVISION.PROGRAM-ID. Multiplier.AUTHOR. Michael Coughlan.* Example program using ACCEPT, DISPLAY and MULTIPLY to * get two single digit numbers from the user and multiply them together

Page 41: cobol

DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.PROCEDURE DIVISION. DISPLAY "Enter first number (1 digit) : " WITH NO ADVANCING. ACCEPT Num1. DISPLAY "Enter second number (1 digit) : " WITH NO ADVANCING. ACCEPT Num2. MULTIPLY Num1 BY Num2 GIVING Result. DISPLAY "Result is = ", Result. STOP RUN.

SELECTION AND ITERATION

4. An example program that implements a primitive calculator. The calculator only does additions and multiplications. IDENTIFICATION DIVISION.PROGRAM-ID. Iteration-If.AUTHOR. Michael Coughlan.DATA DIVISION.WORKING-STORAGE SECTION.01 Num1 PIC 9 VALUE ZEROS.01 Num2 PIC 9 VALUE ZEROS.01 Result PIC 99 VALUE ZEROS.01 Operator PIC X VALUE SPACE.PROCEDURE DIVISION.Calculator. PERFORM 3 TIMES DISPLAY "Enter First Number : " WITH NO ADVANCING ACCEPT Num1 DISPLAY "Enter Second Number : " WITH NO ADVANCING ACCEPT Num2 DISPLAY "Enter operator (+ or *) : " WITH NO ADVANCING ACCEPT Operator IF Operator = "+" THEN ADD Num1, Num2 GIVING Result END-IF IF Operator = "*" THEN MULTIPLY Num1 BY Num2 GIVING Result END-IF DISPLAY "Result is = ", Result END-PERFORM. STOP RUN.5. An example program demonstrating the use of Condition Names (level 88's).  IDENTIFICATION DIVISION.PROGRAM-ID. Conditions.AUTHOR. Michael Coughlan.* An example program demonstrating the use of

Page 42: cobol

* condition names (level 88's).* The EVALUATE and PERFORM verbs are also used.DATA DIVISION.WORKING-STORAGE SECTION.01 Char PIC X. 88 Vowel VALUE "a", "e", "i", "o", "u". 88 Consonant VALUE "b", "c", "d", "f", "g", "h" "j" THRU "n", "p" THRU "t", "v" THRU "z". 88 Digit VALUE "0" THRU "9". 88 ValidCharacter VALUE "a" THRU "z", "0" THRU "9".PROCEDURE DIVISION.Begin. DISPLAY "Enter lower case character or digit. No data ends.". ACCEPT Char. PERFORM UNTIL NOT ValidCharacter EVALUATE TRUE WHEN Vowel DISPLAY "The letter " Char " is a vowel." WHEN Consonant DISPLAY "The letter " Char " is a consonant." WHEN Digit DISPLAY Char " is a digit." WHEN OTHER DISPLAY "problems found" END-EVALUATE END-PERFORM STOP RUN.6. An example program demonstrating how the first format of the PERFORM may be used to change the flow of control through a program. IDENTIFICATION DIVISION.PROGRAM-ID. PerformFormat1.AUTHOR. Michael Coughlan.* Illustrates how the first format of the PERFORM may* be used to change the flow of control through a program.* Use the output of this program to get an understanding of how* this format of the PERFORM works.PROCEDURE DIVISION.TopLevel. DISPLAY "In TopLevel. Starting to run program" PERFORM OneLevelDown DISPLAY "Back in TopLevel.". STOP RUN.TwoLevelsDown. DISPLAY ">>>>>>>> Now in TwoLevelsDown." PERFORM ThreeLevelsDown. DISPLAY ">>>>>>>> Back in TwoLevelsDown.".OneLevelDown. DISPLAY ">>>> Now in OneLevelDown" PERFORM TwoLevelsDown DISPLAY ">>>> Back in OneLevelDown".ThreeLevelsDown. DISPLAY ">>>>>>>>>>>> Now in ThreeLevelsDown".

Page 43: cobol

7. Demonstrates the second format of the PERFORM. The PERFORM..TIMES may be used to execute a block of code x number of times.IDENTIFICATION DIVISION.

PROGRAM-ID. PerformFormat2.AUTHOR. Michael Coughlan.* Demonstrates the second format of the PERFORM.* The PERFORM..TIMES format executes a block of code x * number of times.DATA DIVISION.WORKING-STORAGE SECTION.01 NumofTimes PIC 9 VALUE 5.PROCEDURE DIVISION.Begin. DISPLAY "Starting to run program" PERFORM 3 TIMES DISPLAY ">>>>This is an in line Perform" END-PERFORM DISPLAY "Finished in line Perform" PERFORM OutOfLineEG NumOfTimes TIMES DISPLAY "Back in Begin. About to Stop". STOP RUN.OutOfLineEG.

DISPLAY ">>>> This is an out of line Perform".

8. Demonstrates how the PERFORM..UNTIL (third format) may be used to process a stream of values where the length of the stream cannot be determined in advance (although in this case there is a set maximum number of values in the stream). 

IDENTIFICATION DIVISION.PROGRAM-ID. PerformFormat3.AUTHOR. Michael Coughlan.* Demonstrates the use of the PERFORM..UNTIL.* The PERFORM..UNTIL is most often used to process a * stream of data where the length of the stream can not * be determined in advance.* Pay particular attention to the way the number stream is * processed in this program.* Note how the ON SIZE ERROR can be used to detect when the* result of a computation is tot big for the data-item intended* to hold it.* The INITIALIZE verb sets a data-item to its initial or * starting value.DATA DIVISION.WORKING-STORAGE SECTION.01 IterCount PIC 99 VALUE ZEROS. 88 MaxCountReached VALUE 99.01 UserInput PIC 99 VALUE ZEROS.

Page 44: cobol

88 EndOfUserInput VALUE ZEROS.01 RunningTotal PIC 999 VALUE ZEROS.01 AverageValue PIC 99 VALUES ZEROS.

PROCEDURE DIVISION.Begin. PERFORM UNTIL IterCount = 5 DISPLAY "IterCount = " IterCount ADD 1 TO IterCount END-PERFORM DISPLAY "Finished in line Perform." INITIALIZE Itercount DISPLAY "Enter a stream of up to 99 numbers." DISPLAY "Each number must be in the range 1-99. Enter 0 to stop." DISPLAY "Enter number :- " WITH NO ADVANCING ACCEPT UserInput PERFORM GetUserInput UNTIL EndOfUserInput OR MaxCountReached DISPLAY "The final total is - " RunningTotal DISPLAY "The final count is - " IterCount COMPUTE AverageValue = RunningTotal / IterCount DISPLAY "The average value entered is - " AverageValue STOP RUN.GetUserInput. ADD UserInput TO RunningTotal ON SIZE ERROR DISPLAY "Error - new total too large for data-item." NOT ON SIZE ERROR ADD 1 TO IterCount END-ADD END-ADD DISPLAY "Total so far is - " RunningTotal DISPLAY "Count so far is - " IterCount DISPLAY "Enter number :- " WITH NO ADVANCING

ACCEPT UserInput.

9. Demonstrates how the PERFORM..VARYING and the PERFORM..VARYING..AFTER (fourth format) may be used for counting iteration. Also introduces the WITH TEST BEFORE and WITH TEST AFTER phrases.

IDENTIFICATION DIVISION.PROGRAM-ID. PerformFormat4.AUTHOR. Michael Coughlan.* An example program using the PERFORM..VARYING format.* Pay particular attention to the values produced by the* WITH TEST BEFORE and WITH TEST AFTER loops.* Note that the PERFORM within a PERFORM produces the same* results as the PERFORM..VARYING..AFTERDATA DIVISION.WORKING-STORAGE SECTION.01 LoopCount PIC 9 VALUE ZEROS.01 LoopCount2 PIC S9 VALUE ZEROS.PROCEDURE DIVISION.

Page 45: cobol

Begin. DISPLAY "Start WHILE Iteration of LoopBody" PERFORM LoopBody WITH TEST BEFORE VARYING LoopCount FROM 1 BY 2 UNTIL LoopCount GREATER THAN 5. DISPLAY "Finished WHILE iteration. LoopCount = " LoopCount. DISPLAY "Start REPEAT Iteration of LoopBody" PERFORM LoopBody WITH TEST AFTER VARYING LoopCount FROM 1 BY 2 UNTIL LoopCount GREATER THAN 5. DISPLAY "Finished REPEAT iteration. LoopCount = " LoopCount. DISPLAY "Start inline loops" PERFORM VARYING LoopCount FROM 1 BY 1 UNTIL LoopCount GREATER THAN 4 PERFORM VARYING LoopCount2 FROM 5 BY -2 UNTIL LoopCount2 LESS THAN ZERO DISPLAY "InLine loop " WITH NO ADVANCING DISPLAY "LoopCount = " LoopCount " LoopCount2 = " LoopCount2 END-PERFORM END-PERFORM. DISPLAY "Finished inline loops". DISPLAY "Start PERFORM VARYING..AFTER". PERFORM LoopBody VARYING LoopCount FROM 1 BY 1 UNTIL LoopCount GREATER THAN 4 AFTER LoopCount2 FROM 5 BY -2 UNTIL LoopCount2 LESS THAN ZERO. DISPLAY "Finished PERFORM VARYING..AFTER". STOP RUN.LoopBody. DISPLAY "LoopBody " WITH NO ADVANCING DISPLAY "LoopCount = " LoopCount " LoopCount2 = " LoopCount2.

10. Demonstrates how the PERFORM..VARYING and the PERFORM..VARYING..AFTER (fourth format) may be used to simulate a mileage counter. 

IDENTIFICATION DIVISION.PROGRAM-ID. MileageCounter.AUTHOR. Michael Coughlan.* Simulates a mileage counterDATA DIVISION.WORKING-STORAGE SECTION.01 Counters. 02 HundredsCount PIC 99 VALUE ZEROS. 02 TensCount PIC 99 VALUE ZEROS. 02 UnitsCount PIC 99 VALUE ZEROS.01 DisplayItems. 02 PrnHunds PIC 9. 02 PrnTens PIC 9.

Page 46: cobol

02 PrnUnits PIC 9.PROCEDURE DIVISION.Begin. DISPLAY "Using an out-of-line Perform". DISPLAY "About to start mileage counter simulation". PERFORM CountMilage VARYING HundredsCount FROM 0 BY 1 UNTIL HundredsCount > 9 AFTER TensCount FROM 0 BY 1 UNTIL TensCount > 9 AFTER UnitsCount FROM 0 BY 1 UNTIL UnitsCount > 9 DISPLAY "End of mileage counter simulation." DISPLAY "Now using in-line Performs" DISPLAY "About to start mileage counter simulation". PERFORM VARYING HundredsCount FROM 0 BY 1 UNTIL HundredsCount > 9 PERFORM VARYING TensCount FROM 0 BY 1 UNTIL TensCount > 9 PERFORM VARYING UnitsCount FROM 0 BY 1 UNTIL UnitsCount > 9 MOVE HundredsCount TO PrnHunds MOVE TensCount TO PrnTens MOVE UnitsCount TO PrnUnits DISPLAY PrnHunds "-" PrnTens "-" PrnUnits END-PERFORM END-PERFORM END-PERFORM. DISPLAY "End of mileage counter simulation." STOP RUN.CountMilage. MOVE HundredsCount TO PrnHunds MOVE TensCount TO PrnTens MOVE UnitsCount TO PrnUnits DISPLAY PrnHunds "-" PrnTens "-" PrnUnits.

SEQUENTIAL FILE

11. Example program demonstrating how to create a sequential file from data input by the user. 

IDENTIFICATION DIVISION.PROGRAM-ID. SeqWrite.AUTHOR. Michael Coughlan.* Example program showing how to create a sequential file* using the ACCEPT and the WRITE verbs.* Note: In this version of COBOL pressing the Carriage Return (CR)* without entering any data results in StudentDetails being filled* with spaces.ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL. SELECT StudentFile ASSIGN TO "STUDENTS.DAT" ORGANIZATION IS LINE SEQUENTIAL.DATA DIVISION.FILE SECTION.

Page 47: cobol

FD StudentFile.01 StudentDetails. 02 StudentId PIC 9(7). 02 StudentName. 03 Surname PIC X(8). 03 Initials PIC XX. 02 DateOfBirth. 03 YOBirth PIC 9(4). 03 MOBirth PIC 9(2). 03 DOBirth PIC 9(2). 02 CourseCode PIC X(4). 02 Gender PIC X.PROCEDURE DIVISION.Begin. OPEN OUTPUT StudentFile DISPLAY "Enter student details using template below. Enter no data to end." PERFORM GetStudentDetails PERFORM UNTIL StudentDetails = SPACES WRITE StudentDetails PERFORM GetStudentDetails END-PERFORM CLOSE StudentFile STOP RUN.GetStudentDetails. DISPLAY "Enter - StudId, Surname, Initials, YOB, MOB, DOB, Course, Gender" DISPLAY "NNNNNNNSSSSSSSSIIYYYYMMDDCCCCG"

ACCEPT StudentDetails.

12. An example program that reads a sequential file and displays the records. This version does not use level 88's to signal when the end of the file has been reached.To test the program download thistestdata file.

IDENTIFICATION DIVISION.PROGRAM-ID. SeqReadNo88.AUTHOR. Michael Coughlan.* An example showing how to read a sequential file without* using condition names.* See SeqRead.CBL for the definitive example.ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL. SELECT StudentFile ASSIGN TO "STUDENTS.DAT"

ORGANIZATION IS LINE SEQUENTIAL.DATA DIVISION.FILE SECTION.FD StudentFile.01 StudentDetails. 02 StudentId PIC 9(7). 02 StudentName.

Page 48: cobol

03 Surname PIC X(8). 03 Initials PIC XX. 02 DateOfBirth. 03 YOBirth PIC 9(4). 03 MOBirth PIC 9(2). 03 DOBirth PIC 9(2). 02 CourseCode PIC X(4). 02 Gender PIC X.PROCEDURE DIVISION.Begin. OPEN INPUT StudentFile READ StudentFile AT END MOVE HIGH-VALUES TO StudentDetails END-READ PERFORM UNTIL StudentDetails = HIGH-VALUES DISPLAY StudentId SPACE StudentName SPACE CourseCode SPACE YOBirth READ StudentFile AT END MOVE HIGH-VALUES TO StudentDetails END-READ END-PERFORM CLOSE StudentFile

STOP RUN.

13. An example program that reads a sequential file and displays the records. This is the correct version which uses the Condition Name (level 88) "EndOfFile"to signal when the end of the file has been reached.To test the program download this testdata file.

IDENTIFICATION DIVISION.PROGRAM-ID. SeqRead.AUTHOR. Michael Coughlan.* An example program showing how to read a sequential file.* This is the definitive example ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL. SELECT StudentFile ASSIGN TO "STUDENTS.DAT"

ORGANIZATION IS LINE SEQUENTIAL.DATA DIVISION.FILE SECTION.FD StudentFile.01 StudentDetails. 88 EndOfStudentFile VALUE HIGH-VALUES. 02 StudentId PIC 9(7). 02 StudentName. 03 Surname PIC X(8). 03 Initials PIC XX. 02 DateOfBirth. 03 YOBirth PIC 9(4). 03 MOBirth PIC 9(2).

Page 49: cobol

03 DOBirth PIC 9(2). 02 CourseCode PIC X(4). 02 Gender PIC X.PROCEDURE DIVISION.Begin. OPEN INPUT StudentFile READ StudentFile AT END SET EndOfStudentFile TO TRUE END-READ PERFORM UNTIL EndOfStudentFile DISPLAY StudentId SPACE StudentName SPACE CourseCode SPACE YOBirth READ StudentFile AT END SET EndOfStudentFile TO TRUE END-READ END-PERFORM CLOSE StudentFile STOP RUN.

14. Demonstrates how to insert records into a sequential file from a file of transaction records. A new file is created which contains the inserted records.To test this program you will need to download Student Masterfile - Students.Dat and the Transaction file Transins.dat. 

IDENTIFICATION DIVISION.PROGRAM-ID. InsertRecords.AUTHOR. Michael Coughlan.* This program updates the Students.Dat file with insertions* taken from the Transins.Dat file to create a new file* - Students.New - which contains the inserted records.

ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL. SELECT StudentRecords ASSIGN "STUDENTS.DAT" ORGANIZATION IS LINE SEQUENTIAL ACCESS MODE IS SEQUENTIAL.

SELECT TransRecords ASSIGN "TRANSINS.DAT" ORGANIZATION IS LINE SEQUENTIAL ACCESS MODE IS SEQUENTIAL.

SELECT NewStudentRecords ASSIGN "STUDENTS.NEW" ORGANIZATION IS LINE SEQUENTIAL ACCESS MODE IS SEQUENTIAL.DATA DIVISION.FILE SECTION.FD StudentRecords.01 StudentRecord. 88 EndOfStudentFile VALUE HIGH-VALUES. 02 StudentID PIC X(7).

Page 50: cobol

02 FILLER PIC X(23).FD TransRecords.01 TransRecord. 88 EndOfTransFile VALUE HIGH-VALUES. 02 TransStudentID PIC X(7). 02 FILLER PIC X(23).FD NewStudentRecords.01 NewStudentRecord PIC X(30).PROCEDURE DIVISION.BEGIN. OPEN INPUT StudentRecords OPEN INPUT TransRecords OPEN OUTPUT NewStudentRecords

READ StudentRecords AT END SET EndOfStudentFile TO TRUE END-READ READ TransRecords AT END SET EndOfTransFile TO TRUE END-READ PERFORM UNTIL (EndOfStudentFile) AND (EndOfTransFile) EVALUATE TRUE WHEN (StudentID < TransStudentID) WRITE NewStudentRecord FROM StudentRecord READ StudentRecords AT END SET EndOfStudentFile TO TRUE END-READ WHEN (StudentID > TransStudentID) WRITE NewStudentRecord FROM TransRecord READ TransRecords AT END SET EndOfTransFile TO TRUE END-READ WHEN (StudentID = TransStudentID) DISPLAY "Error - " TransStudentId " already exists in file" READ TransRecords AT END SET EndOfTransFile TO TRUE END-READ END-EVALUATE END-PERFORM CLOSE StudentRecords CLOSE TransRecords CLOSE NewStudentRecords STOP RUN.

15. This program reads records from the student file, counts the total number of student records in the file and the number records for females and males. Prints the results in a very short report.To test the program download Students.Dat IDENTIFICATION DIVISION.

PROGRAM-ID. StudentNumbersReport . AUTHOR. Michael Coughlan.

Page 51: cobol

*INPUT The student record file Students.Dat Records in this file * are sequenced on ascending Student Number. *OUTPUT Shows the number of student records in the file and the * number of records for males and females. *PROCESSING For each record read; * Adds one to the TotalStudents count * IF the Gender is Male adds one to TotalMales * IF the Gender is Female adds one to TotalFemales * At end of file writes the results to the report file. ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT StudentFile ASSIGN TO "STUDENTS.DAT" ORGANIZATION IS LINE SEQUENTIAL. SELECT ReportFile ASSIGN TO "STUDENTS.RPT" ORGANIZATION IS LINE SEQUENTIAL. DATA DIVISION. FILE SECTION. FD StudentFile. 01 StudentDetails. 88 EndOfStudentFile VALUE HIGH-VALUES. 02 StudentId PIC 9(7). 02 StudentName. 03 Surname PIC X(8). 03 Initials PIC XX. 02 DateOfBirth. 03 YOBirth PIC 9(4). 03 MOBirth PIC 9(2). 03 DOBirth PIC 9(2). 02 CourseCode PIC X(4). 02 Gender PIC X. 88 Male VALUE "M", "m". FD ReportFile. 01 PrintLine PIC X(40). WORKING-STORAGE SECTION. 01 HeadingLine PIC X(21) VALUE " Record Count Report". 01 StudentTotalLine. 02 FILLER PIC X(17) VALUE "Total Students = ". 02 PrnStudentCount PIC Z,ZZ9. 01 MaleTotalLine. 02 FILLER PIC X(17) VALUE "Total Males = ". 02 PrnMaleCount PIC Z,ZZ9. 01 FemaleTotalLine. 02 FILLER PIC X(17) VALUE "Total Females = ". 02 PrnFemaleCount PIC Z,ZZ9. 01 WorkTotals. 02 StudentCount PIC 9(4) VALUE ZERO. 02 MaleCount PIC 9(4) VALUE ZERO. 02 FemaleCount PIC 9(4) VALUE ZERO.

Page 52: cobol

PROCEDURE DIVISION. Begin. OPEN INPUT StudentFile OPEN OUTPUT ReportFile READ StudentFile AT END SET EndOfStudentFile TO TRUE END-READ PERFORM UNTIL EndOfStudentFile ADD 1 TO StudentCount IF Male ADD 1 TO MaleCount ELSE ADD 1 TO FemaleCount END-IF READ StudentFile AT END SET EndOfStudentFile TO TRUE END-READ END-PERFORM PERFORM PrintReportLines CLOSE StudentFile, ReportFile STOP RUN. PrintReportLines. MOVE StudentCount TO PrnStudentCount MOVE MaleCount TO PrnMaleCount MOVE FemaleCount TO PrnFemaleCount WRITE PrintLine FROM HeadingLine AFTER ADVANCING PAGE WRITE PrintLine FROM StudentTotalLine AFTER ADVANCING 2 LINES WRITE PrintLine FROM MaleTotalLine AFTER ADVANCING 2 LINES WRITE PrintLine FROM FemaleTotalLine AFTER ADVANCING 2 LINES.

Sorting & Merging

16. Uses the SORT and an INPUT PROCEDURE to accept records from the user and sort them on ascending StudentId.

IDENTIFICATION DIVISION.PROGRAM-ID. InputSort.AUTHOR. Michael Coughlan.* An example program using the SORT and an * INPUT PROCEDURE. The program accepts records* from the user and RELEASEs them to the work file* where they are sorted. This program* allows student records to be entered in any order but* produces a file sequenced on ascending StudentId. ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL. SELECT StudentFile ASSIGN TO "SORTSTUD.DAT"

ORGANIZATION IS LINE SEQUENTIAL.

Page 53: cobol

SELECT WorkFile ASSIGN TO "WORK.TMP".DATA DIVISION.FILE SECTION.FD StudentFile.01 StudentDetails PIC X(30).* The StudentDetails record has the description shown below.* But in this program we don't need to refer to any of the items in * the record and so we have described it as PIC X(32) * 01 StudentDetails* 02 StudentId PIC 9(7).* 02 StudentName.* 03 Surname PIC X(8).* 03 Initials PIC XX.* 02 DateOfBirth.* 03 YOBirth PIC 9(4).* 03 MOBirth PIC 9(2).* 03 DOBirth PIC 9(2).* 02 CourseCode PIC X(4).* 02 Gender PIC X.SD WorkFile.01 WorkRec. 02 WStudentId PIC 9(7). 02 FILLER PIC X(23).PROCEDURE DIVISION.Begin. SORT WorkFile ON ASCENDING KEY WStudentId INPUT PROCEDURE IS GetStudentDetails GIVING StudentFile. STOP RUN.GetStudentDetails. DISPLAY "Enter student details using template below." DISPLAY "Enter no data to end.". DISPLAY "Enter - StudId, Surname, Initials, YOB, MOB, DOB, Course, Gender" DISPLAY "NNNNNNNSSSSSSSSIIYYYYMMDDCCCCG" ACCEPT WorkRec. PERFORM UNTIL WorkRec = SPACES RELEASE WorkRec ACCEPT WorkRec END-PERFORM.

17. Sorts the student masterfile (sorted on ascending Student Id) and produces a new file, sorted on ascending student name, containing only the records of male students. To test the program download Students.Dat

IDENTIFICATION DIVISION.PROGRAM-ID. MaleSort.AUTHOR. Michael Coughlan.* Uses the the SORT and an INPUT PROCEDURE to read* the student masterfile (sorted on ascending Student Id)* and from it to produce a file containing only the records of* male students sorted on ascending student name.

Page 54: cobol

ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL. SELECT StudentFile ASSIGN TO "STUDENTS.DAT"

ORGANIZATION IS LINE SEQUENTIAL.

SELECT MaleStudentFile ASSIGN TO "MALESTUDS.DAT"ORGANIZATION IS LINE SEQUENTIAL.

SELECT WorkFile ASSIGN TO "WORK.TMP".DATA DIVISION.FILE SECTION.FD StudentFile.01 StudentRec PIC X(30). 88 EndOfFile VALUE HIGH-VALUES.FD MaleStudentFile.01 MaleStudentRec PIC X(30).

SD WorkFile.01 WorkRec. 02 FILLER PIC 9(7). 02 WStudentName PIC X(10). 02 FILLER PIC X(12). 02 WGender PIC X. 88 MaleStudent VALUE "M".PROCEDURE DIVISION.Begin. SORT WorkFile ON ASCENDING KEY WStudentName INPUT PROCEDURE IS GetMaleStudents GIVING MaleStudentFile. STOP RUN.GetMaleStudents. OPEN INPUT StudentFile READ StudentFile AT END SET EndOfFile TO TRUE END-READ PERFORM UNTIL EndOfFile MOVE StudentRec TO WorkRec IF MaleStudent RELEASE WorkRec END-IF READ StudentFile AT END SET EndOfFile TO TRUE END-READ END-PERFORM CLOSE StudentFile.

18. Uses the MERGE to insert records from a transaction file into a sequential master file.

To test this program you will need to download Student Masterfile - Students.Dat and the Transaction file Transins.dat. 

Page 55: cobol

IDENTIFICATION DIVISION.PROGRAM-ID. MergeFiles.AUTHOR. MICHAEL COUGHLAN.* Example program demonstrating the use of the MERGE.* The program merges the file Students.Dat and * Transins.Dat to create a new file Students.New.* A problem with using the MERGE for inserting records is that * duplicate records are not detected.* See the example program - SeqInsert.cbl - for a more traditional * approach to inserting records in a Sequential File.ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL. SELECT StudentFile ASSIGN TO "STUDENTS.DAT" ORGANIZATION IS LINE SEQUENTIAL. SELECT InsertionsFile ASSIGN TO "TRANSINS.DAT" ORGANIZATION IS LINE SEQUENTIAL. SELECT NewStudentFile ASSIGN TO "STUDENTS.NEW" ORGANIZATION IS LINE SEQUENTIAL. SELECT WorkFile ASSIGN TO "WORK.TMP".DATA DIVISION.FILE SECTION.FD StudentFile.01 StudentRec PIC X(30).FD InsertionsFile.01 InsertionRec PIC X(30).FD NewStudentFile.01 NewStudentRec PIC X(30).SD WorkFile.01 WorkRec. 02 WStudentId PIC 9(7). 02 FILLER PIC X(23).PROCEDURE DIVISION.Begin. MERGE WorkFile ON ASCENDING KEY WStudentId USING InsertionsFile, StudentFile GIVING NewStudentFile. STOP RUN.String handling

19. Solves a number of string handling tasks such as : - Extracting a substring from a string given the start position and length of the substring. Extracting the first x number of chars from a string.Extracting the last x number of chars from a string.Removing trailing blanks from a string. Removing leading blanks from a string. Finding the location of the first occurrence of any of a substring's chars in a string IDENTIFICATION DIVISION.PROGRAM-ID. RefModification.AUTHOR. Michael Coughlan.

Page 56: cobol

* An example program using Reference Modification, Intrinsic Functions* and the INSPECT.* The program solves a number of tasks suggested by Judy Yaeger in her* article "Character Manipulation Using COBOL" where she attempted to show* the limitations of COBOL string handling.DATA DIVISION.WORKING-STORAGE SECTION.01 xStr PIC X(50) VALUE " This is the first source string".01 xStr2 PIC X(32) VALUE "This is the second source string".01 StrSize PIC 99 VALUE 32.01 CharCount PIC 99 VALUE ZEROS.01 EndCount PIC 99 VALUE ZEROS.01 yStr PIC X(4) VALUE SPACES.01 CharPos PIC 99 VALUE ZEROS.01 StrLength PIC 99 VALUE ZEROS.PROCEDURE DIVISION.Begin.* Task1 substring(xStr, StartPos, Length)* Extract a substring from a string given the StartPos and Length.* Solution - use reference modification to get the substring.* In this example we get 3 characters starting at position 9 DISPLAY "Task1 = " xStr(9:3)* Task2 prefix(xStr,Length)* Extract the first Length number of chars from a string* Solution - use reference modification starting at position 1.* In this example we get the first 7 characters DISPLAY "Task2 = " xStr(1:7)* Task3 suffix(xStr,Length)* Extract the last Length number of chars from a string* Solution - use reference modification with start of substring* defined as the FullStringLength - SubStringLength + 1* In this example we get the last 13 characters. MOVE 13 TO StrLength DISPLAY "Task3 = " xStr2((StrSize - StrLength) + 1:StrLength)* Task4: trimblank(xStr)* Remove trailing blanks from a string* Solution 1 * Use the REVERSE intrinsic function to reverse the string* then use the INSPECT tallying to count the number of spaces at the* begining of the reversed string. The substring length is then the* FullSringLength - CharCount.* Use reference modification of get the substring. DISPLAY "Task4 Before = " xStr "<<<<<<" MOVE 0 TO CharCount INSPECT FUNCTION REVERSE(xStr) TALLYING CharCount FOR LEADING SPACES DISPLAY "Task4 After = "xStr(1:50 - CharCount) "<<<<<<<".* Solution 2* Use reference modification and the PERFORM..VARYING to* keep reducing the size of the substring until a non space character

Page 57: cobol

* is encountered. Then use reference modification to get the substring. PERFORM VARYING CharCount FROM 50 BY -1 UNTIL xStr(CharCount:1) NOT = SPACE END-PERFORM DISPLAY "Task4 After = "xStr(1:CharCount) "<<<<<<<".* Task5 Left_trimblank(xStr)* Remove leading blanks from a string.* Solution - Use the inspect to count the leading blanks and reference* modification to get the substring from the point indicated by CharCount* and for FullStrLength - CharCount characters. MOVE 1 TO CharCount. INSPECT xStr TALLYING CharCount FOR LEADING SPACES DISPLAY "Task5 =" xStr(CharCount: 50 - CharCount)* Task6 index(xStr,yStr)* Find the location of the first occurrence of substring yStr in xStr.* Solution - Use the INSPECT..TALLYING to count the characters before* the first occurrence of the substring. CharCount has the location.* In this example we get the position of the substring "source". MOVE 1 TO CharCount INSPECT xStr TALLYING CharCount for CHARACTERS BEFORE INITIAL "source". DISPLAY "Task6 First occurrence is in char position " CharCount* Task7 cindex(xStr,yStr)* Find the location of the first occurrence of any of the characters * in substring xStr, in string yStr* Solution - Use the PERFORM..VARYING and reference modification to* locate each of the characters in the yString. Then use the INSPECT to* find the position of each in the xString. Return whichever is the least. MOVE "fred" TO yStr MOVE 51 TO EndCount PERFORM VARYING CharPos FROM 1 BY 1 UNTIL CharPos > 4 MOVE 1 TO CharCount INSPECT xStr TALLYING CharCount FOR CHARACTERS BEFORE INITIAL yStr(CharPos:1) IF CharCount < EndCount MOVE CharCount TO EndCount END-IF END-PERFORM DISPLAY "Task7 First occurrence is in char position " EndCount DISPLAY "The character is " xStr(EndCount:1) STOP RUN.

20. An example showing the unpacking of comma separated records and the size validation of the unpacked fields.To test this program use the data file VarLen.dat. IDENTIFICATION DIVISION.PROGRAM-ID. UnstringFileEg.AUTHOR. Michael Coughlan.* Example showing the unpacking of comma separated records* and the size validation of the unpacked fields.* In this example we have only implemented unpacking

Page 58: cobol

* an InsertSupplier record.ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL. SELECT VarLengthRecFile ASSIGN TO "VarLen.DAT"

ORGANIZATION IS LINE SEQUENTIAL.DATA DIVISION.FILE SECTION.FD VarLengthRecFile.01 VarLenRec. 88 EndOfFile VALUE HIGH-VALUES. 02 TypeCode PIC XX. 88 DeleteSupplier VALUE "1,". 88 DeleteVideo VALUE "2,". 88 InsertVideo VALUE "3,". 88 InsertSupplier VALUE "4,". 88 ValidTypeCode VALUE "1,", "2,", "3,","4,". 02 RemainingRec PIC X(78).

WORKING-STORAGE SECTION.01 InsertSupplierRec. 02 TransType PIC 9. 02 TransDate PIC X(8). 02 Supplier-Code PIC XX. 02 Supplier-Name PIC X(20). 02 Supplier-Address PIC X(50).* These counts allow us to detect if there are too many chars* in a particular field. For instance the date field should be* 8 characters in size.01 InsertSupplierCounts. 02 DateCount PIC 99. 88 ValidDate VALUE 8. 02 SuppCodeCount PIC 99. 88 ValidSuppCode VALUE 1 THRU 2. 02 SuppNameCount PIC 99. 88 ValidSuppName VALUE 1 THRU 20. 02 SuppAdrCount PIC 99. 88 ValidSuppAdr VALUE 1 THRU 50.01 StringEnd PIC 99.PROCEDURE DIVISION.Begin. OPEN INPUT VarLengthRecFile READ VarLengthRecFile AT END SET EndOfFile TO TRUE END-READ PERFORM UNTIL EndOfFile MOVE ZEROS TO InsertSupplierCounts* First find the actual length of the record PERFORM VARYING StringEnd FROM 78 BY -1 UNTIL RemainingRec(StringEnd:1) NOT = SPACE

Page 59: cobol

END-PERFORM IF InsertSupplier UNSTRING RemainingRec(1:StringEnd) DELIMITED BY "," INTO TransDate COUNT IN DateCount Supplier-Code COUNT IN SuppCodeCount Supplier-Name COUNT IN SuppNameCount Supplier-Address COUNT IN SuppAdrCount END-UNSTRING PERFORM CheckForErrors ELSE IF NOT ValidTypeCode DISPLAY SPACE DISPLAY "Record = " VarLenRec(1:70) DISPLAY "Type code is not valid" END-IF END-IF READ VarLengthRecFile AT END SET EndOfFile TO TRUE END-READ END-PERFORM CLOSE VarLengthRecFile STOP RUN.CheckForErrors. DISPLAY SPACE DISPLAY "Record = " VarLenRec(1:70) IF NOT ValidDate DISPLAY "Date Size Error" END-IF IF NOT ValidSuppCode DISPLAY "Supplier Code Error" END-IF IF NOT ValidSuppName DISPLAY "Supplier name Error" END-IF IF NOT ValidSuppAdr DISPLAY "Supplier address Error" END-IF.

Report Generator

21. A simplified version of RepWriteFull.cbl using only one control break.All four of these Report Writer programs use the GBsales.dat data file.

IDENTIFICATION DIVISION.PROGRAM-ID. ReportExampleA.AUTHOR. Michael Coughlan.* Very simple version - only salesperson totalsENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL. SELECT SalesFile ASSIGN TO "GBSALES.DAT" ORGANIZATION IS LINE SEQUENTIAL. SELECT PrintFile ASSIGN TO "SALESREPORTA.LPT".DATA DIVISION.FILE SECTION.FD SalesFile.01 SalesRecord. 88 EndOfFile VALUE HIGH-VALUES. 02 CityCode PIC 9.

Page 60: cobol

02 SalesPersonNum PIC 9. 02 ValueOfSale PIC 9(4)V99.FD PrintFile REPORT IS SalesReport.WORKING-STORAGE SECTION.01 NameTable. 02 TableValues. 03 FILLER PIC X(18) VALUE "Dublin Belfast ". 03 FILLER PIC X(18) VALUE "Cork Galway ". 03 FILLER PIC X(18) VALUE "Sligo Waterford". 03 FILLER PIC X(9) VALUE "Limerick". 02 FILLER REDEFINES TableValues. 03 CityName PIC X(9) OCCURS 7 TIMES.REPORT SECTION.RD SalesReport CONTROLS ARE SalesPersonNum PAGE LIMIT IS 66 HEADING 1 FIRST DETAIL 6 LAST DETAIL 42 FOOTING 52.

01 TYPE IS PAGE HEADING. 02 LINE 1. 03 COLUMN 12 PIC X(32) VALUE "An example COBOL Report Program". 02 LINE 2. 03 COLUMN 6 PIC X(17) VALUE "Bible Salesperson". 03 COLUMN 23 PIC X(26) VALUE " - Sales and Salary Report". 02 LINE 4. 03 COLUMN 2 PIC X(4) VALUE "City". 03 COLUMN 12 PIC X(11) VALUE "Salesperson". 03 COLUMN 28 PIC X(4) VALUE "Sale". 02 LINE 5. 03 COLUMN 2 PIC X(4) VALUE "Name". 03 COLUMN 13 PIC X(6) VALUE "Number". 03 COLUMN 28 PIC X(5) VALUE "Value".01 DetailLine TYPE IS DETAIL. 02 LINE IS PLUS 1. 03 COLUMN 1 PIC X(9) SOURCE CityName(CityCode). 03 COLUMN 15 PIC 9 SOURCE SalesPersonNum. 03 COLUMN 25 PIC $$,$$$.99 SOURCE ValueOfSale.01 SalesPersonGrp TYPE IS CONTROL FOOTING SalesPersonNum NEXT GROUP PLUS 2. 02 LINE IS PLUS 1. 03 COLUMN 15 PIC X(21) VALUE "Sales for salesperson".

Page 61: cobol

03 COLUMN 37 PIC 9 SOURCE SalesPersonNum. 03 COLUMN 43 PIC X VALUE "=". 03 SMS COLUMN 45 PIC $$$$$,$$$.99 SUM ValueOfSale.01 TYPE IS PAGE FOOTING. 02 LINE IS 53. 03 COLUMN 1 PIC X(29) VALUE "Programmer - Michael Coughlan". 03 COLUMN 45 PIC X(6) VALUE "Page :". 03 COLUMN 52 PIC Z9 SOURCE PAGE-COUNTER.PROCEDURE DIVISION.Begin. OPEN INPUT SalesFile. OPEN OUTPUT PrintFile. READ SalesFile AT END SET EndOfFile TO TRUE END-READ. INITIATE SalesReport. PERFORM PrintSalaryReport UNTIL EndOfFile. TERMINATE SalesReport. CLOSE SalesFile, PrintFile. STOP RUN.PrintSalaryReport. GENERATE DetailLine. READ SalesFile AT END SET EndOfFile TO TRUE END-READ.

22. This program counts the number of students born in each month and displays the result.The program uses a pre-filled table of month names.This program is the solution to one of the programming exercises.Read the program specification first.

IDENTIFICATION DIVISION.PROGRAM-ID. MonthTable.AUTHOR. Michael Coughlan.* This program counts the number of students born in each month and * displays the result.ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL. SELECT StudentFile ASSIGN TO "STUDENTS.DAT"

ORGANIZATION IS LINE SEQUENTIAL.DATA DIVISION.FILE SECTION.FD StudentFile.01 StudentDetails. 88 EndOfStudentFile VALUE HIGH-VALUES. 02 StudentId PIC 9(7). 02 StudentName. 03 Surname PIC X(8). 03 Initials PIC XX.

Page 62: cobol

02 DateOfBirth. 03 YOBirth PIC 9(4). 03 MOBirth PIC 9(2). 03 DOBirth PIC 9(2). 02 CourseCode PIC X(4). 02 Gender PIC X.WORKING-STORAGE SECTION.01 MonthTable. 02 TableValues. 03 FILLER PIC X(18) VALUE "January February". 03 FILLER PIC X(18) VALUE "March April". 03 FILLER PIC X(18) VALUE "May June". 03 FILLER PIC X(18) VALUE "July August". 03 FILLER PIC X(18) VALUE "SeptemberOctober". 03 FILLER PIC X(18) VALUE "November December". 02 FILLERh REDEFINES TableValues. 03 Month OCCURS 12 TIMES PIC X(9).01 MonthCount OCCURS 12 TIMES PIC 999 VALUE ZEROS.01 MonthIdx PIC 999.01 HeadingLine PIC X(19) VALUE " Month StudCount".01 DisplayLine. 02 PrnMonth PIC X(9). 02 FILLER PIC X(4) VALUE SPACES. 02 PrnStudentCount PIC ZZ9. PROCEDURE DIVISION.Begin. OPEN INPUT StudentFile READ StudentFile AT END SET EndOfStudentFile TO TRUE END-READ PERFORM UNTIL EndOfStudentFile ADD 1 TO MonthCount(MOBirth) READ StudentFile AT END SET EndOfStudentFile TO TRUE END-READ END-PERFORM DISPLAY HeadingLine PERFORM VARYING MonthIdx FROM 1 BY 1 UNTIL MonthIdx > 12 MOVE Month(MonthIdx) TO PrnMonth MOVE MonthCount(MonthIdx) TO PrnStudentCount DISPLAY DisplayLine END-PERFORM. CLOSE StudentFile STOP RUN.

Program Specification.

A program is required which will process the Students File (Students.Dat) and will count the number students born on each month of the year and will display the results to January to December order.

Page 63: cobol

 Download Students.Dat and save it to the WorkArea directory on the drive D:   Student File Description

The Students File is a sequential file held in ascending StudentId order. Each record of the students file contains the following items;

Field Type Length Value

Student Id 9 7 0-9999999

Student Name Group

Surname X 8 -

Initials X 2 -

DateOfBirth Group

Year 9 4 0000-9999

Month 9 2 01-12

Day 9 2 01-31

Course Code X 4 -

Gender X 1 M/F

  Example Run  Month    StudCount January        2 February       2 March          3 April          4 May            1 June           0 July           2 August         1 September      4 October        5 November       3 December       5

Use Edited picture clauses and the zero suppression symbol to produce the output as shown.

  Suggested Approaches.

The main problem that we face here is that the results must be displayed in MonthName order but the file is held in StudentId order.

A tables based solution is a good idea here.  We can use the month number as a direct index into the month table.   Sample Solution

When you have written your program and have compiled it and have it working correctly you may wish to compare it with this sample solution.

SCREEN SECTION

Page 64: cobol

Program 1.

ID DIVISION.PROGRAM-ID. SCREEN1.AUTHOR. CHANJIN CHUNG.DATA DIVISION.WORKING-STORAGE SECTION.01 CYYDDD. 03 CYY PIC 99. 03 CDDD PIC 999.01 BYYDDD. 03 BYY PIC 99. 03 BDDD PIC 999.01 DAYSLIVED PIC 9(5).001400 01 FLAG PIC X VALUE 'C'.001500 SCREEN SECTION.001600 01 FORM-SCREEN BACKGROUND IS BLUE FOREGROUND IS WHITE.001700 05 BLANK SCREEN.001800 05 'TODAY IS ' LINE 7 COLUMN 2 HIGHLIGHT.001900 05 LINE 7 COLUMN 11 PIC 99999 FROM CYYDDD HIGHLIGHT.002000 05 'ENTER YOUR DOB IN YYDDD FORMAT: ' LINE 9 COLUMN 2.002100 01 INPUT-SCREEN.002200 05 LINE 9 COLUMN 34 PIC 99999 TO BYYDDD AUTO.002300 01 OUTPUT-SCREEN.002400 05 'YOU HAVE LIVED' LINE 11 COLUMN 2.002500 05 LINE 11 COLUMN 17 PIC ZZ,ZZZ FROM DAYSLIVED HIGHLIGHT.002600 05 'DAYS.' LINE 11 COLUMN 24.002700 01 END-SCREEN.002800 05 LINE 24 COLUMN 2 VALUE002900 'PRESS <Enter> TO CONTINUE OR "Q" TO END'.003000003100 PROCEDURE DIVISION.003200 MAIN-PARA.003300 PERFORM UNTIL FLAG = 'Q' OR 'q'003400 ACCEPT CYYDDD FROM DAY003500 DISPLAY FORM-SCREEN003600 ACCEPT INPUT-SCREEN003700 COMPUTE DAYSLIVED = (CYY - BYY) * 365 + CDDD - BDDD003800 DISPLAY OUTPUT-SCREEN003900 DISPLAY END-SCREEN004000 ACCEPT FLAG LINE 24 COLUMN 47 PROMPT ' ' REVERSED004100 END-PERFORM.004200 STOP RUN.Program 2.

ID DIVISION.000200 PROGRAM-ID. PRICE.000300*==============================================================000400* Demonstrates use of SCREEN SECTION adapting CALC3 to this000500* technique. Adapted to RM/COBOL-85 Version 5.24. Uses000600* modular, structured logic and functionality can readily

Page 65: cobol

000700* be expanded.000800*==============================================================000900001000 DATA DIVISION.001100 WORKING-STORAGE SECTION.001200 01 WS-QUANTITY PIC 9(5).001300 01 WS-PRICE PIC S99V99.001400 01 WS-TOTAL PIC S9(7)V99.001500 01 WS-TAX-AMOUNT PIC S9(7)V99.001600 01 WS-GRAND-TOTAL PIC S9(8)V99.001700 01 WS-RESPONSE PIC X VALUE 'C'.001800*001900 SCREEN SECTION.002000*--------------------------------------------------------------002100 01 CALC5-LABEL-SCREEN BACKGROUND IS BLUE002200 FOREGROUND IS WHITE.002300 05 BLANK SCREEN.002400 05 'Quantity Price Total'002500 LINE 5 COLUMN 20 HIGHLIGHT.002600002700 05 '6% Tax'002800 LINE 10 COLUMN 35 HIGHLIGHT.002900003000 05 '============='003100 LINE 12 COLUMN 43 HIGHLIGHT.003200003300 05 'Grand Total'003400 LINE 14 COLUMN 30 HIGHLIGHT.003500*--------------------------------------------------------------003600 01 CALC5-CLEAR-OFF-SCREEN.003700 05 LINE 7 COLUMN 21 VALUE ' ' REVERSED.003800 05 LINE 7 COLUMN 33 VALUE ' ' REVERSED.003900 05 LINE 7 COLUMN 43 VALUE ' ' REVERSED.004000 05 LINE 10 COLUMN 43 VALUE ' ' REVERSED.004100 05 LINE 14 COLUMN 43 VALUE ' ' REVERSED.004200 05 LINE 24 COLUMN 1 VALUE004300 'Enter data and press <Tab> or <Enter>' BLANK LINE.004400*--------------------------------------------------------------004500 01 CALC5-INPUT-SCREEN.004600004700 05 LINE 7 COLUMN 21 PIC ZZ,ZZ9 TO WS-QUANTITY004800 REVERSED NO HIGHLIGHT REQUIRED AUTO.004900005000 05 LINE 7 COLUMN 33 PIC Z9.99- TO WS-PRICE005100 REVERSED NO HIGHLIGHT REQUIRED.005200*--------------------------------------------------------------005300 01 CALC5-OUTPUT-SCREEN.005400005500 05 LINE 7 COLUMN 21 PIC ZZ,ZZ9 FROM WS-QUANTITY005600 REVERSED.

Page 66: cobol

005700005800 05 LINE 7 COLUMN 33 PIC ZZ.99- FROM WS-PRICE005900 REVERSED.006000006100 05 LINE 7 COLUMN 43 PIC ZZ,ZZZ,ZZ9.99- FROM WS-TOTAL006200 REVERSED.006300006400 05 LINE 10 COLUMN 43 PIC ZZ,ZZZ,ZZ9.99- FROM WS-TAX-AMOUNT006500 REVERSED.006600006700 05 LINE 14 COLUMN 43 PIC ZZ,ZZZ,ZZ9.99-006800 FROM WS-GRAND-TOTAL REVERSED.006900007000 05 LINE 24 COLUMN 1 VALUE007100 'Press <Enter> to continue or "Q" to end' BLANK LINE.007200*--------------------------------------------------------------007300 01 CALC5-ENDING-SCREEN BACKGROUND IS BLACK007400 FOREGROUND IS BLUE.007500 05 BLANK SCREEN.007600 05 LINE 7 COLUMN 10007700 VALUE '********************************'.007800 05 LINE 8 COLUMN 10007900 VALUE '* *'.008000 05 LINE 9 COLUMN 10008100 VALUE '* *'.008200 05 LINE 10 COLUMN 10008300 VALUE '* *'.008400 05 LINE 11 COLUMN 10008500 VALUE '********************************'.008600*==============================================================008700*008800 PROCEDURE DIVISION.008900 0000-MAINLINE.009000 PERFORM 1000-BOJ.009100 PERFORM 2000-PROCESS009200 UNTIL WS-RESPONSE = 'Q' OR 'q'.009300 PERFORM 3000-EOJ.009400 STOP RUN.009500009600*==============================================================009700009800 1000-BOJ.009900*---------------------------------------------010000* Clear screen and display labels highlighted010100*---------------------------------------------010200 DISPLAY CALC5-LABEL-SCREEN.010300010400*==============================================================010500010600 2000-PROCESS.

Page 67: cobol

010700*------------------------------------------------------010800* Blank out the data fields from any prior transaction010900*------------------------------------------------------011000 DISPLAY CALC5-CLEAR-OFF-SCREEN.011100011200*---------------------------------------------------011300* Accept the data, do computations, present results011400*---------------------------------------------------011500 ACCEPT CALC5-INPUT-SCREEN.011600 COMPUTE WS-TOTAL = WS-QUANTITY * WS-PRICE.011700 COMPUTE WS-TAX-AMOUNT = WS-TOTAL * .06.011800 COMPUTE WS-GRAND-TOTAL = WS-TOTAL + WS-TAX-AMOUNT.011900 DISPLAY CALC5-OUTPUT-SCREEN.012000012100*---------------------------------------012200* Ask if user wants to continue or quit012300*---------------------------------------012400 ACCEPT WS-RESPONSE012500 LINE 24 COLUMN 60012600 PROMPT '_' REVERSED NO BEEP LOW.012700012800*==============================================================012900013000 3000-EOJ.013100*-------------------------------------------------013200* Clear the screen, display sign-off message, and013300* leave the system set to normal screen colors013400*-------------------------------------------------013500 DISPLAY CALC5-ENDING-SCREEN.013600 DISPLAY 'CALC5 ENDED AS REQUESTED'013700 LINE 9 COLUMN 14013800 BLINK013900 CONTROL "FCOLOR=RED".014000 DISPLAY ' '014100 LINE 1 COLUMN 1014200 CONTROL "FCOLOR=WHITE".