COBOL provides two styles of arithmetic: verb-based (ADD, SUBTRACT, MULTIPLY, DIVIDE) and expression-based (COMPUTE). Each verb has a clear meaning; COMPUTE lets you write formulas with +, -, *, /, and **. You can add ROUNDED and ON SIZE ERROR to handle rounding and overflow. This page introduces these operations for beginners.
COBOL does math in two ways. One way is to use a verb: "ADD this to that," "MULTIPLY this by that." The other way is to write a formula: "COMPUTE result = this + that * 2." Both produce a numeric result. If the result is too big for the field, you can use ON SIZE ERROR to handle it instead of storing a wrong value.
| Verb | Example form |
|---|---|
| ADD | ADD A TO B. or ADD A B GIVING C. |
| SUBTRACT | SUBTRACT A FROM B. or SUBTRACT A FROM B GIVING C. |
| MULTIPLY | MULTIPLY A BY B. or MULTIPLY A BY B GIVING C. |
| DIVIDE | DIVIDE A INTO B. or DIVIDE A INTO B GIVING C. |
| COMPUTE | COMPUTE C = A + B * 2. |
Each verb takes numeric operands and (optionally) GIVING a result field. Without GIVING, the result often goes into the first or last operand (depending on the verb); with GIVING, the result goes into a separate field and the operands are not changed. ROUNDED rounds the result to the receiving field's decimal places. ON SIZE ERROR runs if the result does not fit (e.g. too many integer digits).
1234567891011121314*> ADD: add values; result can go into one of the fields or into a new field ADD WS-QTY TO WS-TOTAL ADD WS-A WS-B WS-C GIVING WS-SUM *> SUBTRACT: subtract second from first; use GIVING for separate result SUBTRACT WS-DEDUCT FROM WS-GROSS GIVING WS-NET *> MULTIPLY and DIVIDE MULTIPLY WS-RATE BY WS-HOURS GIVING WS-PAY DIVIDE WS-TOTAL INTO WS-COUNT GIVING WS-AVG ON SIZE ERROR DISPLAY "Overflow in average" MOVE ZERO TO WS-AVG END-DIVIDE
result-field; do not change the operands.COMPUTE evaluates an arithmetic expression and stores the result. You can use +, -, *, /, and ** (exponentiation). Precedence is: parentheses first, then **, then * and /, then + and -. So COMPUTE Z = A + B * C multiplies B by C first, then adds A.
12345678*> COMPUTE with expression COMPUTE WS-TOTAL = WS-PRICE * WS-QTY COMPUTE WS-INTEREST = WS-PRINCIPAL * WS-RATE / 100 COMPUTE WS-SQUARED = WS-N ** 2 ROUNDED ON SIZE ERROR DISPLAY "Result too large" END-COMPUTE
The receiving field (after GIVING or on the left of COMPUTE) must be numeric and large enough for the result. Its PICTURE (e.g. PIC 9(5)V99) defines how many digits and decimal places are kept. If the result has more decimal places, ROUNDED applies; if it has more integer digits than the field allows, you get size error unless you handle it with ON SIZE ERROR. Plan your PICTUREs and use ON SIZE ERROR for critical calculations.
9(5)V99 for five digits and two decimals).1. Which verb evaluates a full expression like WS-A + WS-B * WS-C?
2. What does ON SIZE ERROR do?