BudiBadu Logo
Samplebadu

COBOL by Example: Arithmetic

COBOL 2002

Performing arithmetic operations using English-like verbs ADD, SUBTRACT, MULTIPLY, and DIVIDE with the GIVING clause for result storage, implementing complex calculations with the COMPUTE statement using standard mathematical operators, handling rounding explicitly with ROUNDED clause, detecting numeric overflows with ON SIZE ERROR exception handling, and preserving data integrity in financial calculations.

Code

       IDENTIFICATION DIVISION.
       PROGRAM-ID. ARITHMETIC.
       
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  NUM1        PIC 99 VALUE 10.
       01  NUM2        PIC 99 VALUE 5.
       01  RESULT      PIC 999.
       
       PROCEDURE DIVISION.
           ADD NUM1 TO NUM2 GIVING RESULT.
           DISPLAY "Add: " RESULT.
           
           SUBTRACT NUM2 FROM NUM1 GIVING RESULT.
           DISPLAY "Subtract: " RESULT.
           
           MULTIPLY NUM1 BY NUM2 GIVING RESULT.
           DISPLAY "Multiply: " RESULT.
           
           DIVIDE NUM1 BY NUM2 GIVING RESULT.
           DISPLAY "Divide: " RESULT.
           
           COMPUTE RESULT = (NUM1 + NUM2) * 2.
           DISPLAY "Compute: " RESULT.
           STOP RUN.

Explanation

COBOL provides verbose, English-like statements for basic arithmetic: ADD, SUBTRACT, MULTIPLY, and DIVIDE. These are very readable but can be cumbersome for complex formulas. For more complex mathematical expressions, the COMPUTE statement is used, allowing standard operators like +, -, *, /, and ** (exponentiation).

A key feature of COBOL arithmetic is the GIVING clause. Without it, the result is stored in one of the operands (e.g., ADD A TO B modifies B). With GIVING, the result is stored in a separate variable, preserving the original values. This distinction is crucial for maintaining data integrity in financial calculations.

COBOL also handles rounding and size errors (overflows) explicitly with ROUNDED and ON SIZE ERROR clauses. This makes it extremely robust for business applications where losing a cent or overflowing a field is unacceptable. The COMPUTE statement is generally preferred for any calculation involving more than one operation.

Code Breakdown

10
ADD NUM1 TO NUM2 GIVING RESULT. Adds 10 and 5, storing 15 in RESULT. NUM1 and NUM2 remain unchanged.
13
SUBTRACT NUM2 FROM NUM1 GIVING RESULT. Subtracts 5 from 10. Note the order: "FROM" determines the minuend.
16
MULTIPLY NUM1 BY NUM2 GIVING RESULT. Multiplies 10 by 5. The result (50) is stored in RESULT.
19
DIVIDE NUM1 BY NUM2 GIVING RESULT. Divides 10 by 5. The result (2) is stored in RESULT.
22
COMPUTE RESULT = (NUM1 + NUM2) * 2. Performs the calculation (10 + 5) * 2 = 30. This is much more concise for multi-step math.