COMPUTE Statement


The COMPUTE is a powerful arithmetic statement used to perform all arithmetic operations. It is flexible because it can handle multiple arithmetic operations in one expression. It also allows more complex calculations than basic arithmetic verbs like ADD, SUBTRACT, MULTIPLY, and DIVIDE.

The arithmetic operators used in COMPUTE statements are + (ADD), - (SUBTRACT), * (MULTIPLY), / (DIVIDE), and ** (EXPONENT) statements.

Syntax -

COMPUTE output-variable [ROUNDED] = arithmetic-expression
       [ON SIZE ERROR statements-set1]
   [NOT ON SIZE ERROR statements-set2]
[END-COMPUTE]
Note! All statements coded in [ ] are optional.

Parameters -

  • Output-variable - specifies the numeric variable where the computation result will be stored.
  • Arithmetic-expression - The arithmetic operation(s) we want to perform. It can combine addition, subtraction, multiplication, division, and even functions.
  • ROUNDED phrase - Used to round the result to the nearest whole number.
  • END-COMPUTE - is a scope terminator used to end the scope of the COMPUTE statement. It is not required when the COMPUTE statement ends with a period.

Error Handling -

Practical Example -


Scenario - Let's assume we have three variables WS-INP1, WS-INP2, and WS-INP3, and we want to compute the expression (WS-INP1 + WS-INP2) * WS-INP3 and store it in WS-OP.

Code -

----+----1----+----2----+----3----+----4----+----5----+
       IDENTIFICATION DIVISION.                               
       PROGRAM-ID. COMPUTEP.                                  

       DATA DIVISION.                                         
       WORKING-STORAGE SECTION.                               
       01 WS-VAR.                                             
          05 WS-INP1          PIC 9(3) VALUE 240.     
          05 WS-INP2          PIC 9(2) VALUE 10.      
          05 WS-INP3          PIC 9(2) VALUE 20.      
          05 WS-OP            PIC 9(5).               

       PROCEDURE DIVISION.                                    

           COMPUTE WS-OP = ( WS-INP1 + WS-INP2 ) * WS-INP3    
                       ON SIZE ERROR DISPLAY "SIZE ERROR"     
                   NOT ON SIZE ERROR DISPLAY "RESULT: " WS-OP 
           END-COMPUTE.                                       

           STOP RUN.

Output -

RESULT: 05000

Explaining example -

In this example:

  • If the computation is successful, "RESULT:" will be displayed.
  • If the result is too large (or has some other size error) for WS-OP, then "SIZE ERROR" is displayed.