COBOL COMPUTE Statement
- COMPUTE is a powerful arithmetic statement used to perform all arithmetic operations instead of using dedicated arithmetic statements - ADD, SUBTACT, MULTIPLY, and DIVIDE statements.
- It is flexible because it can handle multiple arithmetic operations in a single expression.
- 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 - Specifies a user-defined formulae that performs arithmetic calculation.
- ROUNDED phrase - Used to round the result to the nearest whole number.
- END-COMPUTE - Specifies the end of the COMPUTE statement. It is not required when the COMPUTE ends with a period.
Error Handling -
- SIZE ERROR phrase - Executes when there's an arithmetic overflow or underflow.
- NOT SIZE ERROR phrase - Executes when the computation is successful without any size errors.
Practical Example -
Scenario - Let's assume we have three variables, WS-INP1, WS-INP2, and WS-INP3. We want to perform the expression (WS-INP1 + WS-INP2) * WS-INP3 and store it in WS-OP.
Code -
----+----1----+----2----+----3----+----4----+----5----+
       ...
       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.
		   ...Output -
RESULT: 05000
Explaining example -
In this example:
- If the computation is successful, "RESULT:" will be displayed.
- If the result exceeds the maximum value (or has some other size error) for WS-OP, then "SIZE ERROR" will be displayed.
