Sunday, 25 March 2012


TUESDAY, APRIL 5, 2011

COBOL/400 Tutorial : Basics of COBOL/400

Agenda:

History of COBOL
Overview of COBOL
Coding Rules in COBOL
Program Structure
Divisions in COBOL
Data Names and Identifiers
Figurative Constants
File Handling
Calling A Program
Subfiles
Array Handling
Sorting and Merging
Debugging a Program
Miscellaneous
Interview questions and Some Tips & Tricks


History of COBOL

COmmon Business Oriented Language (COBOL) developed by committee COnference onDAta SYstem Languages (CODASYL) in 1959.
In 1968American National Standards (ANS) version of COBOL was developed and approved.
In 1974, 2nd version was developed to make language more efficient and standardized.
In 1985, 3rd version was developed and it is now most widely used.
COBOL/400 is just combination of COBOL 85 and some enhancement related toAS/400.

.IBM COBOL/400 = ANS COBOL 1985 + Enhancements
.COBOL
.High-Level Language
.English-like Language
.Easy to use/understand the code
.Designed for developing Business Applications

Overview of COBOL
.Disadvantages
.Not designed to handle 
scientific applications
.Advantages
.Simple
.Portable
.Maintainable
.COBOL
.Programs are hierarchical in structure
.Each element of the hierarchy consists of one or more subordinate 
elements 
.The hierarchy consists of 
.Divisions
.Sections 
.Paragraphs
.Sentences 
.Statements 

Structure of COBOL 
.COBOL
.DIVISION
.A division is a block of code, usually containing one or more sections 


.SECTION
.A section is a block of code usually containing one or more paragraphs 


.PARAGRAPH
.A paragraph is a block of code made up of one or more sentences 


.SENTENCE
.A sentence consists of one or more statements


.STATEMENT 
.A statement consists of a COBOL verb and an operand or operands 

Structure of COBOL
.CodingRules
.Each COBOL instruction coded on single line of 80 characters
.Columns 1-6 for Sequence number
.Column 7 for continuation, comment, starting new page
.Columns 8-72 for COBOL program statements
.Columns 73-80 for Comment Area (optional and rarely used 
today)


Column 7

.* (asterisk) designates entire line as comment
./ (slash) forces page break when printing source listing
.-(dash) to indicate continuation of nonnumeric literal


Structure of COBOL 
.MARGINRULES
.Columns 8-72 divided into two areas
.Area A -columns 8 -11
.Area B -columns 12 -72


.Division, Section and Paragraph-names must begin in Area A
.First letter of name must begin in column 8 or 9 or 10 or 11
.Entry may extend into Area B

.All statements, clauses, and sentences begin anywhere in Area 
B (column 12, 13, 14, etc.)
.Select entries in ENVIRONMENT DIVISION
.Data description entries in DATA DIVISION
.All PROCEDURE DIVISION instructions

Structure of COBOL
Divisions

.COBOLhasfourdivisions
.IDENTIFICATION DIVISION
.ENVIRONMENT DIVISION
.DATA DIVISION
.PROCEDURE DIVISION


.The sequence in which they are specified is fixed, and must 
follow the order 




DIVISONS 
.Providesidentifyinginformationaboutprogram
.MustbethefirstdivisionineveryCOBOLsourceprogram
.MustbeginwiththewordsIDENTIFICATIONDIVISIONfollowedbyaseparatorperiod
.DividedintoParagraphs
.PROGRAM-ID
.AUTHOR
.INSTALLATION
.DATE-WRITTEN
.DATE-COMPILED
.SECURITY


IDENTIFICATION DIVISION
TheIDENTIFICATIONDIVISIONhasthefollowingstructure:

IDENTIFICATION DIVISION.

PROGRAM-ID.<Name Of Program>.

AUTHOR.<Programmer Name>.

INSTALLATION.<Name of the company or location>.

DATE-WRITTEN.<Date of Written>.

DATE-COMPILED.<Date of Compilation>.

SECURITY.<Level of confidentiality>.


.PROGRAM-IDisrequiredandmustbethefirstparagraphintheIdentificationDivision.
.OtherParagraphsareoptional.


IDENTIFICATION DIVISION 
.EnvironmentDivisionhas2sections
.CONFIGURATIONSECTION
.INPUT-OUTPUTSECTION


ENVIRONMENT DIVISION
.CONFIGURATIONSECTION

.Describestheenvironmentinwhichtheprogramwillrun
.SpecifiesthecharacterforCurrencySign
.SpecifiestheDatanameforLocalDataArea
.ThissectionisOptional

ENVIRONMENT DIVISION 
.CONFIGURATIONSECTIONThe CONFIGURATION SECTION has the following structure:
ENVIRONMENT DIVISION.
CONFIGURATION SECTION. 
SOURCE-COMPUTER. IBM-AS400.
OBJECT-COMPUTER. IBM-AS400.
SPECIAL-NAMES. C01 IS TOP-OF-PAGELOCAL-DATA IS LOCAL-DATA-AREACURRENCY-SIGNIS “Y".


ENVIRONMENT DIVISION
PICTURE clause, Must be a one-character, nonnumeric literal.
Must NOT be any of the following:
.Digits zero (0) through nine (9)
.Uppercase alphabetic characters A B C D P R S V X Z
.Lowercase alphabetic characters a through z
.The space
.Special characters * + -/ , . ; ( ) = ".
.A figurative constant.


When the CURRENCY 
SIGN clause is omitted, 
only the dollar sign ($) 
may be used as the 
PICTURE symbol for the 
currency sign 
.INPUT-OUTPUTSECTION
.Defineseachfile
.AssignsthefiletoInput/Outputdevices
.Contains2paragraphs
.FILE-CONTROLparagraph
.I-O-CONTROLparagraphRequired in the program if file is used

ENVIRONMENT DIVISION
.INPUT-OUTPUTSECTION
.FILE-CONTROLParagraph

.DefineseachfileintheCOBOLprogramwithanexternalmedium
.Specifiesfileorganization,accessmodeandotherinformation

COBOLallowsforfourdistinctkindsoffileinputandoutput:

.Sequential
.Indexed
.Relative
.Transaction


ENVIRONMENT DIVISION 
.INPUT-OUTPUTSECTION
.FILE-CONTROLParagraph

FORMAT:

INPUT-OUTPUTSECTION.

FILE-CONTROL.

SELECT<File-name>

ASSIGNTO <Device Name>-<Actual File Name>-<Attribute>

ORGANIZATIONIS <File Organization Type>

ACCESS MODEIS <Access Mode>

RECORD KEYIS EXTERNALLY-DESCRIBED-KEY / <Data-Name-1>

RELATIVE KEYIS <Data-Name-2>

FILE STATUSIS <Data-Name-3>.


ENVIRONMENT DIVISION 
.INPUT-OUTPUTSECTION
.FILE-CONTROLParagraph
.SELECTClause

SELECT<File-name>

.Selectsafile
File-Name:

.Afile-namemustconformtotherulesforaCOBOLuser-definedname
.Mustcontainatleastonealphabeticcharacter
.Mustbeuniquewithinthisprogram

ENVIRONMENT DIVISION

.INPUT-OUTPUTSECTION
.FILE-CONTROLParagraph
.ASSIGNClause


ASSIGNTO<DeviceName>-<ActualFileName>-<Attribute>

.Associatesafilewithanexternalmedium
.Ithas3Parts:
.DeviceName
.Thispartspecifiesthetypeofdevicethatthefilewilluse

ENVIRONMENT DIVISIONDevice Name:
DATABASE -for database fileWORKSTATION –for display filePRINTER –for printer fileFORMATFILE –for external printer file (RLU)
.INPUT-OUTPUTSECTION
.FILE-CONTROLParagraph
.ASSIGNClause




ASSIGNTO<DeviceName>-<ActualFileName>-<Attribute>

.ActualFilename
.Actualexternalfilename–10-charactersMax.
.Thisexternalfilehastobecreatedbeforecompilingtheprogram


.Attribute(Optional)
.CanbeSI-indicatesthataseparateindicatorareahasbeenspecifiedintheDDSforaFORMATFILEorWORKSTATIONfile.

ENVIRONMENT DIVISION 
.INPUT-OUTPUTSECTION
.FILE-CONTROLParagraph
.ORGANIZATIONClause
.Specifiesthelogicalstructureofthefile

ORGANIZATIONIS<FileOrganizationType>

OrganizationTypes:

.SEQUENTIAL
.INDEXED
.RELATIVE
.TRANSACTION

ENVIRONMENT DIVISIONWhen the ORGANIZATION clause is omitted, ORGANIZATION SEQUENTIAL is assumed 
.INPUT-OUTPUTSECTION
.FILE-CONTROLParagraph
.ORGANIZATIONClause
.ORGANIZATIONISSEQUENTIAL

.Therecordsinthefilesisestablishedbytheorderinwhichrecordsareplacedinthefilewhenitiscreated

.ORGANIZATIONISINDEXED
.Thepositionofeachlogicalrecordinthefileisdeterminedbythekeysequenceaccesspathcreatedwiththefile

.ORGANIZATIONISRELATIVE
.Thepositionofeachrecordinthefileisdeterminedbyitsrelativerecordnumber

.ORAGANIZATIONISTRANSACTION
.SignifiesinteractionbetweenaCOBOLprogramandeitheraworkstationuser

ENVIRONMENT DIVISION 
.INPUT-OUTPUTSECTION
.FILE-CONTROLParagraph
.ACCESSMODEClause

ACCESSMODEIS<AccessMode>

.Definesthemannerinwhichtherecordsofthefilearemadeavailableforprocessing
.3typesofAccessModesareavailable
.SEQUENTIAL
.RANDOM
.DYNAMIC


ENVIRONMENT DIVISION

.INPUT-OUTPUTSECTION
.FILE-CONTROLParagraph
.ACCESSMODEClause

ACCESSMODEIS<AccessMode>

.SEQUENTIAL
.Allowsreadingandwritingrecordsofafileinaserialmanner

.RANDOM
.Allowsreadingandwritingrecordsofafilebasedonthekeyfield[s]specifiedinafile

.DYNAMIC
.Recordscanbeprocessedsequentiallyand/orrandomly
.MustbeusedforSubfileprocessing

ENVIRONMENT DIVISION 
.INPUT-OUTPUTSECTION
.FILE-CONTROLParagraph
.RECORDKEYClause
.MustbespecifiedforanIndexedfile
.Specifiesthedataitemwithintherecordthatistherecordkeyforanindexedfile.

RECORDKEYISEXTERNALLY-DESCRIBED-KEY/<Data-Name-1>

[WITHDUPLICATES]

ENVIRONMENT DIVISION 
.INPUT-OUTPUTSECTION
.FILE-CONTROLParagraph
.RECORDKEYClause
.EXTERNALLY-DESCRIBED-KEY
.COBOLReservedword
.KeysfromExternalDatabasefilewillbeused


.Data-Name-1
.RECORDKEYdataitem
.Mustbedescribedasafixedlengthalphanumericitemwithinarecorddescriptionentryassociatedwiththefile
.CanbeanumericitemwhenthefileisassignedtoaDATABASEdevicetype


.WITHDUPLICATES
.CanonlybespecifiedforfilesassignedtoDATABASE
.Allowsthefiletohavekeyswiththesamevalues.








ENVIRONMENT DIVISION 
.INPUT-OUTPUTSECTION
.FILE-CONTROLParagraph
.RELATIVEKEYClause
.identifiesadata-namethatspecifiestherelativerecordnumberforaspecificlogicalrecordwithinarelativefile






RELATIVEKEYIS<Data-Name-2>

Data-Name-2

.Mustbedefinedasanunsignedintegerdata








ENVIRONMENT DIVISION 
.INPUT-OUTPUTSECTION
.FILE-CONTROLParagraph
.Relationship Between Data Organizations and Access Modes




ENVIRONMENT DIVISION
Sequential

Random

Dynamic

Sequential

Y

N

N

Indexed

Y

Y

Y

Relative

Y

Y

Y

Transaction

Y

N

Y



Access Mode

Organization 
.INPUT-OUTPUTSECTION
.FILE-CONTROLParagraph
.FILESTATUSClause
.Monitorstheexecutionofeachinput-outputrequestforthefile






FILESTATUSIS<statuskeydataitem>

Status Key Data Item

.2-characteralphanumericitem,mustbedefinedintheDATADIVISION
.WhentheFILESTATUSclauseisspecified,thesystemmovesavalueintothestatuskeydataitemaftereachinput-outputrequest
.Success.Valuewillbe.00.








ENVIRONMENT DIVISION 
.INPUT-OUTPUTSECTION
.CodeExample[ForDatabasefile]
.FileorganizedbyKeyfields
.AccessbySequentialENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECTEMPLOYEE-FILEASSIGNTO DATABASE-EMPPFORGANIZATIONIS INDEXEDACCESS MODEIS SEQUENTIALRECORD KEYIS EXTERNALLY-DESCRIBED-KEYFILE STATUSIS WS-FILE-STATUS.






ENVIRONMENT DIVISION 
.INPUT-OUTPUTSECTION
.CodeExample[ForDisplayfile]
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECTDISPLAY-FILEASSIGNTO WORKSTATION-EMPD0ORGANIZATIONIS TRANSACTIONACCESS MODEIS DYNAMICFILE STATUSIS WS-FILE-STATUS.




ENVIRONMENT DIVISION 
.Describesallthedatainastructuredmanner
.TheDATADIVISIONhas3sections:
.FILESECTION
.DescribesallInputandOutputfile(ExternallyDescribed)usedintheprogram


.WORKING-STORAGESECTION
.AnyfieldthatisnotpartofI/Ofiles(i.e.WorkAreas)isdefinedinthissection








.LINKAGESECTION
.MustbedefinedintheCalledprogramifanyparametersthatneedtoreceivedfromCallingprogram.
.Parametersaredescribedinthissection








DATA DIVISION 
.FILESECTION
.MustcontainanFileDescription(FD)EntryandRecordDescriptionEntryforeachexternaldescribedfile




FileDescriptionEntry

FD<File-Name>
DATA DIVISION.
FILE SECTION.
FD EMPLOYEE-FILE.
.
.
FD DISPLAY-FILE

DATA DIVISION


.FILESECTION
.RecordDescriptionEntries


Level {data-name-1

FILLER} 

[REDEFINE clause] 

[BLANK-WHEN-ZERO clause] [JUSTIFIED clause]

[OCCURS clause] [PIC clause]

[SIGN clause] [SYNCH clause]

[USAGE clause] [VALUE clause] .

DATA DIVISION 
.FILESECTION
.RecordDescriptionEntry
.Definedasan01Entry
.Specifiesformatofarecord[RecordFormatName,Fields,length]






01<RecordFormat-Name>
DATA DIVISION.
FILE SECTION.
FD EMPLOYEE-FILE01 EMPLOYEE-RECORD.
05 EMPLOYEE-NUMBERPIC 9(07).
05 FIRST-NAMEPIC X(15).
05 MIDDLE-INITIALPIC X(01).
05 LAST-NAMEPIC X(15).
05 MONTHLY-SALARYPIC 9(07)V9(02).

DATA DIVISION 
.RulesforDefiningData-Name
.1to30characters
.Letters,digitsandhyphens(-)only
.Maynotbeginorendwithhyphen
.NoBlankswithinthedata-name
.Mustcontainatleastonealphabeticcharacter
.MaynotbeaCOBOLreservedwordlikeADD,MOVE,LOW-VALUES,RETURN-CODE,
DATE,LINE,etc
.ShouldbeMeaningful.
.Usesuffixesorprefixessuchas–INor–OUTwhereappropriate




Example:

.EMPLOYEE-NUMBER
.FIRST-NAME
.LAST-NAME
.INPUT-IN




DATA DIVISION 
.LevelNumbers
.Specifiesthehierarchyofdatawithinarecord
.Integersfrom01to49
.SpecialLevelNumbers
.66–ForRENAME
.77–ForIndependentdataitem,cannotbesubdivided
.88–ForConditionalName


.Level-number01and77mustbegininAreaA
.Levelnumbers02through49,66and88maybegininAreaAorAreaB
.Level-numbersmustbefollowedbyaspacefollowedbyitsassociateddata-name




DATA DIVISION 
.PICTUREClause(PIC)
.SpecifiestheTypeofData
.IndicatestheSizeoftheField




.DataTypes


Example:

01 EMPLOYEE-DETAIL.

05 EMP-IDPIC 9(06).

05 EMP-NAMEPIC X(30).

Type

PIC Clause

Description

Alphabetic

A

Contain only Letters or Blanks

Alphanumeric

X

Contain Letters, Numbers, Blanks, Special 
Characters

Numeric

9

Contain only numeric values



DATA DIVISION


.GroupItem
.DataFieldthatcanbefurthersubdivided
.HasnoPICTUREClause


.ElementaryItem
.DataFieldthatcannotbefurthersubdivided
.HasPICTUREClauseExample:
01 WS-DATE.
05 WS-DAYPIC 9(02). 
05 WS-MONTHPIC 9(02).
05 WS-YEAR.
10 CENTUARYPIC 9(02).
10 YEAR PIC 9(02).




DATA DIVISION 
.ImpliedDecimalPoint
.SymbolVisusedtodenoteanImplieddecimalpoint
.NotOccupyastorage




Example:

For Salary amount 12345.67 [ 5 Integer and 2 decimal positions]

01 EMPLOYEE-DETAIL.

05 EMP-SALARYPIC 9(05)V9(02). 

DATA DIVISION 
.SignedNumericData
.CharacterSisusedwithPICClause
.+isthecharacterusedforthepositiveoperationalsign.
.-isthecharacterusedforthenegativeoperationalsign.




Example:

05 WS-TEMPERATUREPIC S9(3).

DATA DIVISION 
.TypesofNumericData
.ZonedDecimal
.PackedDecimal
.Binary(lesswidelyused)




PackedDecimal

.Storestwonumericdigitinonebyteoffield
.Storedupto8bytes(15Digits)inlength
.RecommendedforArithmeticoperations[Processingtimecanbesaved]




ZonedDecimal

.Storesonenumericdigitinonebyteoffield
.Storedupto15bytesinlength




DATA DIVISION 
.ConvertingZonedDecimaltoPackedDecimal
.DividethenumberofdigitsintheZoneddecimalfieldby2
.Ifthereisadecimalremainderof.5,dropit
.Add1totheresult




Example

ForFivedigit

.Divide5by2;2.5isthequotient
.Dropthedecimalremainder.5androunddownto2
.Add1




Result:3bytesareneededforPackedfield

ForSixdigit

.Divide6by2;3isthequotient
.Add1




Result:4bytesareneededforPackedfield

DATA DIVISION 
.BLANKWHENZEROClause
.ANumericDataitemcontainsspaceswhenitsvalueiszero
.Notallowedon66and88levelitems




DATA DIVISION 
.JUSTIFIEDClause
.Overrides standard positioning rules for a receiving item of the alphabetic or alphanumeric
categories
.Cannot be specified for numeric{ JUSTIFIEDRIGHTJUST} 




b.Space

Alignment

Sending Field value

Receiving Field value

(5-char)

Standard

THE

THEbb

JUSTIFIED RIGHT

THE

bbTHE

Standard

TOObBIG

TOObB

JUSTIFIED RIGHT

TOObBIG

ObBIG



DATA DIVISION


.OCCURSClause
.UsedfordefiningTables/Arrays
.Specifiesthatthenameditemistoberepeatedasmanytimesasstated
.Thenumberofoccurrencesofanitemcanbeuptoamaximumof3,000,000
.Cannotbeusedinadatadescriptionentrywhoselevel-numberis01,66,77,or88.




For example:

01 TABLE-ONE.

05 ELEMENT-ONE OCCURS3 TIMES.

10 ELEMENT-A PIC X(4).

10 ELEMENT-B PIC 9(4).

DATA DIVISION 
.REDEFINEClause
.Allows you to use different data description entries to describe the same computer storage 
area




Level-Number<Data-Name-1>REDEFINESData-Name-2

.Data-Name-1.redefiningitem
.Data-Name-2.redefineditem
.Level-numbersofdata-name-1anddata-name-2mustbeidentical
.Mustnotbelevel66orlevel88




05 WS-AMOUNTPIC 9(7).
05 WS-AMOUNT-NEW REDEFINES 
WS-AMOUNTPIC 9(5)V99.
For example:
05 A PIC X(6).
05 B REDEFINES A.
10 B-1 PIC X(2).
10 B-2 PIC 9(4).
DATA DIVISION 
.RENAMEClause
.Groupingsofelementarydataitems
.Mustbespecifiedin66level
.Alevel-66entrycannotrenamealevel-01,level-77,level-88oranotherlevel-66entry




66data-name-1RENAMESdata-name-2

[THRU data-name-3]
For example:
01 WS-DATE.
05 YEARPIC 9(2).
05 MONTHPIC 9(2).
05 DAYPIC 9(2).
66 NEW-DATE RENAMESYEAR THRUDAY.

DATA DIVISION 
.USAGEClause
.Specifiestheformatinwhichdataisrepresentedinstorage
.TheUSAGEclausecanbespecifiedforadatadescriptionentrywithalevel-numberotherthan66or88
.Ifitisspecifiedatthegrouplevel,itappliestoeachelementaryiteminthegroup




USAGEIS {BINARYCOMP COMPUTATIONAL 
COMP-3 COMPUTATIONAL-3 
COMP-4 COMPUTATIONAL-4 
DISPLAYINDEXPACKED-DECIMALPOINTER }
DATA DIVISION 
.USAGEClause
.COMP:BinaryForm
.COMP-3:PackedForm
.COMP-4:EquivalenttoBinary




DATA DIVISION 
.DefiningPackedDecimalField


01WORK-AREA.

05WS-AMOUNTPIC9(7)COMP-3.

OR

05WS-AMOUNTPIC9(7)PACKED-DECIMAL.

DATA DIVISION 
.VALUEClause
.Specifiestheinitialcontentsofadataitem
.CancontainLiteralorFigurativeConstant




Valid

01WORK-AREA.

05END-OF-FILEPICX(1)VALUE“N”.

05WS-MONTHPICX(3)VALUE“JAN”.

05WS-CONSTANTPIC9(4)VALUE1234.

05WS-SIGNED-VALUEPICS9(5)VALUE-56789.

05WS-NAMEPICX(10)VALUESPACES.

05WS-AMOUNTPIC9(5)V99VALUEZEROS.

Invalid

05 WS-CHARACTERPIC X(10)VALUE ZEROS.

05 WS-NUMERICPIC 9(5)VALUE SPACES.

DATA DIVISION 
.VariableandConstantData
.Bydefiningfiles,records,andfieldsandassigningcorrespondinguser-defineddata-namesintheDATADIVISION,dataisreservedforstorage
.TheareadescribedbytheFileDescriptionentriesissaidtocontainvariabledata
.Aconstantorliteralisaformofdatarequiredforprocessingthatisnotdependentontheinputtothesystem
.Numericliteral
.Nonnumericliteral
.Figurativeconstant






DATA DIVISION 
.TypesofConstants
.Numericliteral
.AnumericliteralisaconstantthatcanbeusedinMOVEstatementsandarithmeticoperations




FORMINGNUMERICLITERALSRULES

.1to18digits
.A+or-signmaybeused,butitmustappeartotheleftofthenumber
.Adecimalpointispermittedwithintheliteral.Itmaynotbetherightmostcharacteroftheliteral.






Valid Numeric Literals+15.8.05-387.5842-97Invalid Numeric Literals1,00015.
$100.0017.45-
DATA DIVISION 
.TypesofConstants
.Non-numericliteral
.AnonnumericoralphanumericliteralisaconstantthatisusedinthePROCEDUREDIVISIONforalloperationsexceptarithmetic




FORMINGNON-NUMERICLITERALSRULES

.1to160characters(includingspaces)
.Theliteralmustbeenclosedinquotationmarks(“)orapostrophes(„)
.Anycharactersmaybeusedexceptthequotationmarksandapostrophes






Valid Non-numeric Literals“CODE”
„INPUT.
“ABC 123”
„$100.00.
“1,000.
DATA DIVISION 
.TypesofConstants
.Non-numericliteral




UsingtheApostropheinCOBOL/400

.Bydefault,theCOBOL/400compilerexpectsdoublequotationmarks(“)
.WhenApostrophe(„)isused,severitylevel10errorMESSAGE(LBL0014)willbegenerated
.Toeliminatethiserror,thefollowingstatementshouldbeusedastheFirststatementintheprogram.






PROCESSAPOST.

Example:

PROCESSAPOST.

IDENTIFICATIONDIVISION.

PROCESS APOST.
Tells the compiler that the Apostrophe is being 
used instead of double quotationDATA DIVISION 
.TypesofConstants
.FigurativeConstant
.AFigurativeconstantisaCOBOLreservedwordsuchasSPACE(orSPACES)orZERO(orZEROSorZEROES)
.ZEROS
.Meaningall0.s.
.ReceivingfieldmayhavePICof9.soraPICofX.s






.SPACES
.Meaningallblanksorspaces
.ReceivingfieldmustbePICofA.soraPICofX.s






DATA DIVISION 
.PROCEDUREDIVISION
.ContainsParagraphs,SentencesandStatements
.Readdata,processthedataandproduceoutput




PROCEDUREDIVISION.

Paragraph

.EachParagraphisanindependentmoduleorroutine
.Includesseriesofinstructionstoperformaspecificsetofoperations
.ParagraphnamemustbecodedinAreaA
.MustbeuniqueinaCOBOLprogram
.ThelengthofParagraphnamemustbe30charactersMax.
.Endswithaperiod




PROCEDURE DIVISION 
.Sentence


.EachParagraphconsistsofSentences.
.Sentenceiscodedononeormorelinesandconsistsofstatementorgroupofstatements
.Endswithaperiod
.MustbecodedinAreaB




Statement

.StatementbeginswithaverbsuchasREAD,MOVE,WRITE,etc
.ConditionsuchasIFA=B
.MustbecodedinAreaB




PROCEDURE DIVISION 
.GuidelinefordefiningParagraph


PROCEDUREDIVISION.

0000-MAIN-LINE.

PERFORM0100-INITIALIZE.

PERFORM1000-PROCESS.

PERFORM2000-CLOSE.

0000-MAIN-LINE-EXIT.

STOPRUN.

PROCEDURE DIVISION 
PROCEDURE DIVISION
.Statements
.OPENStatement
.Makesfilesavailableforprocessing
.IdentifieswhichfileswillbeInputandwhichwillbeoutput
.FilecanbeopenedasINPUT,OUTPUT,I-OorEXTENDmodes




OPENINPUT file-name-1OUTPUT file-name-2.
.File-names used must appear in SELECT statement
.File must be OPEN before reading from or writing to it



PROCEDURE DIVISION
.Statements
.READStatement
.AREADstatementtransmitsdatafromtheinputdevice,assignedintheENVIRONMENTDIVISION,totheinputstoragearea,definedintheFILESECTIONoftheDATADIVISION.




READ file-name-1AT END statement-1 . . .
[NOT AT END statement-2 . . .]
[END-READ]
.AT ENDclause –End-of-file has been reached
.NOT AT END–End-of-file has NOT been reached



PROCEDURE DIVISION
.Statements
.READStatement


Thefile-namespecifiedintheREADstatementappearsinthreepreviousplacesintheprogram:

.TheSELECTstatement,indicatingthefile-nameandthedeviceorimplementor-nameassignedtothefile.Ifafileisstoredonadisk,forexample,aREADoperationtransmitsdatafromthedisktotheinputarea
.TheFDentry,describingthefileanditsformat
.TheOPENstatement,accessingthefileandactivatingthedevice



PROCEDURE DIVISION
.Statements
.READStatement


Example

READ EMPLOYEE-FILE

AT END

MOVE “Y” TO END-OF-FILE

NOT AT END

PERFORM 1200-UPDATE-ROUTINE

END-READ.


PROCEDURE DIVISION
.Statements
.WRITEStatement
.TheWRITEinstructiontakesdataintheoutputareadefinedintheDATADIVISIONandtransmitsittothedevicespecifiedintheENVIRONMENTDIVISION




AsimpleWRITEstatementhasthefollowingformat:

WRITErecord-name-1

Example:

WRITEOUTPUT-RECORD.

.FilemustbeopeninOUTPUT,I-OorEXTENDmode



PROCEDURE DIVISION
.Statements
.REWRITEStatement
.Replaces/Updatesanexistingrecordinafile




AsimpleREWRITEstatementhasthefollowingformat:

REWRITErecord-name-1

Example:

REWRITEOUTPUT-RECORD.

.FilemustbeopeninI-Omode
.ReplacesarecordretrievedbyaREADstatement



PROCEDURE DIVISION
.Statements
.DELETEStatement
.Removesarecordinafile




AsimpleDELETEstatementhasthefollowingformat:

DELETEfile-name

Example:

DELETEEMPLOYEE-FILE.

.FilemustbeopeninI-Omode
.RemovesarecordretrievedbyaREADstatement


DELETE is NOT possible for a file having Sequential Organization and Sequential Access Mode 
PROCEDURE DIVISION
.Statements
.PERFORMStatements
.Transferscontrolexplicitlytooneormoreproceduresandimplicitlyreturnscontroltothenextexecutablestatementafterexecutionofthespecifedprocedure[s]orimperativestatementsiscompleted




ThePERFORMstatementcanbe:

.Anout-of-linePERFORMstatement
.Procedure-name-1isspecified.


.Anin-linePERFORMstatement
.Procedure-name-1isomitted
.MustbedelimitedbytheEND-PERFORMphrase






PERFORM 
Statement(s)
END-PERFORM. 
PROCEDURE DIVISION
.Statements
.PERFORMStatements


ThePERFORMstatementhasfourformats:

.BasicPERFORM
.TIMESphrasePERFORM
.UNTILphrasePERFORM
.VARYINGphrasePERFORM.





PROCEDURE DIVISION
.Statements
.BasicPERFORM
.BasicPERFORMstatementarerunonceandcontrolthenpassestothenextexecutablestatementfollowingthePERFORMstatement




PERFORMParagraph-name-1

Toexecuteagroupofparagraphs

PERFORMParagraph-name-1THROUGHParagrapgh-name-2

THRU

The PERFORM executes all statements beginning at Paragraph-name-1 

until the end of paragraph-name-2 is reached.

If you specify procedure-name-1, you must not specify imperative-statementand the END-PERFORM phrase. 
If you omit procedure-name-1, you must specify imperative-statementand the END-PERFORM phrase. 
Imperative-statementrepresents the statements to be executed for an in-line PERFORM statement. 
PROCEDURE DIVISION
.Statements
.PERFORM…TIMES
.The procedure(s) referred to in the TIMES phrase PERFORM statement are executed the
number of times specified by the value in identifier-1




PERFORMParagraph-name-1Identifier-1TIMES

Example

1000-PROCESS.

PERFORM1400-WRITE-ROUTINE5TIMES


PROCEDURE DIVISION
.Statements
.PERFORM…UNTIL
.Theprocedure(s)referredtoareperformeduntiltheconditionspecifiedbytheUNTILphraseistrue




PERFORMParagraph-name-1

UNTILcondition-1

Example

0000-MAIN.

PERFORM1000-PROCESS

UNTILEND-OF-FILE=“Y”.

.

.

0000-MAIN-EXIT.

STOPRUN.


PROCEDURE DIVISION
.Statements
.PERFORM…VARYING
.TheVARYINGphraseincreasesordecreasesthevalueofoneormoreidentifiersorindex-
names,accordingtocertainrules.




PERFORMParagraph-name-1

VARYINGIdentifier-1FROMIdentifier-2BYIdentifier-3

UNTILcondition-1

Example

1200-LOOP-RTN.

PERFORM1210-ADD-RTN

VARYINGINTEGER1FROM1BY2

UNTILINTEGER1>1001..

1210-ADD-RTN.

ADDINTEGER1TOWS-COUNTER.


PROCEDURE DIVISION
.Statements
.GOTOStatement
.Permanentlytransferscontroltoanotherparagraph




GOTOparagraph-name-1

Example

1000-PROCESS.

.

.

IFEND-OF-FILE=“Y”

GOTO2000-CLOSE-RTN

END-IF.


PROCEDURE DIVISION
.Statements
.EXITStatement
.providesacommonendpointforaaGOTOstatementorseriesofparagraphsinwhichaPERFORM…THRUhasbeenused




1000-PROCESS.
READ EMPLOYEE-FILEAT END 
MOVE “Y” TO END-OF-FILEEND-READ.
IF END-OF-FILE = “Y”
GO TO 1000-PROCESS-EXIT 
END-IF.
PERFORM 1200-VALIDATION-RTNPERFORM 1300-DATA-MAPPING-RTNPERFORM 1400-WRITE-RTN.
1000-PROCESS-EXIT.
EXIT.
ExamplePROCEDURE DIVISION.
0000-MAINLINE.
PERFORM 0100-INITIALIZE-RTN.
PERFORM 1000-PROCESS THRU1000-PROCESS-EXITUNTIL END-OF-FILE = “Y”.
PERFORM 2000-CLOSE-RTN.
0000-MAINLINE-EXIT.
STOP RUN. 
PROCEDURE DIVISION
.Statements
.CLOSEStatement
.Closeallfilesopened
.Releasesfilesanddeactivatesdevices
.Indicatesfilesnolongerneededforprocessing




CLOSEfile-name-1.

Example

2000-CLOSE.

CLOSEEMPLOYEE-FILE.

For closing multiple files using one CLOSE statement.

CLOSEEMPLOYEE-FILE

PAYROLL-FILE

DISPLAY-FILE.


PROCEDURE DIVISION
.Statements
.STOPRUNStatement
.Tellsthecomputertoterminatetheprogram
.AllprogramsshouldincludeaSTOPRUNstatementtoendtherun
.Usuallythelastinstructioninthemainmodule




Example

0000-MAIN-EXIT.

STOPRUN.

When a STOP RUN Statement is executed, it will close any files that are still opened. 
PROCEDURE DIVISION
.Statements
.EXITPROGRAMStatement
.Specifiestheendofacalledprogramandreturnscontroltothecallingprogram




Example

0000-MAIN-EXIT.

EXITPROGRAM.


PROCEDURE DIVISION
.Statements
.GOBACKStatement
.Specifiesthelogicalendofacalledprogram
.ItfunctionsliketheEXITPROGRAMstatementwhencodedasapartofacalledprogramandliketheSTOPRUNstatementwhencodedinamainprogram
.Returnscontroltothecallingprogram




Example

0000-MAIN-EXIT.

GOBACK.


PROCEDURE DIVISION
.Statements
.MOVEStatement
.Transfersdatafromoneareaofstoragetooneormoreotherareas




MOVEIdentifier-1TOIdentifier-2.

MOVELiteral-1TOIdentifier-2.

.Identifier-1/Literal-1.SendingField
.Identifier-2.ReceivingField







PROCEDURE DIVISION
.Statements
.MOVEStatement–NumericMOVE
.NumericFieldorLiteralismovedtoanumericreceivingField.
.Fortheintegerportion,movementisfromrighttoleft.Allnon-filledhigh-order(leftmost)integerpositionsofthereceivingfieldarereplacedwithzeros
.Forthedecimalportion,movementisfromlefttoright,beginningattheimplieddecimalpoint.
Low-order(rightmost)non-filleddecimalpositionsofthereceivingfieldarereplacedwithzeros




MOVE123TOWS-CONTANT.

MovingSignedNumeric

.Ifanumericfieldcanhavenegativecontents,thenitmusthaveanSinitsPICclause
.IfwecodeMOVE-123TOAMT1,forexample,thenAMT1shouldbedefinedwithaPICS9(3)
.AnSshouldbeincludedinthePICclauseofanumericfieldwheneverthesignofthenumberistoberetained





PROCEDURE DIVISION
.Statements
.MOVEStatement–Non-NumericMOVE
.Movinganalphanumericoralphabeticfield,definedbyaPICTUREofX'sorA's,toanotheralphanumericoralphabeticfield
.Movinganonnumericliteraltoanalphanumericoralphabeticfield
.Movinganumericfieldornumericliteraltoanalphanumericfieldortoanygroupitem
.Inanonnumericmove,dataistransmittedfromthesendingfieldtothereceivingfieldfromlefttoright.
.Low-orderorrightmostpositionsofthereceivingfieldthatarenotreplacedwithsendingfieldcharactersarefilledwithspaces.
.Agroupmoveisconsideredanonnumericmove
.Allgroupitems,eventhosewithnumericsubfields,aretreatedasalphanumericfields




MOVE“PROGRAMMER”TOWS-DESIGNATION.

MOVE“Y”TOEND-OF-FILE.

MOVE“ABC123”TOWS-CONSTANT.


PROCEDURE DIVISION
.Statements
.MOVEStatement–withFigurativeConstant


MOVEZEROSTOWS-TOTAL-HOURS.

MOVESPACESTOWS-NAME.


PROCEDURE DIVISION
.Statements
.MOVEStatement–DecimalDataError
.DonotmoveAlphanumericFieldstonumericfields
.Whenanumericfieldisusedinanarithmeticoperationandthefielddoesnotcontainnumericdata,aDecimalDataErrorwillOccur.





PROCEDURE DIVISION
.Statements
.MOVEStatement–QualificationofNames
.Ifthesamenameisusedtodefinefieldsindifferentrecordsorgroupitems,indicatewhichrecordorgroupitemistobeaccessed




Example:

01IN-REC.

05AMTPIC9(7).

01OUT-REC.

05 AMTPIC 9(7).

MOVEAMTOFIN-RECTOWS-AMOUNT.


PROCEDURE DIVISION
.Statements
.MOVEwithCORRESPONDING


MOVECORRIdentifier-1TOIdentifier-2.

.Bothidentifiersmustbegroupitems
.WhenyouspecifyCORRESPONDING,selecteditemsinidentifier-1aremovedtoidentifier-2






Example

1000-PROCESS.

MOVECORREMPLOYEE-REC-INTOEMPLOYEE-REC-OUT.


PROCEDURE DIVISION
.Statements
.PermissibleMOVEOperations


Receiving Field

Sending Field

Numeric

Alphabetic

Alphanumeric

Group Item

Numeric

Yes

No

Yes*

Yes

Alphabetic

No

Yes

Yes

Yes

Alphanumeric

No

Yes

Yes

Yes

ZEROS

Yes

No

Yes

Yes

SPACES

No

Yes

Yes

Yes

Group Item

No

Yes

Yes

Yes

* Numeric Integer fields can be moved to Alphanumeric fields, but numeric 
field with V in the PIC clause cannot be moved to Alphanumeric fields




PROCEDURE DIVISION

.Statements
.MOVEStatement–ReferencingSegmentsofafield


01WORK-AREA.

05WS-TELEPHONE-NUMPICX(14)VALUE“91-44-42250000”.

ToextracttheAreacodeonly

MOVEWS-TELEPHONE-NUM(4:2)TOWS-AREA-CODE.

Starting PositionExtract Length 
PROCEDURE DIVISION
.Statements
.STRINGStatement
.Usedtocombineseveralfieldstoformoneconcisefield(Concatenation)






STRING{{Identifier-1/Literal-1}...

DELIMITEDBY{Identifier-2/Literal-2/SIZE}}...

INTOIdentifier-3

END-STRING.

Example:

01 WORK-AREA.

05 STUDENT-NAME.

10 LAST-NAMEPIC X(15).

10 FIRST-NAMEPIC X(10).

10 MIDDLE-NAMEPIC X(10).

.NeedtoCombineas:JulieAnneJohnson


LAST-NAME

FIRST NAME

MIDDLE-NAME

Johnson

Julie

Anne




PROCEDURE DIVISION

.Statements
.STRINGStatement


STRING

FIRST-NAMEDELIMITEDBY„.

MIDDLE-NAMEDELIMITEDBY„.

LAST-NAMEDELIMITEDBY„.

INTONAME-OUT

END-STRING.

STRING 

FIRST-NAMEDELIMITED BY „ .

„ . DELIMITED BY SIZE

MIDDLE-NAMEDELIMITED BY „ .

„ . DELIMITED BY SIZE

LAST-NAMEDELIMITED BY „ .

INTO NAME-OUT

END-STRING.

It will move the characters to NAME-OUT until 
a blank character is found.
NAME-OUT will have : JulieAnneJohnson„ . DELIMITED BY SIZE 
Places a blank after each field.
NAME-OUT will have : Julie Anne Johnson 
PROCEDURE DIVISION
.ArithmeticVerbs
.AllthebasicarithmeticoperationsADD,SUBTRACT,MULTIPLYandDIVIDErequirethatthefieldsoperatedon
.havenumericPICclauses
.actuallyhavenumericdatawhentheprogramisexecuted






Data fields specified in any arithmetic statement must be defined in the 

DATA DIVISON, either in the FILE SECTION or in the 

WORKING-STORAGE SECTION


PROCEDURE DIVISION
.ArithmeticVerbs
.ADDStatement




ADDhastwoinstructionformats:

Format1

ADD{identifier-1}{literal-1}...TOidentifier-2...

Format2

ADD{identifier-1}{literal-1}...TO{identifier-2}{literal-2}GIVINGidentifier-3…

.Theresult,orsum,ofanADDoperationisalwaysplacedinthelastfieldmentioned.TheonlyfieldthatisalteredasaresultoftheADDoperationisthislastfield,whichistheonedirectlyfollowingthewordTO,whenusingFormat1,orGIVING,whenusingFormat2







PROCEDURE DIVISION
.ArithmeticVerbs
.ADDStatement




Example:

ADDHOURS-WORKEDTOWEEKLY-HOURS

.ThefieldsHOURS-WORKEDandWEEKLY-HOURSareaddedtogether,andtheresultisplacedinthelastfieldspecified--WEEKLY-HOURS
.WhenusingtheGIVINGformat,allfieldsandliteralsprecedingthewordGIVINGareaddedtogetherandthesumisplacedinthefieldfollowingthewordGIVING.Thus,whenusingtheGIVINGformat,thelastdatafieldisnotpartoftheADDoperation.




ADDHOURS-WORKEDOVERTIME-HOURS

GIVING TOTAL-HOURS


PROCEDURE DIVISION
.ArithmeticVerbs
.SUBTRACTStatement




TheSUBTRACToperationhasthefollowingtwoformats:

Format1

SUBTRACT{identifier-1}{literal-1}..FROMidentifier-2..

Format2

SUBTRACT{identifier-1}{literal-1}..FROM{identifier-2}{literal-2}GIVINGidentifier-3...


PROCEDURE DIVISION
.ArithmeticVerbs
.SUBTRACTStatement




Example:

Format1

SUBTRACT15.40FROMGROSS-PAY.

Format2

SUBTRACT15.40FROMGROSS-PAY

GIVINGNET-PAY.

.Examples1and2producethesameresultbutindifferentstorageareas.
.InExample2,theoriginalcontentsofNET-PAYarereplacedwiththeresultanddonotaffectthecalculation





PROCEDURE DIVISION
.ArithmeticVerbs
.MULTIPLYStatement




MULTIPLYhasthefollowingformats:

FORMAT1

MULTIPLY{identifier-1}{literal-1}BYidentifier-2...

FORMAT2

MULTIPLY{identifier-1}{literal-1}

BY{identifier-2} {literal-2} GIVINGidentifier-3…


PROCEDURE DIVISION
.ArithmeticVerbs
.MULTIPLYStatement




Example:

FORMAT1

MULTIPLYHOURS-WORKEDBYHOURLY-RATE.

FORMAT2

MULTIPLYHOURSBY60GIVINGMINUTES.


PROCEDURE DIVISION
.ArithmeticVerbs
.DIVIDEStatement




DIVIDEhasthefollowingformats:

FORMAT1

DIVIDE{identifier-1}{literal-1}INTOidentifier-2...

FORMAT2

DIVIDE{identifier-1}{literal-1}INTO{identifier-2}{literal-2}GIVINGidentifier-3...

FORMAT3

DIVIDE{identifier-1}{literal-1}BY{identifier-2}{literal-2}GIVINGidentifier-3...


PROCEDURE DIVISION
.ArithmeticVerbs
.DIVIDEStatement




Example:

FORMAT1

DIVIDE3INTOAVERAGE-BONUS.

FORMAT2

DIVIDE60INTOMINUTESGIVINGHOURS.

FORMAT3

DIVIDEMINUTESBY60GIVINGHOURS.

Either the word INTO or BY may be used 
with a DIVIDE statement. 
The GIVING clause is optional with INTO 
but required with BY 
PROCEDURE DIVISION
.ArithmeticVerbs
.ExampleofArithmeticoperations




CelsiustemperaturesaretobeconvertedtoFahrenheittemperaturesaccordingtothefollowingformula:

FAHRENHEIT=(9/5)CELSIUS+32

Solution1:

MULTIPLY9BYCELSIUS.

DIVIDE5INTOCELSIUS.

ADD32CELSIUSGIVINGFAHRENHEIT.

Solution2:

MULTIPLY1.8BYCELSIUS.

ADD32CELSIUSGIVINGFAHRENHEIT.


PROCEDURE DIVISION
.ArithmeticVerbs
.UsingREMAINDERclausewithDIVIDE
.Whenperformingadivisionoperation,theresultwillbeplacedinthereceivingfieldaccordingtothePICspecificationsofthatfield.Considerthefollowing:




DIVIDEMINUTESBY60

GIVINGWS-HOURS.

Letusassume

MINUTEScontainsvalueof402

WS-HOURShasaPICof9(2).

AftertheDIVIDEoperation402/60isperformed:6isplacedinWS-HOURS.

Tostoretheremaindervalue:

DIVIDEMINUTESBY60

GIVING WS-HOURS

REMAINDER WS-REMAINDER-MINS

WS-HOURS = 06WS-REMAINDER-MINS = 42 
PROCEDURE DIVISION
.ArithmeticVerbs
.ROUNDEDOption




Consider the following example:

ADD AMT1 AMT2 

GIVING AMT3

AMT1AMT2 AMT3

PICTURE ContentsPICTURE ContentsPICTURE Contents after ADD

99V999 12.857 99V999 25.142 99V99 37.99

12.857

+25.142

------------

37.999this will be 
truncated 

.Thelow-orderdecimalpositionistruncated






To obtain rounded results, the ROUNDEDoption may be specified with any arithmetic statements 
PROCEDURE DIVISION
.ArithmeticVerbs
.ROUNDEDOptionSome examples:




1. ADD AMT1 TO AMT2 ROUNDED.

2. SUBTRACT DISCOUNT FROM TOTAL ROUNDED.

3. MULTIPLY QTY BY PRICE ROUNDED.

4. DIVIDE UNITS-OF-ITEM INTO TOTAL ROUNDED.

5. ADD AMT1 AMT2 GIVING TOTAL1 ROUNDED.

6. ADD AMT1 AMT2 GIVING TOTAL1 ROUNDED 

TOTAL2 ROUNDED.

In example 5If AMT1 and AMT2 had contents of 12.8576 and 25.142 and TOTAL1 had a PIC of 9(2)V9(2), 
the result would be rounded to 38.00 
PROCEDURE DIVISION
.ArithmeticVerbs
.ROUNDEDOption




HowRoundingIsAccomplished

.ROUNDEDisoptionalwithallarithmeticoperations
.IftheROUNDEDoptionisnotspecified,truncationofdecimalpositionswilloccuriftheresultantfieldcannotaccommodateallthedecimalpositionsintheanswer
.WiththeROUNDEDoption,thecomputerwillalwaysroundtheresulttothePICTUREspecificationofthereceivingfield
.IfROUNDEDandREMAINDERaretobeusedinthesameDIVIDEstatement,ROUNDEDmustappearfirst




Format:

DIVIDE ... 

[ROUNDED] 

[REMAINDER identifier]


PROCEDURE DIVISION
.ArithmeticVerbs
.ONSIZEERROROption




Considerthefollowingexample:

ADDAMT1,AMT2TOAMT3

Beforetheoperationthefieldscontainthefollowing:

AMT1AMT2AMT3

PICTURE Contents PICTURE Contents PICTURE Contents

9(3)8009(3) 150 9(3) 050

.Theprogramwilladd800,150,and050.
.Itwillattempttoplacethesum,1000,intoAMT3,whichisathree-positionfield.
.SincenumericMOVEoperationsmoveintegerdatafromrighttoleft,000willbeplacedinAMT3
.Inthiscase,Theresultantfieldisnotlargeenoughtostoretheaccumulatedsum.Wesaythatanoverfloworsizeerrorconditionhasoccurred
.Thecomputerwillnotgenerallystoporaborttherunbecauseofasizeerrorcondition;instead,itwilltruncatehigh-orderorleftmostpositionsofthefield.Thus,000willbeplacedinAMT3





PROCEDURE DIVISION
.ArithmeticVerbs
.ONSIZEERROROption
.COBOLhasabuilt-insolution.
.UseanONSIZEERRORclausewithanyarithmeticoperationasfollows




FORMAT:

arithmeticstatement

[ONSIZEERRORimperativestatement...]

Example1:

ADDAMT1AMT2TOAMT3GIVINGTOTAL-OUT

ONSIZEERRORMOVEZEROTOTOTAL-OUT

END-ADD.

Example2:

DIVIDE60INTOMINUTESGIVINGHOURS

ONSIZEERRORMOVE„INVALIDDIVIDE.TOERROR-MESSAGE

END-DIVIDE.


PROCEDURE DIVISION
.ArithmeticVerbs
.ONSIZEERROROption




DividingbyzerocausesaSIZEERROR

QTYTOTAL

PICTURE Contents PICTURE Contents 

9(4)00009(2) 10

.WhenyouspecifyONSIZEERROR,thecomputerwilltestthatthedivisorisnotzerobeforeattemptingtoDIVIDE




DIVIDEQTYINTOTOTAL

ONSIZEERRORMOVEZEROTOTOTAL

END-DIVIDE.

IF QTY IS NOT ZERODIVIDE QTY INTO TOTALELSEMOVE ZERO TO TOTALEND-IF. 
PROCEDURE DIVISION
.ArithmeticVerbs
.ONSIZEERROROption
.IftheONSIZEERRORoptionisemployedalongwiththeROUNDEDoption,thewordROUNDEDalwaysprecedesONSIZEERROR




Format:

arithmeticstatement

[ROUNDED]

[ONSIZEERRORimperativestatement...]


PROCEDURE DIVISION
.ArithmeticVerbs
.NOTONSIZEERROROption




Example:

ADDAMT1,AMT2GIVINGTOTAL-AMT

NOTONSIZEERROR

PERFORM300-WRITE-RTN

END-ADD

.300-WRITE-RTN is executed only if the ADD operation results in a valid addition





PROCEDURE DIVISION
.ArithmeticVerbs
.COMPUTEStatement
.Providesanothermethodofperformingarithmeticoperation
.UsesarithmeticSymbolsratherthanarithmeticVerbs






SymbolMeaning

+ADD

-SUBTRACT

*MULTIPLY

/DIVIDE

**Exponentiation

Examples:

1.COMPUTETAX=.05*AMT.

2.COMPUTEDAILY-SALES=QTY*UNIT-PRICE/5.

3.COMPUTENET=AMT-.05*AMT.


PROCEDURE DIVISION
.ArithmeticVerbs
.RuleswithaCOMPUTEStatement
.MustfollowprecisespacingruleswhenusingtheCOMPUTEstatement.Thatis,theequalsignaswellasthearithmeticsymbolsmustbeprecededandfollowedbyaspace






TocalculateSumofB,CandDandplacetheresultinA

COMPUTEA=B+C+D

.TheROUNDED,ONSIZEERRORandNOTONSIZEERRORoptionsmayalsobeusedwiththeCOMPUTE






COMPUTEidentifier-1[ROUNDED]...={arithmeticexpressions/literal-1/identifier-2}

[ONSIZEERRORimperativestatement]

[NOTONSIZEERRORimperativestatement]

[END-COMPUTE]

The primary advantage of a COMPUTE statement is that several arithmetic operations may be 
performed with one instruction 
PROCEDURE DIVISION
.ArithmeticVerbs
.OrderofEvaluationinCOMPUTEStatement




()OperationswithinParenthesesareperformedfirst

**exponentiation

*or/(whicheverappearsfirstfromlefttoright)

+or-(whicheverappearsfirstfromlefttoright)

.Withoutparentheses,exponentiationisperformedfirst
.Multiplicationanddivisionoperationsfollowanyexponentiationandprecedeadditionorsubtractionoperations
.Iftherearetwoormoremultiplicationordivisionoperations,theyareevaluatedfromlefttorightintheexpression
.Additionandsubtractionareevaluatedlast,alsofromlefttoright







PROCEDURE DIVISION
.ArithmeticVerbs
.INITIALIZEStatement
.Individualfieldsoraseriesofelementaryitemscontainedwithinagroupitemcanallbeinitialized
.Numericfieldsareinitializedwithzeros
.Alphanumericfieldsareinitializedwithblanks






WORKING-STORAGESECTION.

01 WS-TEMP-NAMEPIC X(30).

01 WS-TOTAL-AMOUNTPIC 9(07)V99.

01 WS-WORK-FIELDS. 

05 WS-CHAR PIC X(30). 

05 WS-NUMERIC PIC 9(10). 

PROCEDURE DIVISION.

INITIALIZEWS-TEMP-NAME.

INITIALIZEWS-TOTAL-AMOUNT.

INITIALIZEWS-WORK-FIELDS.

Sets WS-TEMP-NAME to SPACESSets WS-TOTAL-AMOUNT to ZEROSSets WS-CHAR to SPACES and 
WS-NUMERIC to ZEROS 
PROCEDURE DIVISION
.DecisionMakingStatements
.IFStatement




FORMAT

IFcondition-1

[THEN]*

imperativestatement[s]

[ELSE

imperativestatement[s]

[END-IF]*

.*ThewordsTHENandEND-IFareoptional







PROCEDURE DIVISION
.DecisionMakingStatements
.RelationalOperators
.Relationaloperatorscanbeusedinplaceofwords






ThefollowingsymbolsforsimplerelationalconditionsarevalidwithinaCOBOLstatement:

SymbolMeaning

<IS LESS THAN

>IS GREATER THAN

=IS EQUAL TO

<=IS LESS THAN OR EQUAL TO

>=IS GREATER THAN OR EQUAL TO

Examples:

IF AMOUNT > ZERO

IF FIRST-NAME = SPACES

IF AMOUNT1 <= 0


PROCEDURE DIVISION
.DecisionMakingStatements
.DoNotMixFieldTypesinaComparison
.Fieldsthatarecomparedtooneanothershouldhavethesamedatatypestoobtainproperresults


.NumericFieldsShouldNotContainBlanks




Supposewecode

IFAMT-INISEQUALTO10

ADD1TOCOUNTER

END-IF.

.IfAMT-INwereafielddefinedasnumeric,butactuallycontainedallblanks,theinstructionwouldresultinadataexceptionerror,whichcausesaprogramtoterminateabnormally







PROCEDURE DIVISION

.DecisionMakingStatements
.HowComparisonsArePerformed
.Whencomparingnumericfields,thefollowingareallconsideredequal




01212.0012+12

.NumericcomparisonsareperformedinCOBOLalgebraically.Although12.00doesnothavethesameinternalconfigurationas012,theirnumericvaluesareknowntobeequal


.Similarly,whencomparingnonnumericfields,thefollowingareconsideredequivalent:




ABCABCb(b--denotesablankposition)ABCbb

.Low-orderorrightmostblankswillnotupsettheequivalence.Onlysignificantornonblankpositionsarecompared,fromlefttoright.Consequently,bABCisnotequaltoABCbsinceAisnotequaltoblanks







PROCEDURE DIVISION

.DecisionMakingStatements
.EBCDICCollatingSequence
.Whenperforminganalphanumericcomparison,thehierarchyofthecomparison,calledthecollatingsequence,dependsonthecomputerbeingused
.CollatingSequencefortheAS/400isEBCDIC[ExtendedBinaryCodedDecimalInterchangeCode].UsedtorepresentLetters,numbers,Specialcharacters
.CharactersarecomparedtooneanotherintheEBCDICasfollowsLow Special charactersa-zA-ZHigh0-9




.Fornumericcomparisons,012<022<042,andsoon
.ForalphabetsA<B<Candsoon
.LowercaselettersareLessthanuppercaseletters
.LettersareLessthanNumbers







PROCEDURE DIVISION
.DecisionMakingStatements
.CONTINUEorNEXTSENTENCEstatement
.Enables
.toavoidperforminganyoperationifaconditionexists
.toexecuteinstructionsonlyiftheELSEconditionismet






IFAMOUNT1=AMOUNT2

CONTINUE

ELSE

ADD1TOTOTAL.

If END-IF is included as a scope terminator, 
CONTINUE must not be specified
Alternate Solution:

IF AMOUNT1 = AMOUNT2

NEXT SENTENCE

ELSE

ADD 1 TO TOTAL

END-IF.

Recommended Solution:
IF AMOUNT1 NOT = AMOUNT2ADD 1 TO TOTALEND-IF. 
PROCEDURE DIVISION

.DecisionMakingStatements
.NestedIFstatement
.AnestedconditionalisaconditionalinwhichanIFstatementitselfcancontainadditionalIFclauses.




IFcondition-1

IFcondition-2

statement-1

ELSE

statement-2

END-IF

ELSE

IFcondition-3

statement-3

ELSE

statement-4

END-IF

END-IF

Use END-IF for each IF statement avoid errors


PROCEDURE DIVISION

.DecisionMakingStatements
.UsingORinaConditional
.Toperformanoperationoraseriesofoperationsifanyoneofseveralconditionsexists,useacompoundORcondition




Example:

1.IFAMT1=AMT2ORAMT2>AMT3

PERFORM500-TOTAL-RTN

END-IF.

2. IF AMT1 < AMT3 

ORAMT1 = AMT4

ADD AMT1 TO TOTAL

ELSE

PERFORM 600-ERR-RTN

END-IF.

3. IF TOTAL = 7 OR 8

PERFORM 500-PRINT-RTN

END-IF.


PROCEDURE DIVISION

.DecisionMakingStatements
.UsingANDinaConditional
.Ifastatementorstatementsaretobeexecutedonlywhenallofseveralconditionsaremet,usethewordANDinthecompoundconditional




Example:

IFAMT1=AMTA

ANDAMT2 = AMTB

ANDAMT3 = AMTC

PERFORM 500-PRINT-RTN

ELSE

PERFORM 600-ERR-RTN

END-IF.


PROCEDURE DIVISION
.DecisionMakingStatements
.UsingANDandORinthesameStatementExample:
IF (AMT1 < 20 ORAMT1 = 20) 
AND(AMT1 < 10 ORAMT1 = 10)
PERFORM 500-PRINT-RTNEND-IF.




HIERARCHYRULES

1. Conditions surrounding the word AND are evaluated first.

2. Conditions surrounding the word OR are evaluated last.

3. When there are several AND or OR connectors, the AND conditions are evaluated first, 

as they appear in the statement, from left to right. Then the OR conditions are evaluated, 

also from left to right

4. To override Rules 1-3, use parentheses around conditions you want to be evaluated first


PROCEDURE DIVISION
.DecisionMakingStatements
.EVALUATEStatement
.Usedtoimplementthecasestructure
.UsedinsteadofnestedIFStatements






Format:

EVALUATE{identifier-1/expression-1}

WHENCONDITION-1

imperativestatemet-1

WHENCONDITION-2

imperativestatemet-2

.

.

WHENOTHER

imperativestatemet-3

END-EVALUATE


PROCEDURE DIVISION
.DecisionMakingStatements
.EVALUATEStatement




IFYEARS-IN-COLLEGE-IN=1

PERFORM300-FRESHMAN-RTN

ELSE

IFYEARS-IN-COLLEGE-IN=2

PERFORM400-SOPHOMORE-RTN

ELSE

IFYEARS-IN-COLLEGE-IN=3

PERFORM500-JUNIOR-RTN

ELSE

IFYEARS-IN-COLLEGE-IN=4

PERFORM600-SENIOR-RTN

ELSE

PERFORM 800-ERR-RTN

END-IF

END-IF

END-IF

END-IF

Using Nested IF


PROCEDURE DIVISION

.DecisionMakingStatements
.EVALUATEStatement
.ThepreviousIFstatementscanbemoreclearlyandefficientlyimplementedusingtheEVALUATEstatement:




EVALUATEYEARS-IN-COLLEGE-IN

WHEN1

PERFORM300-FRESHMAN-RTN

WHEN2

PERFORM400-SOPHOMORE-RTN

WHEN3

PERFORM500-JUNIOR-RTN

WHEN4

PERFORM600-SENIOR-RTN

WHENOTHER

PERFORM800-ERROR-RTN

END-EVALUATE

Using EVALUATE


PROCEDURE DIVISION

.DecisionMakingStatements
.EVALUATEwithTHRUClause




EVALUATEAVERAGE

WHEN60THRU100

MOVE„A.TOGRADE

WHEN50THRU59

MOVE„B.TOGRADE

WHEN35THRU49

MOVE„C.TOGRADE

WHEN0THRU34

MOVE„F.TOGRADE

WHENOTHER

PERFORM800-ERROR-RTN

END-EVALUATE


PROCEDURE DIVISION
.DecisionMakingStatements
.EVALUATEwithTRUE




EVALUATETRUE

WHENAVERAGE>=60AND<=100

MOVE„A.TOGRADE

WHENAVERAGE>=50AND<=59

MOVE„B.TOGRADE

WHENAVERAGE>=35AND<=49

MOVE„C.TOGRADE

WHENAVERAGE>=0AND<=34

MOVE„F.TOGRADE

WHENOTHER

PERFORM800-ERROR-RTN

END-EVALUATE


PROCEDURE DIVISION
.DecisionMakingStatements
.DATAVALIDATION
.SignTest
.WecantestwhetherafieldisPOSITIVE,NEGATIVE,orZEROwithasigntestIF AMT IS POSITIVEPERFORM 200-CALC-RTNEND-IF.
IF AMT IS NEGATIVEPERFORM 900-ERR-RTNEND-IF.







PROCEDURE DIVISION
.DecisionMakingStatements
.DATAVALIDATION
.ClassTest
.WecantestwhetherafieldvalueisNUMERICorALPHABETIC






NumericTest:

IF AMT1 IS NUMERIC

PERFORM 200-CALC-RTN

END-IF.

Alphabetic Test:

IF NAME IS ALPHABETIC

PERFORM 300-ALPHA-RTN

END-IF.

ALPHABETIC:A-Z,a-zandblank

ALPHABETIC-UPPER:A-Zandblank

ALPHABETIC-LOWER:a-zandblank

IF AMT2 IS NOT NUMERIC

PERFORM 900-ERR-RTN

END-IF.

IF NAME IS ALPHABETIC-UPPER

PERFORM 310-UPPER-CASE-RTN

END-IF.

IF NAME IS ALPHABETIC-LOWER

PERFORM 310-LOWER-CASE-RTN

END-IF.


PROCEDURE DIVISION

.DecisionMakingStatements
.CONDITION-NAMES
.An88-levelentrycodedintheDATADIVISIONisacondition-namethatdenotesapossiblevalueforanidentifier




Formatfor88-levelitems:

88condition-nameVALUEliteral.

.Thecondition-namemustbeuniqueanditsVALUEmustbealiteralconsistentwiththedatatypeofthefieldprecedingit




05ARE-THERE-MORE-RECORDSPICX(3)VALUE„YES..

88 THERE-ARE-MORE-RECORDS VALUE „YES..

88 NO-MORE-RECORDS VALUE „NO..

IFNO-MORE-RECORDS

PERFROM 900-CLOSE-RTN

END-IF

Instead of condition

IF ARE-THERE-MORE-RECORDS = „NO.


PROCEDURE DIVISION

.DecisionMakingStatements
.SETStatement
.Usedtosetacondition-nametoTRUE.






SETNO-MORE-RECORDSTOTRUE.

.Whenthisstatementisexecuted,thevalue„NO.associatedwiththecondition-nameNO-
MORE-RECORDSisplacedinitsconditionalvariableARE-THERE-MORE-RECORDS
.Ifmultiplecondition-namesarespecified,onlyonecondition-namecanbeTRUEatonetime.







PROCEDURE DIVISION

.DecisionMakingStatements
.INSPECTStatement
.Tocountthenumberofoccurrencesofaspecificcharacterinafield
.Tofillallorportionsofadataitemwithspacesorzeros
.Toreplacespecificcharacterwithanothercharacter






Format1INSPECTidentifier-1 
TALLYING{identifier-2 FOR{{ALL} {LEADING} {CHARACTERS}} {identifier-3} {literal-1}}
[{BEFORE} {AFTER} INITIAL {identifier-4} {literal-2}]…

Format2

INSPECTidentifier-1 

REPLACING {{CHARACTERS} {{ALL} {LEADING} {FIRST}} {identifier-2} {literal-1}}

BY{identifier-3} {literal-2} [{BEFORE} {AFTER} INITIAL {identifier-4} {literal-3}]}..


PROCEDURE DIVISION

.DecisionMakingStatements
.INSPECTStatement




Examples:

INSPECTITEM-1TALLYINGCTR1FORALLSPACES

INSPECTITEM-2TALLYINGCTR2FORCHARACTERSBEFOREINITIALSPACE

INSPECTITEM-3TALLYINGCTR3FORLEADINGZEROS

ItemsResulting Contents

ITEM-1 = bbb67bCTR1 = 4

ITEM-2 = 01787bCTR2 = 5

ITEM-3 = 007800CTR3 = 2


PROCEDURE DIVISION

.DecisionMakingStatements
.INSPECTStatement




Examples:

Field Inspected

BeforeAfter

INSPECT DATE-IN REPLACING ALL „-. BY „/. 10-25-98 10/25/98

INSPECT SSN REPLACING ALL SPACES BY „-. 080 62 7731 080-62-7731

INSPECT ITEM-E REPLACING LEADING „1. BY „2. 113211223211

INSPECT ITEM-E REPLACING CHARACTERS 113211333211

BY „3. BEFORE INITIAL „2.

INSPECT ITEM-E REPLACING FIRST „X. BY „Y. ABCXYZ ABCYYZ


PROCEDURE DIVISION

.Statements
.ACCEPTStatement
.Transfersdataintothespecifiedidentifierfrom
.SysteminformationDATE,DAY,TIME
.LOCALDATAAREA






DATE/DAY/TIME

ACCEPTidentifierFROMDATE/DAY/TIME

.Identifier.Receivingdata-item






DATE

Has the implicit PICTURE 9(6).

The sequence of data elements (from 
left to right) is:

2 digits for year of century

2 digits for month of year

2 digits for day of month

Thus, 25 December 1988 is expressed 
as: 881225

DAY

Has the implicit PICTURE 9(5).

The sequence of data elements (from 
left to right) is:

2 digits for year of century

3 digits for day of year

Thus 25 December 1988 is expressed 
as: 88360

TIME

Has the implicit PICTURE 9(8).

The sequence of data elements (from 
left to right) is:

2 digits for hour of day

2 digits for minute of hour

2 digits for second of minute

2 digits for hundredths of second

Thus 12.25 seconds after 2:41 PM is 
expressed as: 14411225


PROCEDURE DIVISION
.Statements
.ACCEPTStatement




LOCALDATAAREA

ACCEPTidentifier-1FROMmnemonic-name

.Onlyapplicablewhenthemnemonic-nameintheSPECIAL-NAMESparagraphisassociatedwiththeenvironment-nameLOCAL-DATA
.Identifier-1.Receivingdata-item






ENVIRONMENT DIVISION.

CONFIGURATION SECTION. 

SPECIAL-NAMES.
LOCAL-DATA IS LOCAL-DATA-AREA.

mnemonic-name

ACCEPT WS-DATA FROM LOCAL-DATA-AREA.


File Handling


Topics 

.IntroductiontoCOPYStatement
.SequentialFileProcessing
.IndexedFileProcessing
.RelativeFileProcessing
.DisplayFileProcessing
.PrinterFileProcessing



Introduction to COPY Statement 

.COPYStatement


.To copy prewritten COBOL entries stored in a library into a 
program


.Often used to copy
.FD, 01 entries that define and describe files and records
.Tables
.SCREEN Sections
.Standard modules used in PROCEDURE DIVISION


.Used in 
.ENVIRONMENT DIVISION
.DATA DIVISION
.PROCEDURE DIVISION





.COPYStatement


COPY text-name { OF / IN } library-name.
.Benefits 
.Saves programmer coding, debugging time by using code already 
written 




Introduction to COPY Statement 


.COPYStatement


Example
•Suppose file called Customer, stored in library contains following entries:
01 CUSTOMER-REC.
05CUST-NOPIC X(5).
05CUST-NAMEPIC X(20).
05CUST-ADDRESSPIC X(30).
05CUST-BAL-DUEPIC 9(4)V99.
•Code COPY statement at point in program where entries should appearDATA DIVISION.
FILE SECTION.
FD CUSTFILE.
COPY CUSTOMER.


Introduction to COPY Statement 


.COPYStatement


Replacing COPY Statement EntriesREPLACING==pseudo-text-1== ==pseudo-text-2==
identifier-1BYidentifier-2literal-1literal-2word-1 word-2
•Add REPLACING clause to COPY to make changes to copied 
entries


Introduction to COPY Statement 


.COPYStatement


Example

COPY CUSTOMER 

REPLACING 

CUST-NO BY CUST-NUMBER,

==X(5)== BY ==X(6)==.

Introduction to COPY Statement 
.COPYStatement-Format2


COPY DDS-ALL-FORMATS OF file-name

COPY DDS-format-name OF file-name.

.Can be used only in the DATA DIVISION
.COPYcreates the DATA DIVISION statements to describe the display file
.The DDS-ALL-FORMATSoption of COPY statement generates one storage 
area for all the record formats


Introduction to COPY Statement 


Sequential File Processing 

.SELECTStatement


SELECTfile-name-1

ASSIGNTO implementor-name-1

[ORGANIZATIONIS] SEQUENTIAL

[ACCESSMODE IS SEQUENTIAL]

[FILE STATUSIS data-name-1]


.FDEntryinDATADIVISION


DATA DIVISION.

FILE SECTION.

FD EMPLOYEE-FILE.

01 EMPLOYEE-RECORD.

COPY DDS-ALL-FORMATS OF EMPPF.

Sequential File Processing 


Sequential File Processing 

.READStatement


READfile-name-1AT ENDstatement-1 . . .
NOT AT ENDstatement-2 . . .
END-READ 
Sequential File Processing 

.WRITEStatement


WRITErecord-name-1

END-WRITE

WRITErecord-name-1 FROM identifier-1

END-WRITE


Sequential File Processing 

.REWRITEStatement


REWRITErecord-name-1

END-REWRITE

REWRITErecord-name-1 FROM identifier-1

END-REWRITE

For sequential files and sequential access mode, the record retrieved by the last successfully 
processed READ statement is replaced


Indexed File Processing 

.SELECTStatement


SELECTfile-name-1

ASSIGNTO implementor-name-1

ORGANIZATIONIS INDEXED

ACCESSMODE IS SEQUENTIAL/RANDOM/DYNAMIC

RECORD KEY IS EXTERNALLY-DESCRIBED-KEY

[FILE STATUSIS data-name-1]


.READStatement


For Sequential Access Mode

READfile-name-1

AT ENDstatement-1 . . .

NOT AT ENDstatement-2 . . .

END-READ

Indexed File Processing 
.READStatement


For Random Access Mode

READfile-name-1

INVALID KEYimperative statement-1 . . .

NOT INVALID KEYimperative statement-2 . . .

END-READ

Indexed File Processing 


.READStatement


For Dynamic Access Mode –RANDOM Retrieval

READfile-name-1

INVALID KEYimperative statement-1 . . .

NOT INVALID KEYimperative statement-2 . . .

END-READ

For Dynamic Access Mode –Sequential Retrieval

READfile-name-1 NEXT [RECORD]

AT ENDimperative statement-1 . . .

NOT AT ENDimperative statement-2 . . .

END-READ

Indexed File Processing 


.STARTStatement
.Usedtobeginprocessingakeyedfilesequentiallyatanyrecordlocation
.FilemustbeopenineitherINPUTorI-Omode
.NotallowedforFilehavingSequentialOrganization
.STARTlocatesrecordbutdoesnotREADit




Indexed File Processing 

Format:

STARTfile-name-1 

IS =

KEYIS >data-name-1 /

IS NOT<EXTERNALLY-DESCRIBED-KEY

IS >=

[INVALIDKEY imperative-statement-1]

[NOTINVALIDKEY 

imperative-statement-2]

[END-START]


.STARTStatement
.Example


Indexed File Processing 

Sequential Access ModeMOVE 222 TO I-PART-NUMBER.
START INVENTORY-FILEINVALID KEYDISPLAY „NO RECORD FOUND.
CLOSE INVENTORY-FILESTOP RUN 
NOT INVALID KEYREAD INVENTORY-FILEAT ENDMOVE „Y. WS-EOFEND-READEND-START.
.KEY clause can be omitted only if checking for value equalto RECORD KEY value


Positions to the record in the file 
with a part number = 222


.STARTStatement
.Example


Indexed File Processing 

Dynamic Access Mode

MOVE 200 TO I-PART-NUMBER.

START INVENTORY-FILE

KEY >= EXTERNALLY-DESCRIBED-KEY

INVALID KEY

DISPLAY „NO PART NUMBERS GREATER THAN 200.

CLOSE INVENTORY-FILE

STOP RUN 

NOT INVALID KEY

READ INVENTORY-FILE NEXT RECORD

AT END

MOVE „Y. WS-EOF

END-READ

END-START.

Positions to the record in the file 
with a part number > = 200


.WRITEStatement


WRITErecord-name-1 [FROM identifier-1]

INVALID KEYimperative statement-1 . . .

NOT INVALID KEYimperative statement-2 . . .

END-WRITE

Indexed File Processing 


.REWRITEStatement


REWRITErecord-name-1 [FROM identifier-1]
INVALID KEYimperative statement-1 . . .
NOT INVALID KEYimperative statement-2 . . .
END-REWRITE
Indexed File Processing 


.DELETEStatement


DELETEfile-name-1

INVALID KEYimperative statement-1 . . .

NOT INVALID KEYimperative statement-2 . . .

END-DELETE

Indexed File Processing 


Relative File Processing 

.SELECTStatement


SELECTfile-name-1

ASSIGNTO implementor-name-1

ORGANIZATIONIS RELATIVE

ACCESSMODE IS SEQUENTIAL/RANDOM/DYNAMIC

RELATIVEKEY IS data-name-1

[FILE STATUSIS data-name-2]

.The position of each record in the file is determined by its relative record number
.The first record area is addressed by relative record number 1, and the 10th is addressed by 
relative record number 10 and so on
.Relative files must be assigned to DATABASE.



Relative File Processing 

.SELECTStatement


.RELATIVE KEY clause
.Optional if ACCESS is SEQUENTIAL
.Otherwise, required


.ACCESS IS DYNAMIC allows both sequential and random 
access in same program
.RELATIVE KEY not part of record
.In separate WORKING-STORAGE entry


.If RELATIVE KEY is WS-RRN
.Entry in WORKING-STORAGE is




01 WS-RRNPIC 9(4) VALUE ZERO.

.FILE STATUS field used same way as with indexed files



Relative File Processing 

.I/OStatements


.READ … AT END to read sequentially
.READ … INVALID KEY to read randomly
.Move key value of record to locate to RELATIVE KEY 
before executing READ


.WRITE … INVALID KEY to write record to relative file
.REWRITE … INVALID KEY to update
.DELETE … INVALID KEY to remove record from file





Display File Processing 

.SELECTStatement


SELECTDISPLAY-FILE

ASSIGNTO WORKSTATION-EMPD1-SI

ORGANIZATIONIS TRANSACTION

ACCESSMODE IS SEQUENTIAL

[FILE STATUSIS data-name-1]

CONTROL-AREA IS data-name-2.

.Device type WORKSTATION must be specified in the ASSIGN clause
.Separate Indicator Area (SI) must be specified if the display file has keyword INDARA in its 
DDS
.File Type TRANSACTION is specified in the ORGANIZATION clause



Display File Processing 

.FDEntryinDATADIVISION


DATA DIVISION.

FILE SECTION.

FD DISPLAY-FILE.

01 DISPLAY-RECORD.

COPY DDS-ALL-FORMATS OF EMPD1.


Display File Processing 

.SeparateIndicatorArea(SI)


SI indicates that indicators are stored in a separate indicator 
area.

Group item is defined in WORKING-STORAGE SECTION for all 
indicators.

The INDICATORS phrase is used in READ and WRITE 
statements when sending indicator values to and from the 
display file

Boolean value B.1. for ON and B.0. for OFF are used for 
indicators.


Display File Processing 

.SeparateIndicatorArea(SI)


FILE CONTROL.

SELECT DISPLAY-FILE

ASSIGN TO WORKSTATION-EMPD1-SI

DATA DIVISION.

FILE SECTION.

FD DISPLAY-FILE.

01 DISPLAY-RECORD.

COPY DDS-ALL-FORMATS OF EMPD1.

WORKING-STORAGE SECTION.

01 WS-INDICATORS-LIST.

05 IN21INDICATOR21PIC 1VALUE B’0’.

88 RECORD-NOT-FOUNDVALUE B’1’.

PROCEDURE DIVISION.

.

SET RECORD-NOT-FOUND TO TRUE.

.

WRITE DISPLAY-RECORD FORMAT IS ‘SCREEN1’

INDICATORS ARE WS-INDICATORS-LIST.

READ DISPLAY-FILE RECORD.


Display File Processing 

.CONTROL-AREAClause


.Refers to a Group item
.Can be 2 bytes or 12 bytes or 22 bytes long


.Identifies 
.Function key that the user pressed
.Name of the Program device used
.Name of the DDS record format that was reference by the last I-O 
statement


.Function key Indicators
.Indicator 03 is assigned to function key F3
.Indicator 12 is assigned to function key F12 
.and so on





Display File Processing 

.CONTROL-AREAClause


FILE CONTROL.

SELECT . . .

CONTROL-AREA IS WS-CONTROL.

WORKING-STORAGE SECTION.

01 WS-CONTROL.

05 WS-FUNCTION-KEYPIC X(2).

88 WS-FUNCTION-KEY-03VALUE ’03’.

88 WS-FUNCTION-KEY-12VALUE ’12’.

88 NO-FUNCTION-KEY-PRESSEDVALUE ’00’.

05 WS-DEVICE-NAMEPIC X(10).

05 WS-RECORD-FORMATPIC X(10).

01 WS-INDICATORS-LIST.

05 IN21INDICATOR21PIC 1VALUE B’0’.

88 RECORD-NOT-FOUNDVALUE B’1’.

PROCEDURE DIVISION.

OPEN I-O DISPLAY-FILE.

IF NOT WS-FUNCTION-KEY-03

WRITE DISPLAY-RECORD FORMAT IS ‘SCREEN1’

INDICATORS ARE WS-INDICATORS-LIST.

READ DISPLAY-FILE RECORD

END-IF.


Display File Processing 

.OPENStatement


Display file must be open in I-O mode

OPEN I-O DISPLAY-FILE.


Display File Processing 

.WRITEStatement
.READStatement


WRITE DISPLAY-RECORD 

FORMAT IS „record-format-name.

INDICATORS ARE identifier-1.

READ DISPLAY-FILE RECORD

FORMAT IS „record-format-name.

INDICATORS ARE identifier-1.

To display a screen, both WRITE and READ statement need to be executed


Display File Processing 
.MOVEStatement


.Moving values from Program to Screen


MOVE EMPNO OF EMPLOYEE-RECORD 

TO EMPNO OF SCREEN1-O.

MOVE CORR EMPLOYEE-RECORD TO SCREEN1-O.

.Moving values from Screen to Program


MOVE EMPNO OF SCREEN1-I 

TO EMPNO OF EMPLOYEE-RECORD

MOVE CORR SCREEN-I TO EMPLOYEE-RECORD.


File Status Value and Meanings 

.FILESTATUSclausemonitorstheexecutionofeachinput-outputrequestforthefile.



Printer File Processing


Topics 

.IntroductiontoPrinterfile
.PrinterFileTypes
.UsingPrinterfileinCOBOL/400



Introduction to Printer file

.PrinterFile


.Used for Reports generation



Printer file Types
.TwoTypes


.Program described printer file
.File, record and field descriptions are defined internally within the 
program
.Report Specifications are hard-coded in the WORKING-STORAGE 
SECTION of DATA DIVISION




.Externally described printer file
.Created DDS using STRRLU command
.Compiled as separate object
.Used in program





Using Printer File in COBOL/400

.SELECTStatement


.For Program described


SELECT PRINT-FILE

ASSIGN TO PRINTER-<Pinter-device-name>

ORGANIZATION IS SEQUENTIAL.

.For Externally described 


SELECT PRINT-FILE

ASSIGN TO FORMATFILE-<Externally-described-print-file>

ORGANIZATION IS SEQUENTIAL.


Using Printer File in COBOL/400

.FDEntryinDATADIVISION


.For Program described


FD PRINT-FILE.

01 PRINT-RECORDPIC X(132).

.For Externally described 


FD PRINT-FILE.

01 PRINT-RECORD.

COPY DDS-ALL-FORMATS-O OF <Externally-described-print-file>.


Using Printer File in COBOL/400

.WORKING-STORAGEEntry


.For Program described


01 HEADER-LINE.

05 EMP-NAMEPIC X(15) VALUE „Employee Name..

05 FILLERPIC X(20).

05 EMP-DEPTPIC X(10) VALUE „Department..

05 FILLERPIC X(20).

05 EMP-SALPIC X(10) VALUE „Salary..

01 DETAIL-LINE.

05 EMPNAMEPIC X(30) VALUE SPACES.

05 FILLERPIC X(05).

05 EMPDEPTPIC X(10) VALUE SPACES.

05 FILLERPIC X(20).

05 EMPSALPIC 9(5)V99 VALUE ZEROS.


Using Printer File in COBOL/400
.OPENStatement


.OPEN OUTPUT PRINT-FILE.



Using Printer File in COBOL/400

.WRITEStatement


.For Program described


WRITE PRINT-RECORD [FROM identifier-1]

[AFTER/BEFORE] [ADVANCING] [mnemonic-name-1/PAGE ].

WRITE PRINT-RECORD [FROM identifier-1]

[AFTER/BEFORE] [ADVANCING] [identifier-2/integer-1] LINE/LINES].

.For Externally described


WRITE PRINT-RECORD [FROM identifier-1]

FORMAT IS „<Printer-record-format-name>..


Using Printer File in COBOL/400

.SPECIAL-NAMES Paragraph and ADVANCING Phrase


.When the mnemonic-name associated with the function-name 
CSP is specified in the ADVANCING phrase of a WRITE 
statement for a printer file, it has the same effect as specifying 
ADVANCING 0 LINES. 
.When the mnemonic-name associated with the function-name 
C01 is specified in the ADVANCING phrase of a WRITE 
statement for a printer file, it has the same effect as specifying 
ADVANCING PAGE
.The ADVANCING phrase cannot be specified in WRITE 
statements for Externally described printer files 
.Controlled by DDS Keywords SKIPA, SKIPB, SPACEA and 
SPACEB





Using Printer File in COBOL/400

.WRITE . . . ADVANCING Example


WRITE PRINT-RECORD FROM DETAIL-LINE

AFTER ADVANCING 2 LINES. 

.This will space two lines and then print


WRITE PRINT-RECORD FROM HEADING-2

BEFORE ADVANCING 3 LINES .

.This will print first and then advance the paper three lines


WRITE PRINT-RECORD FROM HEADING-1

AFTER ADVANCING PAGE.

.This will advance the paper to the top of a new page and then print a 
heading



Using Printer File in COBOL/400
.Editing Printed Output


Edit Symbols are used to make data fields clearer, neater and more 
readable. 

Editing Functions

.Printing of decimal points where decimal alignment is implied
.Suppression of Leading Zeros
.Printing Dollar sign and commas
.Printing of asterisks for check protection
.Printing of Plus or Minus signs
.Printing Debit and Credit symbol
.Printing Blanks and Zeros as Separators



Using Printer File in COBOL/400

.Editing Printed Output


Sending Field

Report-Item

Editing option

PIC

Contents

PIC

Edited Results

Printing Decimal 
point

9(2)V99

12^35

9(2).99

12.35

Leading Zero 
Suppression

9(3)

108

038

007

Z(3)

108

38

7

Dollar Sign and 
Comma

9(4)V99

3812^34

$9,999.99

$3,812.34

Printing 
asterisks (*)

9(5)V99

00234^56

$******.99

$***234.56

Printing Plus or 
Minus

S9(3)

9(3)

123-

123

-9(3)

-9(3)

-123

b123




Using Printer File in COBOL/400

.Editing Printed Output


Sending Field

Report-Item

Editing option

PIC

Contents

PIC

Edited 
Results

Printing Debit 
and Credit

S9(3)

123-

123-

123+

123+

9(3)CR

9(3)DB

9(3)CR

9(3)DB

123CR

123DB

123bb

123bb

If the field is unsigned or signed positive, CR or DB will not be printed

Printing 
SPACES or 
ZEROS

9(7)

9(3)

0897434

153

999BB99BB99

99900

089 74 34

15300




Using Printer File in COBOL/400

.Editing Printed Output


Editing may be performed in two ways:

.By moving a sending field to a report-item
.By performing an arithmetic operation and placing the result in a report-item
.PIC Clause of Report-Item determines what type of editing is to be performed



Using Printer File in COBOL/400
.De-Editing 


A report-item may be de-edited by moving it to a numeric field

01 RECORD-A.

05 AMOUNT-EDITEDPIC $ZZ,ZZZ.99.

.

.

01 RECORD-B.

05 AMOUNT-UNEDITEDPIC 9(5)V99.

.

.

MOVE AMOUNT-EDITED TO AMOUNT-UNEDITED.


Calling a Program


Calling a Program 

.CALLStatement


.Used in PROCEDURE DIVISION to CALL or reference 
independent subprograms
.Calling Program
.Main program that calls or references subprogram


.Called Program
.Subprogram that is linked and executed within main program
.Typical subprograms include:
.Edit routines
.Error control checks
.Standard calculations
.Summary and total printing







Calling a Program 
.CALLStatement


CALLliteral-1[USINGidentifier-1 …]
.Literal-1 is name of the called program. It is enclosed in quotes.
.USINGclause required if fields/data passed between Calling 
and called programs



Calling a Program 

.CallingandCalledprograms


Identification Division.

...

Procedure Division.

...

Call 'Sub1‘.

...

Call 'Sub2‘.

...

Identification Division.

Program-ID. Sub1.



Procedure Division. 

Exit Program.

Identification Division.

Program-ID. Sub2.



Procedure Division. 

Exit Program.

1

2

34 
Calling a Program 
.CalledProgramRequirements


.Must have a LINKAGE SECTIONin DATA DIVISION
.Follows FILE and WORKING-STORAGE SECTIONs
.Describes all items passed between main and subprogram
.Format same as WORKING-STORAGE Section
.Cannot contain VALUE clause


.PROCEDURE DIVISIONheader must include USINGclause
.Lists all parameters or fields defined in LINKAGE SECTION


.EXIT PROGRAM
.Last executed statement in called program
.Returns control back to calling program





Calling a Program 
.ParametersRules


.Parameters passed in sequence
.First parameter in CALL … USING passed to first parameter in 
PROCEDURE DIVISION USING clause and so on


.Number of parameters in both USING clause should be the 
same
.PIC clauses for corresponding parameters must be same
.Data-names of corresponding parameters may be same or 
different



Calling a Program 

.CALL...USINGExample


Calling Program

WORKING-STORAGE SECTION.

01 WORK-AREA.

05 WS-EMPIDPIC X(5)VALUE SPACES.

05 WS-SALARYPIC 9(5)V99VALUE ZEROS.

.

.

CALL„SUBPGM1. USINGWS-EMPID 

WS-SALARY.

.

.


Calling a Program 

.CALL...USINGExample


Called Program

.

WORKING-STORAGE SECTION.

.

.

LINKAGE SECTION.

01 LS-EMPIDPIC X(5).

01 LS-SALARYPIC 9(5)V99.

PROCEDURE DIVISION USINGLS-EMPID

LS-SALARY.

.

.

EXIT PROGRAM.


Calling a Program 
.CALL...USINGBYCONTENT


.The calling program is passing the content of the literal or 
identifiers.
.With CALL…BY CONTENT, the called program cannot change 
the values of literal or identifiersCALL„SUBPGM1. USINGBY CONTENTWS-EMPID 
WS-SALARY.
.The Values of WS-EMPID and WS-SALARY cannot be changed





Calling a Program 
.CANCELStatement


.Ensures that the next time the referenced subprogram is called, 
it will be entered in its initial state
.Closes all open files
.Operates only on the program specified 
CANCEL subprogram-name-1



Subfile Handling


Subfile Handling 

.WhatisSubfile?


.A subfile is a group of records that are read from or written to a 
display device
.Subfile can be specified in the DDS for a display file to allow you 
to handle multiple records of the same type on a display


.Record Formats
.Subfile Record Format (SFL)
.Defines the fields


.Subfile Control Record Format (SFTCTL)
.Defines the constant and fields displayed on the screen above the 
subfile record format
.Uses record-level keywords to control the subfile record format







Subfile Handling 

.SubfileKeywords


.SFLCTL
.Identifies the subfile control record format


.SFLSIZ
.Indicates number of records to be included in the subfile


.SFLPAG
.Indicates the number of records retrieved from the subfile and displayed on 
the screen at one time


.SFLDSP
.Indicates when to display the subfile. Controlled by an indicator


.SFLDSPCTL
.Controls the display of any fields or constants defined in the control-record 
format


.SFLCLR
.Indicates when the subfile should be cleared. Controlled by an indicator





.SELECTStatement


SELECTDISPLAY-FILE

ASSIGNTO WORKSTATION-EMPD2-SI

ORGANIZATIONIS TRANSACTION

ACCESSMODE IS DYNAMIC

RELATIVE KEYIS WS-SFL-RRN

FILE STATUSIS WS-FILE-STATUS

CONTROL-AREA IS WS-CONTROL.

.RELATIVE KEY clause must be specified when using Subfile
.Identifies a relative key data field




.Writes records to and Reads records from subfile based on the Relative Record 
number


Subfile Handling 
.SubfileProcess


.CLEAR SUBFILE
.Clear the previous records from subfile


.LOAD SUBFILE
.Read records from database file and write it into subfile


.DISPLAY SUBFILE
.If RRN > 0, display the subfile records in the screen




Subfile Handling 


.ClearSubfile


01 WS-INDICATORS-LIST.

05 IN34INDICATOR34PIC 1VALUE B.0..

1010-CLEAR-SUBFILE-RTN.

MOVE B.1. TO IN34.

WRITE DISPLAY-RECORD 

FORMAT IS „SFLCONTROL.

INDICATORS ARE WS-INDICATORS-LIST.

MOVE B.0. TO IN34.

MOVE ZERO TO WS-SFL-RRN.

Subfile Handling 
Subfile Control Record format specified in 
the DDS


.LoadSubfile


01 WORK-FIELDS.

05 ARE-THERE-MORE-RECORDS PIC X(3)VALUE „YES..

88 NO-MORE-RECORDS VALUE „NO..

05 WS-SFL-RRNPIC 9(4)VALUE ZERO.

.

1100-LOAD-SUBFILE-RTN.

MOVE „YES. TO ARE-THERE-MORE-RECORDS.

READ EMPLOYEE-FILE NEXT RECORD.

PERFORM 1200-READ-EMPLOYEE-RECORD-RTN

UNTIL NO-MORE-RECORDS.

1200-READ-EMPLOYEE-RECORD-RTN.

ADD 1 TO WS-SFL-RRN.

MOVE EMPID OF EMPLOYEE-RECORD TO EMPID OF SFLRECORD-O.

.

WRITE SUBFILEDISPLAY-RECORD

FORMAT IS „SFLRECORD..

READ EMPLOYEE-FILE NEXT RECORD

AT END

SET NO-MORE-RECORDS TO TRUE

END-READ.

Subfile Handling 

Subfile Record format specified in the DDS 
.DisplaySubfile


01 WS-INDICATORS-LIST.

05 IN31INDICATOR31PIC 1 VALUE B.0..

05 IN32INDICATOR32PIC 1 VALUE B.0..

05 IN33INDICATOR33PIC 1 VALUE B.0..

05 IN34INDICATOR34PIC 1 VALUE B.0..

01 WORK-FIELDS.

05 ARE-THERE-MORE-RECORDS PIC X(3)VALUE „YES..

88 NO-MORE-RECORDS VALUE „NO..

05 WS-SFL-RRNPIC 9(4)VALUE ZERO.

.

1300-DISPLAY-SUBFILE-RTN.

WRITE DISPLAY-RECORD

FORMAT IS „SFLFOOTER..

MOVE B.1. TO IN31.

MOVE B.1. TO IN32.

WRITE DISPLAY-RECORD

FORMAT IS „SFLCONTROL.

INDICATORS ARE WS-INDICATORS-LIST.

READ DISPLAY-FILE RECORD

FORMAT IS „SFLCONTROL.

Subfile Handling 


.UpdateSubfile


.

1300-DISPLAY-SUBFILE-RTN.

WRITE DISPLAY-RECORD

FORMAT IS „SFLFOOTER..

MOVE B.1. TO IN31.

MOVE B.1. TO IN32.

WRITE DISPLAY-RECORD

FORMAT IS „SFLCONTROL.

INDICATORS ARE WS-INDICATORS-LIST.

READ DISPLAY-FILE RECORD

FORMAT IS „SFLCONTROL.

**** If no valid Function key is pressed

MOVE „YES. TO ARE-THERE-MORE-RECORDS

READ SUBFILE DISPLAY-FILE NEXT MODIFIEDRECORD

FORMAT IS „SFLRECORD.

AT END 

NO-UPDATE-REQUIRES TO TRUE

NOT AT END

PERFORM 1500-UPDATE-RTN

UNTIL NO-MORE-RECORDS 

END-READ

Subfile Handling 


.UpdateSubfile


.

1500-UPDATE-RTN.

MOVE EMPID OF SFLRECORD-I TO EMPID OF EMPLOYEE-RECORD.

READ EMPLOYEE-FILE.

*** UPDATED VALUES ***

MOVE EMPSAL OF SFLRECORD-I TO EMPSAL OF EMPLOYEE-RECORD.

REWRITE EMPLOYEE-RECORD.

REWRITE SUBFILEDISPLAY-RECORD

FORMAT IS „SFLRECORD..

READ SUBFILEDISPLAY-FILE NEXT MODIFIEDRECORD

FORMAT IS „SFLRECORD.

AT END 

NO-MORE-RECORDS TO TRUE

END-READ.

Subfile Handling 


Arrays and Table Handling


Topics 
.Single-Level OCCURS Clauses
.Processing Data Stored in Array
.Using OCCURS Clause for Table Handling
.Use of SEARCH Statement
.Looking Up Table Data for Accumulating Totals
.SEARCH … VARYING Option for Processing Parallel Tables
.SEARCH ALL Statement
.Multiple-Level OCCURS Clause



Array and Table Handling 

.WhyOCCURSClausesUsed


.To indicate repeated occurrence of fields with same format
.Defines series of related fields with same format as an array or 
table



Array and Table Handling 

.UsesofOCCURSClause


.Defining series of input or output fields, each with same format
.Defining series of totals to which amounts added
.Defining a table to be accessed using contents of input field to 
'look up' required data



Array and Table Handling 

.DefiningSeriesofInputFields


.Suppose 72-character input record consists of 24 hourly 
temperature fields
.Each field is three positions long
.Fields represent temperature for given city at particular hour
.Coding record with 24 independent hourly fields is cumbersome01TEMP-REC.
05ONE-AMPIC S9(3).
05TWO-AMPIC S9(3).
...……
05MIDNIGHTPIC S9(3).



Array and Table Handling 
.DefiningSeriesofInputFields


.To obtain average temperature requires summing 24 fieldsCOMPUTE AVG-TEMP = (ONE-AM +
TWO-AM + … + MIDNIGHT) / 24



Array and Table Handling 

.DefiningFieldswithOCCURS


.Since all 24 fields have same PICTURE
–Can define entire 72-position area as array
–Array divided into 24 three-position fields, called elements01 TEMP-REC.
05 TEMPERATURE OCCURS 24 TIMES 
PIC S9(3).





Array and Table Handling 

.AccessingElementsinArray


.Identifier Temperature is array name
.Use array name along with a subscriptto access fields or 
elements within array
.Subscript indicates which of the 24 elements to accessStatementOutputDisplay Temperature (2) 2 AM valueDisplay Temperature (23) 11 PM value



Array and Table Handling 

.ValidSubscripts


.Valid values are 1 to number of elements in array
.For array Temperature valid subscripts are 1 to 24
.Invalid use of subscripts
–Display Temperature (0)
–Display Temperature (25)





Array and Table Handling 
.Subscripts


.May be integers or numeric fields with integer value
.If field Sub defined in Working-Storage:
05SUB PIC 99VALUE 5.
.To display 5 AM temperature:
Display Temperature (Sub)
.Using a data-name as a subscript enables its contents to be 
varied
.Each time the value of a data-name changes, Temperature 
(Sub) refers to a different element in the array
.Then a single routine can be used to process all elements in 
array



Array and Table Handling 

.Processing Elements in Array


Example: Find average daily temperature
.Use loop repeated 24 times
.Each time through loop add one temperature to array
.Vary contents of a subscript from 1 to 24 so that all 24 
temperatures are added
.Standard or in-line PERFORM… UNTIL or PERFORM… 
VARYING may be used



Array and Table Handling 

.In-line PERFORM UNTIL


MOVE 1 TO SUBMOVE ZEROS TO TOTAL-TEMPPERFORM UNTIL SUB > 24ADD TEMPERATURE (SUB) TO TOTAL-TEMPADD 1 TO SUBEND-PERFORMCOMPUTE AVG-TEMP = TOTAL-TEMP / 24 
Array and Table Handling 

.In-line PERFORM VARYING


MOVE ZEROS TO TOTAL-TEMPPERFORM VARYING SUBFROM 1 BY 1 UNTIL SUB > 24ADD TEMPERATURE (SUB) TO TOTAL-TEMPEND-PERFORMCOMPUTE AVG-TEMP = TOTAL-TEMP / 24 
Array and Table Handling 
.Relative Subscripting


.Integer literal or data-name used as subscript may be modified 
within parenthesesStatementOutputMove 3 To SubDisplay Temperature (Sub + 1) 4 AM valueDisplay Temperature (Sub -2) 1 AM value



Array and Table Handling 

.Debugging Tip


.Define subscript large enough to hold values to reference all 
elements
.Subscript for array of 100 elements should be Pic 9(3), not Pic 9(2)


.Define subscript large enough to store value one more than 
upper subscript limit
.Pic 99 needed to allow for number 10 to exit loop with condition 
Sub > 9 





Array and Table Handling 

Using OCCURS for Totals
.Define array to hold 12 monthly totalsWorking-Storage Section.
01TOTALS.
05 MO-TOT OCCURS 12 TIMESPIC 9(5)V99.



Array and Table Handling 

.Initialize Array of Totals


.Use VALUE clause (Value Zeros) after PIC clause in OCCURS 
level entry
.Three ways in Procedure Division1.INITIALIZE (Initialize Totals)
2.MOVE (Move Zeros To Totals)
3.Perform Varying Sub1From 1 By 1 Until Sub1 > 12Move Zeros to Mo-Tot (Sub1)
End-Perform



Array and Table Handling 
.Add Value to Array Totals


.Assume input record with transactions for same year
.Field Month-In determines Mo-Tot to which contents of input 
field Amt-In is to be added
.For example, if Month-In is 3, Amt-In should be added to third Mo-
Tot element


.For each record read in, if month valid, add amount 
to corresponding total200-CALC-RTN.
IF MONTH-IN >= 1 AND <= 12ADD AMT-IN TO MO-TOT (MONTH-IN)
ELSEPERFORM 400-ERR-RTNEND-IF



Array and Table Handling 

.Print Array of Totals


.Print array of totals after all input read
.Move each array entry to output area
.Write a linePERFORM VARYING SUB FROM 1 BY 1 
UNTIL SUB > 12MOVE MO-TOT (SUB) TO MO-TOT-OUTWRITE PR-REC FROM MO-TOT-LINEAFTER ADVANCING 2 LINESEND-PERFORM





Array and Table Handling 

.Elementary Items with OCCURS


.If item defined by OCCURS has PIC clause, it defines a series 
of elementary items01 TOTALS.
05 MO-TOT OCCURS 12 TIMES PIC 9(5)V99.
.Defines Totals as 84-byte array (12 x 7) of 12 elementary items 



Array and Table Handling 

.Group Items with OCCURS


.Identifier used with OCCURS may also be group item01 TAX-TABLE.
05 GROUP-X OCCURS 20 TIMES.
10 CITY PIC X(6).
10 TAX-RATEPIC V999.
.City and Tax-Rate each occur 20 times in group item Group-X.



Array and Table Handling 
.Initializing Elements


.Two ways to use VALUE clause to initialize all elements to zero1.01 ARRAY-1VALUE ZERO.
05TOTALS OCCURS 50 TIMES PIC 9(5).
2.01 ARRAY-1.05 TOTALS OCCURS 50 TIMES PIC 9(5) 
VALUE ZERO.



Array and Table Handling 

.Initializing Elements


.Can also initialize each element to different value01DAY-NAMESVALUE 'SUNMONTUEWEDTHUFRISAT'.
05 DAYS OCCURS 7 TIMES PIC X(3).
.Entries define 21-character array with 7 three-position fields -
Days(1) = SUN, Days(2) = MON, etc.



Array and Table Handling 

.Tables


.Table is list of stored fields 
.Stored same way as array but used for different purpose
.Used with table look-ups, a procedure to find specific entry in a 
table



Array and Table Handling 

.Data for Table


.Data often read in from separate file
.Stored in WORKING-STORAGE table
.Suppose file contains records with two fields, zip code and sales 
tax rate
.Read in records, storing each zip code and sales tax rate in 
element in table
.After data stored in table, read in input records from customer 
transaction file
.Look up a customer's zip code in table to find corresponding 
sales tax rate
.More efficient to store tax rates in table file than in each 
transaction record
.Minimizes data entry operations
.Easier to maintain or update in table file





Array and Table Handling 
.Table Look-Up Terms


.Table argument (zip code) is table entry field used to locate 
desired element
.Table function (sales tax rate) is table entry field to be used 
when match found
.Search argument (zip code in transaction record) is input field 
used to find a match



Array and Table Handling 

.Table Look-Up


Table entries in WORKING-STORAGETable ArgumentTable FunctionZip CodeSales Tax RateInput Record00123^0601234400456^075Zip Code10111^065(search 12344^080argument)25033^070…...
Rate for Zip 
of 12344 
Array and Table Handling 
.Looking Up Data in Table


.Compare search argument (zip code in transaction record) to 
each table argument (zip code in table) until match is found
.When table and search arguments match, use corresponding 
sales tax rate (table function) with same subscript as table's zip 
code to calculate sales tax



Array and Table Handling 
.Table Look-up with PERFORM


MOVE 0 TO WS-SALES-TAX

PERFORM VARYING X1 FROM 1 BY 1

UNTIL X1 > 1000

IF ZIP-IN = WS-ZIPCODE (X1)

COMPUTE WS-SALES-TAX ROUNDED = 
WS-TAX-RATE (X1) * 

UNIT-PRICE-IN * QTY-IN

END-IF

END-PERFORM


Array and Table Handling 
.SEARCH Statement


SEARCHidentifier-1[AT ENDimperative-statement-1]
WHENcondition-1imperative-statement-2 ...
CONTINUE[END-SEARCH]
.Use in place of PERFORM to search table



Array and Table Handling 
.SEARCH Statement Example


SET X1 TO 1

SEARCH TABLE-ENTRIES

AT END MOVE 0 TO WS-SALES-TAX

WHEN ZIP-IN = WS-ZIPCODE (X1)

COMPUTE WS-SALES-TAX ROUNDED = 

WS-TAX-RATE (X1) * 

UNIT-PRICE-IN * QTY-IN

END-SEARCH


Array and Table Handling 
.SEARCH Statement


.Identifier used after SEARCH is table name specified in 
OCCURS entry
.Condition compares search argument to table argument 
.WHEN clause indicates action to take when condition is met
.AT END clause specifies action to take if table searched but no 
match found



Array and Table Handling 
.INDEXED BY clause


.Special field called indexmust be used with SEARCH
.Similar to subscript but defined along with table as part of 
OCCURS05TABLE-ENTRIES OCCURS 1000 TIMESINDEXED BY X1.
.Compiler automatically supplies appropriate PICTURE clause 
for index



Array and Table Handling 
.Index with SEARCH


.Must initialize index before SEARCH
.SEARCH performs table look-up, automatically incrementing 
index
.Internally, computer can use faster method to access table 
entries with an index than with a subscript, even when SEARCH 
not used
.Both can have values from 1 to number of table elements



Array and Table Handling 
.Modifying Index


.PERFORM … VARYING can modify subscript or index
.SET is only other statement that can modify indexTOSETindex-name-1 UP BYinteger-1DOWN BY



Array and Table Handling 
.SET Statement Examples


.SET options used to initialize, increment or decrement index 
value
.Assume X1 = 3 before each statementStatementValue of X1 after SETSet X1 To 11Set X1 Up By 25Set X1 Down By 12



Array and Table Handling 
.Subscripts vs Indexes


.Subscript
.Represents occurrence of array or table element


.Index
.Represents value used internally to actually access table entry (a 
displacement from first address in array or table)


.Subscript
.Defined in separate WORKING-STORAGE entry
.May be used any where field with its PICTURE is allowed


.Index
.Defined along with OCCURS
.May be used only with table for which it was defined





Array and Table Handling 
.Subscripts vs Indexes


.Subscript
.Value may be changed using PERFORM … VARYING
.Also by MOVE or arithmetic statements


.Index
.Value may be changed using PERFORM … VARYING
.SET only other statement to modify index





Array and Table Handling 
.Serial Search


Each entry (usually starting with first) checked in order until 
.Condition is met
.Table completely searchedBest used when
.Entries not in order by table argument value (not in numerical or 
alphabetical order)
.Entries can be organized so first values are ones searched for 
most frequently, minimizing search time



Array and Table Handling 
.Binary Search


.Most efficient type of look-up when table entries in sequence by 
some table field
.On average, takes fewer comparisons to find match than serial 
search
.Called binary search because each comparison eliminates half 
of entries under consideration
.Assume a table contains 50 customer numbers in ascending 
sequence
.Search table to find match for customer number 5000 stored in 
input field Cust-No-In



Array and Table Handling 
.Binary Search Example


.Assume a table contains 50 customer numbers in ascending 
sequence
.Search table to find match for customer number 5000 stored in 
input field Cust-No-In



Array and Table Handling 
.Binary Search Example


ComparisonEntry #T-Customer-No1.01002.0200…...
1st25.4300…...
3rd31.4890…...
4th34.5000…...
2nd37.5310 
Array and Table Handling 
.Binary Search Method


.Compare Cust-No-In to middle table argument for T-Customer-
In (25th element)
.Cust-No-In > T-Customer-No (25) or 5000 > 4300
.First half of table eliminated from search since entries are in 
ascending order


.Serial search would require 34 comparisons in this example
.Binary search requires only four
.Use binary search for large table (50 or more entries)
.Table entries must be arranged in sequence by some table field



Array and Table Handling 
.Binary Search Statement


SEARCHALLidentifier-1[AT ENDimperative-statement-1]
WHENdata-name-1 = identifier-2literal-1condition-1arithmetic-expression-1imperative-statement-2CONTINUE[END-SEARCH] 
Array and Table Handling 
.SEARCH ALL Limitations


.Condition in WHEN can test only for equality between table and 
search argument
.Condition following WHEN may be compound
.Only ANDs permitted, not ORs
.Each relational test can test only for equality


.Only one WHEN clause can be used
.VARYING option may not be used
.Table argument and its index must appear to left of equal sign
.Valid: 




When T-Customer-No (X1) = Cust-No-In

.Invalid:




When Cust-No-In = T-Customer-No (X1)


Array and Table Handling 
.Key Field


.Must include clause to indicate which table entry serves as key 
field
.Must specify whether KEY is
.ASCENDING KEY -entries in sequence, increasing in value
.DESCENDING KEY -entries in sequence, decreasing in value





Array and Table Handling 
.Multiple-Level OCCURS


.Up to seven levels of OCCURS permitted in COBOL
.For example, define an array to store hourly temperature 
readings for each day during a given week
.Need two-dimensional array with 7 rows, each with 24 columns


.Define array as follows:
01TEMPERATURE-ARRAY.
05DAY-IN-WEEK OCCURS 7 TIMES.
10HOUR OCCURS 24 TIMES.
15 TEMPPIC S9(3).
.For each Day-In-Week there are 24 Hour figures, each 
consisting of a Temp three integers long



Array and Table Handling 
.Double-Level Subscripts


.To access temperatures, use data-name on lowest OCCURS 
level or any data-name subordinate to it
.Either Temp or Hour could be used


.Since Temp defined with two OCCURS, two subscripts must be 
used to access each hourly temperature
.For example, Temp (3, 5) refers to the temperature for the third 
day, fifth hour



Array and Table Handling 
.Table with Subscripts


Temperature Array

Hour

1 AM

2 AM

3 AM

4 AM



12 Mid

Day-In-Week

Day 1 (Sun)

(1,1)

(1,2)

(1,3)

(1,4)



(1,24)

Day 2 (Mon)

(2,1)

(2,2)

(2,3)

(2,4)



(2,24)

Day 3 (Tue)

(3,1)

(3,2)

(3,3)

(3,4)



(3,24)

Day 4 (Wed)

(4,1)

(4,2)

(4,3)

(4,4)



(4,24)















Day 7 (Sat)

(7,1)

(7,2)

(7,3)

(7,4)



(7,24)




Array and Table Handling 

.Accessing Double-Level Array


.Find average temperature for entire week
.Add all array entries and divide by 168 (7 x 24)
.Use nested PERFORMs
.First PERFORM varies major (row) subscript from 1 to 7
.Second PERFORM varies minor (column) subscript from 1 to 24





Array and Table Handling 
.Accessing Double-Level Array


MOVE 0 TO TOTALPERFORM VARYING DAY-SUB FROM 1 BY 1 
UNTIL DAY-SUB > 7PERFORM VARYING HOUR-SUB FROM 1 BY 1 
UNTIL HOUR-SUB > 24ADD TEMP (DAY-SUB, HOUR-SUB) 
TO TOTALEND-PERFORMEND-PERFORMCOMPUTE WEEKLY-AVERAGE = TOTAL / 168 
Array and Table Handling 

.PERFORM … VARYING … AFTER


.Use in place of multiple nested PERFORM … VARYING 
statements
.VARYING clause varies major subscript
.AFTER clause varies minor subscript
.Requires procedure name after PERFORM



Array and Table Handling 

.PERFORM … VARYING … AFTER


MOVE 0 TO TOTAL

PERFORM 700-LOOP1 

VARYING DAY-SUB FROM 1 BY 1 

UNTIL DAY-SUB > 7

AFTER HOUR-SUB FROM 1 BY 1 

UNTIL HOUR-SUB > 24

COMPUTE WEEKLY-AVERAGE = TOTAL / 168.

700-LOOP1.

ADD TEMP (DAY-SUB, HOUR-SUB) 

TO TOTAL.


Array and Table Handling 

.PERFORM … VARYING … AFTER


.Sequence of values for subscripts is (1, 1), (1, 2) … (1, 24), (2, 
1), (2, 2) … (2, 24) … (7, 1) ... (7, 24)
.Day-Sub initialized to 1 and Hour-Sub varied from 1 to 24
.Then Day-Sub incremented to 2 and Hour-Sub varied from 1 to 
24 and so on



Array and Table Handling 
.Chapter Summary


.OCCURS clause used to specify repeated occurrence of items 
with same format
.Use in 02-49 level entries
.May use with elementary or group item
.COBOL permits seven levels of OCCURS


.OCCURS defines
.Array: area used for storing data or totals
.Table: set of fields used in table look-up


.SEARCH statement used for table handling
.Identifier used with SEARCH is data-name used on OCCURS level
.AT END clause specifies action if table searched but condition not 
met





Array and Table Handling 

.Chapter Summary


.WHEN clause indicates what to do when condition met


.SEARCH statement
.Index defined along with OCCURS and used by SEARCH
.Use SET or PERFORM … VARYING to change value of index
.SET index to 1 before using SEARCH


.SEARCH ALL statement
.Used to perform binary search
.Can test only an equal condition
.Can use compound condition with ANDs
.Only one WHEN clause can be used
.Define index to use in searching table
.Include ASCENDING or DESCENDING KEY clause in table 
definition





Array and Table Handling 

.Chapter Summary


.Multiple-Level OCCURS
.Used with array or table
.Lowest-level OCCURS data-name or item subordinate to it used to 
access table entry
.INDEXED BY must be included on all OCURRS levels if SEARCH 
used
.Identifier used with SEARCH typically one on lowest OCCURS 
level
.Only index on same level incremented





Sorting and Merging


Topics
.The SORT feature
.Processing data before and/or after sorting
.The MERGE statement



Sorting and Merging
.SORTStatement


.Common procedure for arranging records in specific order
.Then sequential batch processing performed
.Two techniques for sorting
.Use sort utility separate from COBOL program
.Use COBOL's SORT verb in program





Sorting and Merging
.SORTStatement


.A simplified format for the SORT statement in COBOL is as 
follows:
SORT file-name-1{ON {DESCENDING}{ASCENDING} KEY data-name-1 . .}
USINGfile-name-2GIVINGfile-name-3



Sorting and Merging
.ASCENDING,DESCENDINGKey


.To specify sequence for key field
.ASCENDING: From lowest to highest
.DESCENDING: From highest to lowest


.Sort key fields may be numeric or nonnumeric
.Alphanumeric fields sorted according to collating sequence 
(ASCII or EBCDIC) used by computer 



Sorting and Merging
.MultipleSortKeys


.Can sequence records with more than one key field
.Sort payroll file in ascending alphabetic sequence by name, 
within each level, for each office
.Office number -major sort field
.Level number -intermediate sort field
.Name -minor sort field





Sorting and Merging
.MultipleSortKeys


.For Office 1, desired sequence isOffice-NoLevel-NoName11ADAMS, J. R.
11BROCK, P. T.
11LEE, S.
12ARTHUR, Q. C.
12SHAH, J.
13RAMIREZ, A. P.



Sorting and Merging
.SORTStatement


.Sorts records into ascending name sequence within level within 
office


SORT SORT-FILE

ON ASCENDING KEY OFFICE-NO

ON ASCENDING KEY LEVEL-NO

ON ASCENDING KEY NAME

USING PAYROLL-FILE-IN

GIVING SORT-PAYROLL-FILE-OUT


Sorting and Merging
.MultipleSortKeys


.Choose either ASCENDING or DESCENDING sequence for 
each key
.If all key fields to be sorted in same sequence, can condense 
codingSORT SORT-FILEON ASCENDING KEY MAJOR-KEYINTERMEDIATE-KEYMINOR-KEY...



Sorting and Merging
.DuplicateKeyValues


.Assume records to be sorted in descending order by salary 
.If both 9th and 24th records in input file have salary of 30000, 
which appears first in sort file?
.Can specify that records with same value for key field be placed 
in sort file in same order that they appear in original input file



Sorting and Merging
.DuplicateKeyExample


SORT SORT-FILEON DESCENDING KEY SRT-SALARYWITH DUPLICATES IN ORDERUSING UNSORTED-FILE-INGIVING SORTED-FILE-OUT
.DUPLICATES clause ensures that 9th record appears before 
24th in Sort-File if both have same Salary value 



Sorting and Merging
.FilesusedinSORT


.Input file: File of unsorted input records
.Work or sort file: File used to store records temporarily during 
sorting process
.Output file: File of sorted output records 
.All defined using standard SELECT … ASSIGN entries
.All must have same record format
.All are opened and closed automatically by SORT



Sorting and Merging
.FilesusedinSORT


.Input and output file described with FD entries
.Sort work file 
.Described with SD entry (sort file descriptor)
.Temporary file used only during sorting but not saved
.Sort key fields mustbe described as part of sort record format





Sorting and Merging
.SampleFILESECTION


DATA DIVISION.
FILE SECTION.
FD UNSORTED-FILE-IN.
01UNSORTED-REC-IN.
05NAME-INPIC X(20).
05SALARY-INPIC 9(6).
SDSORT-FILE.
01SORT-REC.
05SRT-NAMEPIC X(20).
05SRT-SALARYPIC 9(6).
FD SORTED-FILE-OUT.
01SORTED-REC-OUT.
05NAME-OUTPIC X(20).
05SALARY-OUTPIC 9(6). 
Sorting and Merging
.OperationperformedbySORT


.Opens all three files
.Moves all records from Unsorted-File-In to Sort-File
.Sorts records in Sort-File in descending sequence by Srt-Salary
.Moves all records from Sort-File to Unsorted-File-Out
.Closes all three files



Sorting and Merging
.INPUTPROCEDURE


.Use in place of USING clause to process data from input file 
priorto sorting
.Assume only records with Salary-In < 75000 need to be sorted
.Use Input Procedure to process and select desired records 
before sorting



Sorting and Merging
.SORTwithINPUTPROCEDURE


SORT SORT-FILEON DESCENDING KEY SRT-SALARYINPUT PROCEDURE SELECT-RECORDSGIVING SORTED-FILE-OUT
.Select-Records is name of paragraph written by programmer to 
process records before sorting



Sorting and Merging
.INPUTPROCEDURE


Select-Records paragraph must

.Open input file (Unsorted-File-In)
.Perform processing of input records until there is no more data
.Close input file



Sorting and Merging
.ProcessingInputRecords


.For each input record, if Salary-In < 75000
.Move input data to sort record
.RELEASE record to sort file


.When INPUT PROCEDURE paragraph is completed, control 
returns to SORT
.All records released to sort file are sorted



Sorting and Merging
.RELEASEStatement


RELEASEsort-record-name-1

[FROMidentifier-1]

.To write a record to the sort file
.Like WRITE but used to output sort records



Sorting and Merging
.INPUTPROCEDURE


.May be used to
.Validate data in input records
.Process only records that meet certain criteria
.Eliminate records with blank fields
.Remove unneeded fields from input records
.Count input records





Sorting and Merging
.OUTPUTPROCEDURE


.With GIVING option, records in sort file automatically written to 
output file after sorting
.Use OUTPUT PROCEDURE to process sorted records prior to, 
or instead of, placing them in output file



Sorting and Merging
.SORTStatementFormat


SORTfile-name-1ONASCENDINGKEY data-name-1 … …
DESCENDINGINPUTPROCEDUREIS procedure-name-1USINGfile-name-2 …
OUTPUTPROCEDUREIS procedure-name-3GIVINGfile-name-3 … 
Sorting and Merging
.SORTProcedures


.If INPUT PROCEDURE used
.SORT transfers control to paragraph or section named in INPUT 
PROCEDURE
.When complete, sort file is sorted
.Records RELEASEd to sort file


.If OUTPUT PROCEDURE used
.SORT transfers control to paragraph or section named in OUTPUT 
PROCEDURE
.Processes all sorted records in sort file and handles transfer of 
records to output file
.Records RETURNed from sort file





Sorting and Merging
.RETURNStatement


RETURNsort-file-name-1AT ENDimperative statement-1[ NOTAT ENDimperative statement-2]
[END-RETURN]
.To retrieve records from the sort file
.Similar to READ



Sorting and Merging
.OUTPUTPROCEDURESteps


Paragraph (or section) must

.Open output file
.Perform paragraph to RETURN and process records from sort 
file until there is no more data
.Close output file
.When OUTPUT PROCEDURE finished, control returns to SORT



Sorting and Merging
.ProcessingSortedRecords


After records sorted but before they are created as output

.Perform any operations on sort records
.MOVE sort record to output area
.WRITE each sort record to output file



Sorting and Merging
.SORTProcedures


.Both INPUT and OUTPUT PROCEDUREs can be used in same 
program
.If used, programmer must open/close the input or output file
.SD (sort) file and files specified with USING or GIVING are 
automatically opened and closed



Sorting and Merging
.WhentousePROCEDUREs


.More efficient to use INPUT PROCEDURE if many records in 
input file can be eliminated before sort
.Use OUTPUT PROCEDURE if records require further 
processing after sort 
.Must use procedure if input or output file and sorted file have 
different-sized fields or fields in different order



Sorting and Merging
.SORTOptionsReview


Option:USINGGIVINGResult:
.File is sorted
.No special handling



Sorting and Merging
.SORTOptionsReview


Option:INPUT PROCEDUREGIVINGResult:
.Processes unsorted input records before they are sorted
.Write records to sort file with RELEASE
.After INPUT PROCEDURE completed, records are sorted



Sorting and Merging
.SORTOptionsReview


Option:USINGOUTPUT PROCEDUREResult:
.Processes records afterthey have been sorted but before they 
are written to output file
.Read records from sort file with RETURN



Sorting and Merging
.SORTOptionsReview


Option:INPUT PROCEDUREOUTPUT PROCEDUREResult:
.Processes data both before and after it is sorted



Sorting and Merging
.MERGEStatement


.To combine two or more files into one
.Files to be merged must each be in sequence by key field
.Format similar to SORT, rules for clauses are same



Sorting and Merging
.MERGEStatement


MERGEfile-name-1ON ASCENDINGKEY data-name-1 … …
DESCENDINGUSINGfile-name-2 file-name-3 …
OUTPUTPROCEDUREIS procedure-name-1GIVINGfile-name-4 …
.To combine two or more files into one



Sorting and Merging
.MERGEStatement


.File-name-1 is work file designated as an SD
.Keys specified are defined within SD
.Data-name-1 is major key, may be followed by intermediate and 
minor keys
.USING clause names file to be merged
.At least two must be included





Sorting and Merging
.MERGEStatement


.Records may be processed after merging with OUTPUT 
PROCEDURE, but not before
.Automatically handles opening, closing, and input/output 
associated with files



Sorting and Merging
.MERGEStatementExample


.Suppose two separate files of employees are to be combined 
into one
.Both input files and the resulting output file contain 80 
characters with an Emp-No in the first nine positions
.File definitions and MERGE instruction follow



Sorting and Merging
.MERGEStatementExample


DATA DIVISION.

FILE SECTION.

FDEMP-FILE-1.

01EMP-REC-1PIC X(80).

FDEMP-FILE-2.

01EMP-REC-2PIC X(80).

SDMERGE-FILE.

01MERGE-REC.

05 MRG-EMP-NOPIC X(9).

05 REST-OF-RECPIC X(71).

FDOUT-EMP-FILE.

01OUT-EMP-RECPIC X(80).


Sorting and Merging
.MERGEStatementExample


PROCEDURE DIVISION.
100-MAIN-MODULE.
MERGE MERGE-FILEON ASCENDING KEY MRG-EMP-NOUSING EMP-FILE-1, EMP-FILE-2GIVING OUT-EMP-FILESTOP RUN. 
Sorting and Merging
.ChapterSummary


.SORT used for sorting records in either ascending or 
descending order
.SORT uses work or sort file described with an SD
.Key fields to be sorted are data-names defined within SD or sort 
file
.Files may be sorted using more than one key field
.Routines separate from SORT may be used to 
.Process unsorted file prior to SORT
.Process sorted file after SORT





Sorting and Merging
.ChapterSummary


.Procedures that are part of SORT permit processing
.Just before sort performed (INPUT PROCEDURE)
.After sort finished but before writing records to sorted file (OUTPUT 
PROCEDURE)


.RELEASE statement used in INPUT PROCEDURE to make 
input records available for sorting
.RETURN statement used in OUTPUT PROCEDURE to read 
records from sort file
.MERGE statement used to merge two or more files into one



References
.Programming in COBOL/400by James Cooper, Nancy Stern and Robert A. Stern


.IBM Redbooks
.COBOL/400 Reference
.COBOL/400 Programmer.s Guide


.IBM COBOL/400 Language Help URLhttp://publib.boulder.ibm.com/infocenter/iadthelp/v7r0/index.jsp?topic=/com.ibm.etools.iseries.langref.doc/evfeb4ls02.htm



Thank You




















0 comments:

Post a Comment