The COMPUTE statement can be used for mathematical calculations that involve more than one calculation.


COMPUTE identifier-1 [ROUNDED] = arithmetic expression.

The answer that results from the calculation is stored in identifier-1 which is usually defined in WORKING-STORAGE.

In evaluating the arithmetic expression, COBOL follows the order of operation which is:

For example:

    (FLD1 + FLD2) / (FLD3 - FLD4) + (FLD5 - 50) / (FLD6 + 2).

  1. FLD1 will be added to FLD2
  2. FLD4 will be subtracted from FLD3
  3. 50 will be subtracted from FLD5
  4. 2 will be added to FLD6
  5. The answer from number 1 will be divided by the answer from number 2
  6. The answer from number 3 will be divided by the answer from number 4
  7. The answer from number 5 will be added to the answer from number 6 and stored in ANS-WS

The algebra would look like this:

    FLD1 + FLD2    +   FLD5 - 50
    FLD3 - FLD4    +   FLD6 + 2

More examples:

For the examples in this table, I am using single letter data names to match with the algebra and to take up less room. In a real COBOL program, more meaningful data names would be used.

Math........................................ COBOL............................................................................
x=a(b+c)/d COMPUTE X = A * (B + C) / D.
The actual multiply sign (*) must be shown.
x = a + b(c-5)+d(e-6) COMPUTE X = A + B * (C - 5) + D * (E - 6).
The subtracts will be done because they are in ( ) and then the multiplies left to right followed by the adds left to right.
x = a+b/c+d COMPUTE X = A + B / C + D.
B will divided by C first and then A and D will be added
x=(a+b)/(c+d) COMPUTE X = (A + B) / (C + D).
Addition will be done first because it is in ( ) and then divide.
x=a(b+c((d+e)/(f+g)+h)) COMPUTE X = A * (B + C * ((D + E) / (F + G) + H)).
D and E are added and F and G are added and the divide is done, then H is added in and the whole thing is multiplied by C, then that answer is added to B and everything is multiplied by A
x=(a+b)(d+(e-f)/(g-30)) COMPUTE X = (A + B) * (D + (E - F) / (G - 30)).
E-F will be divided by G-30 and the answer will be added to D. A will be added to B and then the multiply will take place.