Saturday, 30 August 2014

COBOL Evaluate Statement | EVALUATE statement in COBOL [COBOL Evaluate Examples].


Evaluate statement

COBOL Evaluate statement.


Welcome back to today's session on "COBOL Evaluate Statement". In this session, you'll learn the basics of Evaluate statement in COBOL. Also, you'll go through a couple of examples to re-enforce your COBOL Evaluate knowledge. Let's get started with an introduction to COBOL Evaluate Statement. 

COBOL Evaluate Statement - Agenda. 

  • Introduction to COBOL Evaluate Statement.
  • COBOL Evaluate Statement Syntax.
  • COBOL Evaluate Example. 
  • Different Forms Of Evaluate Statement.
  • Evaluate in COBOL - Youtube.
  • Conclusion.

Introduction to COBOL Evaluate Statement.

COBOL Evaluate statement is similar to SWITCH, CASE statement of any other programming language for example VB 6.0 macro programming language. In this Evaluate in COBOL Tutorial, I would explain the usage of the COBOL EVALUATE statement with syntax and example.

Evaluate statement in COBOL is used to implement the case structure. It tests for series of values. 
The Evaluate statement became available with COBOL-85. It has a complicated syntax that lets you use this statement for a variety of purposes. No matter how you code it, though, it always has one entry point and one exit point, so it is a valid structure for structured programming.

COBOL EVALUATE is better than Nested-ifs in terms of performance and it improves the readability of the COBOL program. COBOL Evaluate statement can be used in different forms for example: Evaluate True in COBOL, Evaluate Thru in COBOL, Evaluate WHEN in COBOL, etc.

COBOL Evaluate Statement Syntax.  

Evaluate statement in COBOL is pretty simple and easy to understand. In fact, the COBOL Evaluate statement is more flexible as compare to the COBOL Ifs statement. Here is the simple format of COBOL Evaluate Syntax.

* The syntax of the Evaluate statement as an If-statement alternative.

EVALUATE TRUE
    WHEN Condition-1
         Statement ... 
    WHEN OTHER 
         Statement- ... 
END-EVALUATE. 

 
Evaluate statement in COBOL, COBOL Evaluate

COBOL evaluate statement Syntax

Each time an Evaluate statement is executed, the conditions in the When clauses are tested in sequence, starting with the first When clause. When a condition in a When Clause is true, the statements in that clause are executed and the Evaluate statement ends without evaluating the other conditions.

#1 COBOL Evaluate Statement Example.

The following COBOL Evaluate statement example reveals how you can code multiple conditions by using the when clause in the COBOL Evaluate statement (i.e. COBOL evaluate true).  
                                                         
EVALUATE                     EVALUATE SQLCODE ALSO FILE-STATUS
   WHEN A=B AND C=D             WHEN 100 ALSO ‘00’
        imperative stmt              imperative stmt
   WHEN (D+X)/Y = 4             WHEN -305 ALSO ‘32’
        imperative stmt              imperative stmt
   WHEN OTHER                   WHEN OTHER
        imperative stmt              imperative stmt
END-EVALUATE                 END-EVALUATE 

#2 COBOL Evaluate Statement Example.




COBOL Evaluate statement Example


The Evaluate statement can be used to implement a case structure for one or more fields. When you work with more than one field, you use the word ALSO before each additional field. Then, in the When clauses, you use the word ALSO before each additional value.

Different Forms Of Evaluate Statement.

The COBOL Evaluate Statement has formats to suits the need of programmers. You can use the EVALUATE statement in COBOL to combine multiple conditions instead of nested ifs. Following are the different types of COBOL Evaluate.

  • COBOL Evaluate WHEN TRUE.
  • COBOL Evaluate WHEN TRUE ALSO TRUE.
  • COBOL Evaluate using Thru phrase.
  • COBOL Evaluate using multiple WHEN.
Do check out the "Different Forms Of Evaluate Statement In COBOL" post for a detailed explanation of COBOL Evaluate Statement types. 

COBOL EVALUATE Statement - Youtube.



Conclusion. 

Finally, this marks an end to the COBOL Evaluate Statement. COBOL Evaluate statement goes hand in hand and you got an alternative to COBOL Ifs statements. Evaluate statement in COBOL is better than IFs statement in terms of performance. Do check out COBOL LEVEL 88 Condition.


►Subscribe to Topictrick & Don't forget to press THE BELL ICON to never miss any updates. Also, Please visit mention the link below to stay connected with Topictrick and the Mainframe forum on - 

► Youtube
► Facebook 
► Reddit

Thank you for your support. 
Mainframe Forum™
Share COBOL
COBOL Evaluate Statement.

Thursday, 14 August 2014

COBOL PERFORM Statement: Inline, Out-of-Line, TIMES, UNTIL, and VARYING

COBOL PERFORM statement diagram showing BASIC PERFORM, PERFORM TIMES, PERFORM UNTIL, and PERFORM VARYING

A COBOL PERFORM statement either runs named paragraph logic and returns, or runs inline statements between PERFORM and END-PERFORM. That one verb is behind many batch loops, validation checks, table scans, and small reusable routines in production COBOL programs.

Pick the form that matches the loop.

What does PERFORM do in COBOL?

PERFORM transfers control to one or more statements and then returns control to the next executable statement. In older paragraph-style COBOL, that usually means PERFORM 2000-VALIDATE-CUSTOMER. In newer structured code, it often means inline logic ended by END-PERFORM.

This page is the overview. For deep loop-condition detail, use the separate COBOL PERFORM UNTIL guide. For counter-style table loops, use the PERFORM VARYING guide.

Inline PERFORM vs out-of-line PERFORM

An inline PERFORM keeps the statements directly in the current flow. It must end with END-PERFORM. An out-of-line PERFORM names a paragraph or section, branches to it, and returns when that performed range finishes.

Type How it is coded Good fit
Inline PERFORM PERFORM ... END-PERFORM Short logic that is easier to read in place
Out-of-line PERFORM PERFORM paragraph-name Reusable logic or longer processing steps

Basic PERFORM example

A basic PERFORM runs the named paragraph once. This is common in old batch programs where each paragraph has a single job: initialize, read, validate, calculate, write, and close.

PROCEDURE DIVISION.
PERFORM 1000-INITIALIZE
PERFORM 2000-PROCESS-FILE
PERFORM 9000-CLOSE-FILES
GOBACK.
1000-INITIALIZE.
OPEN INPUT INFILE
OUTPUT OUTFILE.

Keep out-of-line paragraphs outside accidental fall-through paths. A paragraph that sits directly after the main flow can run once by PERFORM and again by ordinary sequential flow if the program is structured badly.

Inline PERFORM example

Inline PERFORM is clean for small checks because the reader does not need to jump to another paragraph. It also makes scope clear when paired with END-PERFORM.

PERFORM
IF WS-AMOUNT > ZERO
ADD WS-AMOUNT TO WS-TOTAL
ELSE
ADD 1 TO WS-ERROR-COUNT
END-IF
END-PERFORM

Use explicit scope terminators such as END-IF inside inline logic. That helps avoid bugs when another condition or loop is added later.

PERFORM TIMES example

PERFORM TIMES runs logic a fixed number of times. IBM documents that if the count is zero or negative when the statement starts, control passes to the statement after the PERFORM.

PERFORM 5 TIMES
DISPLAY "RETRYING FILE OPEN"
END-PERFORM

This form fits retry loops, small counters, test data generation, and repeatable validation. If the loop needs to stop based on a condition, use PERFORM UNTIL instead.

PERFORM UNTIL example

PERFORM UNTIL repeats while a condition is false, then stops when the condition becomes true. If neither TEST BEFORE nor TEST AFTER is specified, COBOL assumes TEST BEFORE.

PERFORM UNTIL END-OF-FILE
READ INFILE
AT END
SET END-OF-FILE TO TRUE
NOT AT END
PERFORM 3000-PROCESS-RECORD
END-READ
END-PERFORM

For file processing, always make the loop exit visible. A missing AT END action or a flag that never changes can create an endless loop in a batch job.

PERFORM VARYING example

PERFORM VARYING changes a counter or index each time through the loop. It is common with COBOL tables, especially when checking each occurrence of an array-like structure.

PERFORM VARYING WS-SUB FROM 1 BY 1
UNTIL WS-SUB > WS-MAX-ITEMS
IF ITEM-CODE(WS-SUB) = SPACES
ADD 1 TO WS-MISSING-COUNT
END-IF
END-PERFORM

Check the starting value, step value, and stop condition together. If WS-SUB starts at 1 and increases by 1, the condition should eventually become true.

PERFORM THRU warning

PERFORM paragraph-1 THRU paragraph-2 runs a range of paragraphs. It appears in many older systems, but it can be harder to maintain because adding a paragraph inside the range changes what the PERFORM runs. Prefer a single performed paragraph that calls smaller paragraphs when the codebase allows it.

Common mistakes

Recursive PERFORM

A performed paragraph must not cause itself to be performed. IBM warns that recursive PERFORM can produce unpredictable results. In plain terms, do not let 1000-MAIN perform 1000-MAIN again.

Mixing inline and out-of-line syntax

If the PERFORM names a paragraph, do not also put inline imperative statements and END-PERFORM on the same statement. Pick one style for that statement.

Hiding the loop exit

Every loop should show how it ends. For file loops, the AT END path should set a flag. For counter loops, the counter must move toward the end condition.

Related Mainframe Forum guides

Use this page as the PERFORM overview, then read COBOL Basic PERFORM, COBOL PERFORM TIMES, COBOL PERFORM UNTIL, and COBOL PERFORM VARYING. For related control logic, see COBOL IF Statement and COBOL EVALUATE Statement.

External references

IBM documents the formal rules in the Enterprise COBOL PERFORM statement, choosing inline or out-of-line PERFORM, and PERFORM TIMES pages.

FAQ

What is PERFORM in COBOL?

PERFORM runs inline statements or named procedure logic, then returns control to the next executable statement after the performed work finishes.

What is the difference between inline and out-of-line PERFORM?

Inline PERFORM keeps the logic in place and ends with END-PERFORM. Out-of-line PERFORM names a paragraph or section and branches to that procedure.

When should I use PERFORM TIMES?

Use PERFORM TIMES when the number of repeats is known before the loop starts, such as five retry attempts or ten test records.

When should I use PERFORM VARYING?

Use PERFORM VARYING when a counter or index must change on each pass, especially when processing a COBOL table.

COBOL SUBTRACT Statement: FROM, GIVING, and Size Error

A payroll program may read gross pay, then subtract tax, insurance, and loan recovery before writing net pay. In COBOL, the SUBTRACT statement handles that pattern directly. The important choice is whether the original amount should be changed, or whether the result should be written to a separate field with GIVING.

COBOL SUBTRACT statement diagram showing SUBTRACT amount, FROM base value, GIVING result, and ON SIZE ERROR
Use GIVING to keep the original value.

What is the COBOL SUBTRACT statement?

The SUBTRACT statement subtracts one numeric item, or the sum of several numeric items, from another numeric item and stores the result. IBM documents three main forms: basic SUBTRACT ... FROM, SUBTRACT ... FROM ... GIVING, and SUBTRACT CORRESPONDING.

The statement is easy to read when the business rule is a simple reduction. For a longer formula, COMPUTE may be clearer because the full expression appears on one side of the equals sign.

Basic SUBTRACT FROM format

Use the basic form when the value after FROM should be reduced in place. The receiving field is changed immediately.

SUBTRACT amount-1 [amount-2 ...] FROM result-field
    [ROUNDED]
    [ON SIZE ERROR imperative-statement]
END-SUBTRACT

Example: reduce a counter

01 WS-RETRY-COUNT        PIC 9(02) VALUE 03.

SUBTRACT 1 FROM WS-RETRY-COUNT
END-SUBTRACT.

After the statement runs, WS-RETRY-COUNT contains 02. This form is common in loops, retry logic, and balance calculations where the field itself should hold the new value.

SUBTRACT FROM GIVING format

Use GIVING when the source value must remain unchanged. COBOL subtracts the amount before FROM from the value after FROM, then places the answer in the field after GIVING.

SUBTRACT amount-1 [amount-2 ...]
    FROM source-value
    GIVING result-field
    [ROUNDED]
    [ON SIZE ERROR imperative-statement]
END-SUBTRACT

Example: calculate net pay

01 WS-GROSS-PAY          PIC S9(7)V99 COMP-3.
01 WS-TAX-AMOUNT         PIC S9(5)V99 COMP-3.
01 WS-INSURANCE-AMOUNT   PIC S9(5)V99 COMP-3.
01 WS-NET-PAY            PIC S9(7)V99 COMP-3.

SUBTRACT WS-TAX-AMOUNT WS-INSURANCE-AMOUNT
    FROM WS-GROSS-PAY
    GIVING WS-NET-PAY
END-SUBTRACT.

If gross pay is 2500.00, tax is 420.00, and insurance is 80.00, the result is 2000.00. WS-GROSS-PAY is still 2500.00 because the statement used GIVING.

SUBTRACT CORRESPONDING format

SUBTRACT CORRESPONDING, often written as SUBTRACT CORR, works with group items. COBOL matches elementary items by name and subtracts matching numeric fields. This can be useful, but many teams avoid it in business code because the result depends on matching data names inside both groups.

01 WS-OLD-TOTALS.
   05 WS-COUNT            PIC 9(05).
   05 WS-AMOUNT           PIC S9(7)V99 COMP-3.

01 WS-ADJUSTMENT-TOTALS.
   05 WS-COUNT            PIC 9(05).
   05 WS-AMOUNT           PIC S9(7)V99 COMP-3.

SUBTRACT CORRESPONDING WS-ADJUSTMENT-TOTALS
    FROM WS-OLD-TOTALS
END-SUBTRACT.

Review group layouts carefully before using this form. A field name change, copybook change, or added elementary item can change what gets subtracted.

ROUNDED and ON SIZE ERROR

Add ROUNDED when the receiving field has fewer decimal places than the calculated result and the business rule expects rounding. IBM notes that rounding is done before size-error checking.

01 WS-DISCOUNT            PIC S9(5)V999 COMP-3.
01 WS-INVOICE-AMOUNT      PIC S9(7)V99  COMP-3.
01 WS-AFTER-DISCOUNT      PIC S9(7)V99  COMP-3.
01 WS-CALC-STATUS         PIC X(20).

SUBTRACT WS-DISCOUNT
    FROM WS-INVOICE-AMOUNT
    GIVING WS-AFTER-DISCOUNT ROUNDED
    ON SIZE ERROR
       MOVE 'SUBTRACT OVERFLOW' TO WS-CALC-STATUS
    NOT ON SIZE ERROR
       MOVE 'SUBTRACT OK' TO WS-CALC-STATUS
END-SUBTRACT.

A size error can occur when the result cannot fit in the receiving field after decimal alignment. When ON SIZE ERROR is coded and a size error occurs, the affected result field is not changed. That behavior matters in production programs because an old value can remain in the field unless the error path handles it clearly.

SUBTRACT vs COMPUTE

Use case Better statement Reason
Reduce one counter or balance SUBTRACT Short and direct.
Keep the source amount unchanged SUBTRACT ... GIVING The result goes to a separate field.
Calculate a formula with several operators COMPUTE The full arithmetic expression is easier to inspect.
Subtract same-named fields in two groups SUBTRACT CORRESPONDING Works only when the group layouts are intentionally matched.

Common mistakes

Changing the source field by accident

SUBTRACT WS-TAX FROM WS-GROSS-PAY changes WS-GROSS-PAY. If later logic still needs the original gross amount, use GIVING.

Using a receiving field that is too small

A result field such as PIC S9(3)V99 cannot hold a large payroll amount. Define enough digits and code ON SIZE ERROR when bad input or a large adjustment should be trapped.

Skipping END-SUBTRACT in nested code

END-SUBTRACT makes the statement boundary clear. It is especially useful when SUBTRACT has ON SIZE ERROR logic inside an IF or EVALUATE.

Quick checklist

  • Use SUBTRACT ... FROM only when the FROM field should be updated.
  • Use GIVING when the original value must be preserved.
  • Use ROUNDED when decimal rounding is part of the rule.
  • Use ON SIZE ERROR for payroll, billing, balance, and adjustment calculations where overflow should not pass silently.
  • Prefer COMPUTE for mixed arithmetic expressions.

Related COBOL arithmetic topics

For connected examples, read COBOL COMPUTE Statement, COBOL DIVIDE Clause, COBOL MULTIPLY Statement, COBOL USAGE Clause, COBOL ARITH Compiler Option, and COBOL Decision Making.

External references

Technical behavior in this refresh was checked against IBM Enterprise COBOL SUBTRACT statement documentation and IBM size error phrase documentation.

FAQ

Does COBOL SUBTRACT change the FROM field?

Yes, the basic SUBTRACT ... FROM form stores the result back in the FROM field. Use GIVING if the original value must stay unchanged.

Can COBOL SUBTRACT handle more than one amount?

Yes. COBOL adds the amounts before FROM and subtracts that total from the value after FROM.

When should I use ON SIZE ERROR?

Use it when the result may not fit in the receiving field, especially in money, balance, quantity, or adjustment calculations.

Should I use SUBTRACT or COMPUTE?

Use SUBTRACT for a simple reduction. Use COMPUTE when the formula mixes several arithmetic operations.

COBOL REDEFINES Clause: Rules and Practical Examples

05 DATE-FIELDS REDEFINES DATE-TEXT lets a COBOL program view the same eight bytes as one text value or as year, month, and day fields. No MOVE occurs when the alternate name is referenced. Both descriptions begin at the same storage address.

COBOL REDEFINES clause showing the same eight bytes as date text and separate year month day fields
REDEFINES supplies alternate descriptions of one storage area; writing through either description changes the same bytes.

What the COBOL REDEFINES clause does

The COBOL REDEFINES clause overlays one data description on another. It is useful when an input record has several formats, when a field needs both a group and elementary view, or when existing bytes must be split into named subfields without copying them.

REDEFINES changes the description, not the data. COBOL does not convert character digits into packed decimal, validate a date, or select the correct transaction format. The program must know which layout matches the bytes before using fields whose class or usage imposes numeric rules.

Storage rule: the original item and its alternate descriptions occupy overlapping character positions. Redefinitions and renamings do not add their sizes again when COBOL determines a record length.

Basic REDEFINES syntax

level-number data-name-1 REDEFINES data-name-2.
   subordinate-data-items

data-name-1 is the redefining subject. data-name-2 is the earlier item whose storage is being described again. The clause follows the redefining name and must be the first clause in that data description entry.

The two entries use the same level number within the same record area. The redefined name must already be defined. A lower level number cannot intervene in a way that ends the containing group. Use the COBOL Data Division guide for level numbers and record hierarchy.

Example 1: split an eight-byte date

01  WS-DATE-AREA.
    05  WS-DATE-TEXT         PIC X(8).
    05  WS-DATE-FIELDS REDEFINES WS-DATE-TEXT.
        10  WS-DATE-YEAR     PIC 9(4).
        10  WS-DATE-MONTH    PIC 9(2).
        10  WS-DATE-DAY      PIC 9(2).

    MOVE '20260908' TO WS-DATE-TEXT
    DISPLAY WS-DATE-YEAR
    DISPLAY WS-DATE-MONTH
    DISPLAY WS-DATE-DAY

The MOVE stores eight character bytes. The subordinate numeric-display fields occupy those same positions, so the displays produce 2026, 09, and 08. This works because every byte contains a valid display digit.

No automatic validation: if WS-DATE-TEXT contains 2026AB08, the month field is not valid numeric data. Test the source or use a date-validation routine before numeric processing.

Example 2: select a transaction layout

01  INPUT-RECORD.
    05  RECORD-TYPE          PIC X.
        88  SALES-RECORD     VALUE 'S'.
        88  RETURN-RECORD    VALUE 'R'.
    05  RECORD-DATA          PIC X(19).
    05  SALES-DATA REDEFINES RECORD-DATA.
        10  SALE-ITEM        PIC X(8).
        10  SALE-QUANTITY    PIC 9(5).
        10  SALE-AMOUNT      PIC 9(6).
    05  RETURN-DATA REDEFINES RECORD-DATA.
        10  RETURN-ITEM      PIC X(8).
        10  RETURN-CODE      PIC X(3).
        10  RETURN-AMOUNT    PIC 9(6).
        10  FILLER           PIC X(2).

EVALUATE TRUE
  WHEN SALES-RECORD
       PERFORM PROCESS-SALE
  WHEN RETURN-RECORD
       PERFORM PROCESS-RETURN
  WHEN OTHER
       PERFORM REJECT-RECORD
END-EVALUATE

The discriminator sits outside the overlaid 19-byte area. The program tests it before referencing numeric fields in SALES-DATA or RETURN-DATA. Multiple alternate descriptions name the original RECORD-DATA, which makes the common storage owner clear.

This pattern is common in copybooks for fixed-format files and messages. The file's actual record length must still match the FD and data-set attributes. See the COBOL fixed versus variable-length record guide.

Example 3: inspect packed-decimal bytes

01  AMOUNT-AREA.
    05  WS-AMOUNT            PIC S9(7)V99 COMP-3.
    05  WS-AMOUNT-BYTES REDEFINES WS-AMOUNT
                             PIC X(5).

A nine-digit signed packed-decimal item occupies five bytes. The alphanumeric overlay can be useful when moving the exact stored representation to a diagnostic field or examining it in a dump. It does not turn the packed value into readable decimal text.

Do not DISPLAY the byte overlay and expect 123.45. Use an edited numeric receiving field for presentation. The COBOL USAGE clause guide explains DISPLAY, COMP, COMP-3, and COMP-5 storage.

REDEFINES rules that matter in production

RulePractical effect
Subject and object use the same level.An 05-level item overlays another 05-level item, not one of its 10-level children.
The object is defined earlier.The compiler must already know the storage area being described again.
The object cannot contain OCCURS on its own entry.Do not name a table item itself as the REDEFINES object; restructure the surrounding group where allowed.
The subject and its subordinate items cannot contain VALUE clauses.Initialization belongs on the original definition or in executable logic.
Several alternates can overlay one original item.Name the original object in each REDEFINES clause.
EXTERNAL cannot be on the same entry as REDEFINES.External-record layouts have additional size and consistency rules.
GLOBAL belongs only to the redefining subject when coded there.The GLOBAL attribute does not automatically pass to the object.

Do the layouts need equal lengths?

Equal lengths make a record overlay easiest to review, but current Enterprise COBOL does not impose one simple equal-length rule on every case. IBM permits a non-level-01 redefining item to be larger than the item it overlays. This extension does not increase the size of the original item.

Level-01, external-record, file-description, OCCURS, and compiler-compatibility cases have additional restrictions. Treat unequal overlays as a design requiring compiler-listing review and boundary tests. RULES(NOLAXREDEF) can request warnings for certain smaller redefinitions.

Review with offsets: use the compiler data map to compare displacement and length for the original and every alternate. The code may compile while an intended child field still starts on the wrong byte.

REDEFINES versus RENAMES

REDEFINES supplies an alternate data description for the same starting storage area and can change the subordinate structure or data categories. RENAMES uses a level-66 entry to give another name to one item or a contiguous range of existing items.

Use REDEFINES for variant layouts. Use RENAMES when the requirement is another group name for already described positions. The COBOL RENAMES clause guide covers level 66 and THRU.

REDEFINES and variable records

Alternate 01-level records under an FD can describe different record formats. The maximum record size and file organization still come from the FD clauses, record descriptions, and data-set attributes. REDEFINES does not by itself make a QSAM or VSAM record variable length.

When a file truly contains variable-length records, use the applicable RECORD IS VARYING, multiple 01-level descriptions, or OCCURS DEPENDING ON design. Keep the maximum COBOL record length consistent with LRECL and the access method.

Common REDEFINES errors

  • Expecting the alternate item to receive a copied or converted value.
  • Placing the overlay at a different level from the original item.
  • Naming an OCCURS item directly as the object.
  • Coding VALUE on the redefining item or one of its children.
  • Using a numeric alternate before checking the record-type field.
  • Assuming an alphanumeric view of COMP-3 produces readable digits.
  • Changing a copybook overlay without comparing every consumer's offsets.
  • Using REDEFINES where a MOVE and validation would express the requirement more safely.

If the wrong overlay produces invalid packed or zoned data, a numeric instruction can fail with S0C7. Preserve the input record, identify the active layout, and inspect field offsets before changing the arithmetic statement.

Safe coding checklist

  • Keep a discriminator outside the overlaid data when records have variants.
  • Name the raw storage area and every business layout clearly.
  • Match total lengths unless a documented unequal-size design is intentional.
  • Confirm numeric bytes before arithmetic, comparison, or conversion.
  • Check the compiler map after changing a copybook.
  • Regression-test every record type, including rejected and truncated input.
  • Confirm FD length rules for file records.

The Working-Storage versus Local-Storage guide explains lifetime and initialization, while the COBOL TRUNC guide covers binary receiving fields.

Official IBM references

COBOL REDEFINES clause FAQ

Does COBOL REDEFINES allocate more storage?

No. The original item and the redefining item describe the same storage positions. COBOL does not copy or convert the bytes when another description is referenced.

Must the two REDEFINES items have the same level number?

The subject and object use the same level number and belong to the same record area. Level 66 and level 88 entries are not used as ordinary REDEFINES subjects or objects.

Can the item named after REDEFINES contain OCCURS?

No. IBM states that the data description entry for the redefined object cannot itself contain an OCCURS clause. A group layout can still contain subordinate table definitions where the applicable rules permit them.

Why can REDEFINES cause an S0C7 abend?

REDEFINES does not validate which layout matches the bytes. If character data is processed through a numeric or packed-decimal description, a numeric operation can raise a data exception such as S0C7.

Use REDEFINES only after the program has a reliable way to identify which description matches the bytes currently in the shared storage area.

COBOL Terminal Input and Output: ACCEPT and DISPLAY Examples

COBOL terminal input output flow using ACCEPT and DISPLAY
ACCEPT reads input. DISPLAY writes output.

A small test job asks for an account number, the operator types one line, and the program prints the value to the spool. In COBOL, that simple exchange is usually built with two verbs: ACCEPT for input and DISPLAY for output.

This page explains terminal input and output in COBOL in plain English. It focuses on what a beginner sees in a batch job, TSO test, or training program: where the input comes from, where the message goes, and why these verbs should be used carefully in production code.

What Terminal Input and Output Means in COBOL

Terminal input and output means the program communicates with a person or a simple run-time device instead of reading a normal business file. In a mainframe batch job, input can come from SYSIN. Output often goes to SYSOUT, the job log, or a console-related destination depending on the compile and run-time setup.

That is different from file processing. A file program normally uses OPEN, READ, WRITE, and CLOSE with an FD entry. Terminal I/O is simpler, but it is not a replacement for structured file design. Use it for prompts, diagnostics, small utilities, classroom examples, and controlled test jobs.

ACCEPT Verb in COBOL

The ACCEPT statement moves incoming data into a COBOL data item. IBM documents that ACCEPT does not validate or edit the incoming value for you, so the program must check the field after reading it. If the user enters letters into a numeric account field, your program needs to decide what to do.

Simple ACCEPT Syntax

WORKING-STORAGE SECTION.
01  WS-ACCOUNT-NO        PIC X(10).
01  WS-REPLY             PIC X.

PROCEDURE DIVISION.
    DISPLAY "ENTER ACCOUNT NUMBER: ".
    ACCEPT WS-ACCOUNT-NO.

    DISPLAY "ACCOUNT ENTERED: " WS-ACCOUNT-NO.
    STOP RUN.

In a simple batch test, the value accepted by the program can be supplied through SYSIN. That lets a developer repeat the same test without typing at a screen every time.

Batch Test with SYSIN

//STEP01   EXEC PGM=ACCTIO
//STEPLIB  DD DISP=SHR,DSN=PROD.COBOL.LOAD
//SYSOUT   DD SYSOUT=*
//SYSIN    DD *
ACCT000123
/*

When the program executes ACCEPT WS-ACCOUNT-NO, the run-time environment can read the next available input line from the assigned input source. Site standards vary, so always check how your shop maps COBOL terminal input in batch, TSO, and z/OS UNIX runs.

DISPLAY Verb in COBOL

The DISPLAY statement writes literals and data items to an output device. With no special destination phrase, the output normally goes to the system logical output device. In a batch job, that usually means the message appears in spool output associated with SYSOUT.

Simple DISPLAY Syntax

01  WS-ACCOUNT-NO        PIC X(10) VALUE "ACCT000123".
01  WS-STATUS            PIC X(08) VALUE "ACTIVE".

PROCEDURE DIVISION.
    DISPLAY "ACCOUNT=" WS-ACCOUNT-NO
            " STATUS=" WS-STATUS.
    STOP RUN.

This is useful for small trace messages while testing. For example, a developer may display the key before a READ, then display the file status after the READ. For long-running production jobs, permanent logging rules should come from your team standard rather than scattered DISPLAY statements.

ACCEPT and DISPLAY Together

The pair is easy to understand when shown together. The program below reads an employee number and prints a clean response. It also checks that the field is not blank before continuing.

IDENTIFICATION DIVISION.
PROGRAM-ID. TERMIO.

DATA DIVISION.
WORKING-STORAGE SECTION.
01  WS-EMP-NO            PIC X(08).

PROCEDURE DIVISION.
    DISPLAY "ENTER EMPLOYEE NUMBER: ".
    ACCEPT WS-EMP-NO.

    IF WS-EMP-NO = SPACES
        DISPLAY "EMPLOYEE NUMBER IS REQUIRED"
    ELSE
        DISPLAY "EMPLOYEE NUMBER ENTERED: " WS-EMP-NO
    END-IF.

    STOP RUN.

The validation is deliberately simple. In a real payroll or claims program, you might also check length, allowed characters, and whether the key exists in a VSAM file or Db2 table.

Common Uses in Mainframe Work

Use case Typical verb Example
Read one test value ACCEPT Read an account number from SYSIN.
Print a diagnostic message DISPLAY Show WS-FILE-STATUS after a failed read.
Confirm selected options DISPLAY Print the run date, region, or control-card value.
Build a quick training program Both Prompt for a value, accept it, and display the result.

Validation Rules Beginners Often Miss

ACCEPT is not the same as business validation. It reads the data, but it does not prove the data is right. For a numeric field, accept into an alphanumeric work field first when bad input is possible, check it, and only then move it to a numeric field.

01  WS-AMOUNT-TEXT       PIC X(07).
01  WS-AMOUNT            PIC 9(07).

PROCEDURE DIVISION.
    DISPLAY "ENTER AMOUNT: ".
    ACCEPT WS-AMOUNT-TEXT.

    IF WS-AMOUNT-TEXT IS NUMERIC
        MOVE WS-AMOUNT-TEXT TO WS-AMOUNT
        DISPLAY "AMOUNT ACCEPTED: " WS-AMOUNT
    ELSE
        DISPLAY "AMOUNT MUST BE NUMERIC"
    END-IF.

This avoids a common beginner mistake: reading untrusted input directly into a numeric field and then wondering why the program fails later or prints confusing output.

DISPLAY Output Limits and Formatting

Keep displayed lines short. IBM documents device-related limits for displayed records, and console output is especially limited compared with ordinary spool output. A safe training habit is to display concise messages and split long diagnostic text across several lines.

DISPLAY "INPUT ACCOUNT: " WS-ACCOUNT-NO.
DISPLAY "FILE STATUS  : " WS-FILE-STATUS.
DISPLAY "ACTION       : CHECK CUSTOMER MASTER".

Avoid one huge DISPLAY line containing every field in working storage. It is hard to read in spool output, and it can be split by the output device. Short messages are easier to scan during an abend review.

ACCEPT vs READ in COBOL

Use ACCEPT when the program needs a small value from a simple input source. Use READ when the program processes records from a defined file. A batch payment program should not use ACCEPT to process thousands of payment records; it should define the input file in the Environment Division and read it record by record.

For file processing topics, continue with the Mainframe Forum guides on COBOL READ statement, COBOL file status, and COBOL OPEN statement.

How This Fits with Other COBOL Verbs

ACCEPT and DISPLAY are often the first COBOL I/O verbs a learner sees. After that, the next step is usually file input and output, then table processing, string handling, and conditional logic. Related Mainframe Forum notes include COBOL ACCEPT statement, COBOL DISPLAY statement, COBOL PERFORM statement, and COBOL data types.

Common Mistakes

Accepting Bad Data Without a Check

If a field must be numeric, test it before moving it to a numeric target. If the field must be a valid code, compare it with known values or a control table.

Using DISPLAY as a Permanent Audit Trail

DISPLAY is fine for training and controlled diagnostics. For production audit evidence, use the logging method approved for the application so operations teams can search and retain it properly.

Mixing Terminal I/O with File I/O

Do not use ACCEPT for normal transaction files just because it looks shorter than READ. File I/O gives you record definitions, file status checks, and clearer restart behavior.

FAQ

What is the COBOL terminal input verb?

The common terminal input verb is ACCEPT. It reads data from an input source and places it into the named COBOL data item.

What is the COBOL terminal output verb?

The common terminal output verb is DISPLAY. It writes literals or data-item values to the output destination used by the run-time environment.

Can ACCEPT validate input automatically?

No. ACCEPT reads the input value, but the program must validate it. Use checks such as IS NUMERIC, blank checks, valid-code checks, or file/table lookups.

Should production batch programs use ACCEPT for large input files?

No. Large business input should usually be handled with normal file processing: OPEN, READ, file status checks, and CLOSE.

References

For exact syntax and current compiler behavior, use IBM documentation for Enterprise COBOL ACCEPT statement, Enterprise COBOL DISPLAY statement, and assigning input from a screen or file.

Use ACCEPT for small controlled input, use DISPLAY for readable messages, and validate every value that can come from outside the program.

COBOL Rounded Clause | ROUNDED in COBOL Example [COBOL ROUNDED Statement].

COBOL ROUNDED Phrase, COBOL Rounding

COBOL ROUNDED Phrase

Welcome back to today's session on "COBOL Rounded Clause" or "COBOL Rounding". In this session, you'll learn the basics of the COBOL ROUNDED statement and why you use COBOL rounding in your application programs.  You'll go through the COBOL rounding up an example for better understanding. Let's get started with the COBOL Rounded Phrase introduction.  
Agenda. 
  • Introduction. 
  • What is COBOL ROUNDED Clause (i.e. COBOL ROUNDED Statement)?
  • COBOL ROUNDED Syntax. 
  • COBOL ROUNDED Example. 
    • ROUNDING in COBOL Example.
  • ROUNDED in COBOL Rules.
  • Conclusion.

Introduction. 

The capability of rounding up or rounding down is another important feature of any programming language. There are many business scenarios where monetary transaction value is either round-up or rounded down based on the requirement. COBOL ROUNDED Phrase (i.e. COBOL ROUNDED statement) is used to implement rounding in COBOL programs. In COBOL, you do not have any default rounding. You've to specify the rounding in your program. 
 

COBOL Rounding Rule of Thumb. 

  • If the ending value is 5 or more then round Up (i.e. COBOL round up).
  • If the ending value is 4 or less then round Down (i.e. COBOL round down).

What is COBOL ROUNDED Clause (i.e. COBOL ROUNDED Statement)?


COBOL ROUNDED Clause, ROUNDED in COBOL

COBOL ROUNDED CLAUSE
Once the decimal point is aligned, the number of places given for the fraction of the resultant identifier is compared to the number of places in the fraction of the product of an arithmetic operation. 

Unless the COBOL ROUNDED phrase is known, truncation occurs when the size of the fractional result exceeds the number of places given for its storage.

When the COBOL ROUNDED verb is used, the resulting identifier's least significant digit is increased by 1 if the excess's most significant digit is greater than or equal to 5.

COBOL Rounding or truncation occurs relative to the rightmost integer position for which storage is allocated when the resultant identifier is defined by a PICTURE clause containing the rightmost Ps and the number of places in the measured result exceeds the number of integer positions stated.

Important: The COBOL ROUNDED phrase has no effect in a floating-point arithmetic operation; the output of a floating-point operation is always rounded.

COBOL ROUNDED Syntax. 

The syntax of ROUNDED in COBOL is pretty simple and straightforward. You need to specify the ROUNDED keyword as illustrated in the following figure.  
COBOL ROUNDED, ROUNDED in COBOL
ROUNDED  in COBOL Example.

When the result is truncated on either the left or right side after decimal point alignment, this is known as a size error message. Let's look at the following COBOL round down and COBOL rounds up examples.

ROUNDED in COBOL Example. 

Destination Field   |  Actual Result   | Truncated Result | Rounded Result
PIC 9(03)v9.     123.26         123.2          123.3
PIC 9(03)v9.     234.54         234.5          234.5 
PIC 9(03).       456.25         456            456 

Important Point: Division by 0 always leads to SIZE ERROR. 

ROUNDED in COBOL Example: 

COMPUTE SALES-TAX ROUNDED = SALES-AMOUNT * .0785


Rounded in COBOL Rules:

  1. ROUNDED in COBOL can be used with any arithmetic operation. 
  2. Data will be truncated if you did not specify COBOL Rounded Clause and the resultant fields is not sufficient to store the decimal data. 
  3. When the COBOL ROUNDED phrase is used, the output will be rounded to the PICTURE specification of the destination field.
  4. When ROUNDED in COBOL and REMAINDER are used in the same operation then DIVIDE, ROUNDED must be defined first.
You can code the Rounded clause whenever the result of a calculation can have more decimal places than is specified in the picture of the result field. If you don’t use the Rounded clause, the extra decimal places are truncated

Conclusion.

Finally, this marks an end to our today's COBOL ROUNDED clause. In this session, you learn what is COBOL rounding or COBOL ROUNDING Function. You learned COBOL ROUNDED Statement syntax along with COBOL round-up and COBOL round-down examples for better understanding.  


COBOL Tutorial

Have a look at CICS Top 100 Interview Questions Part II.


►Subscribe to Topictrick & Don't forget to press THE BELL ICON to never miss any updates. Also, Please visit mention the link below to stay connected with Topictrick and the Mainframe forum on - 

► Youtube
► Facebook 
► Reddit

Thank you for your support. 
Mainframe Forum™


New In-feed ads