💻 COBOL
COBOL Arithmetic Operations
Beginner 🕑 18 min read
👁 2 views
Arithmetic Verbs in COBOL
COBOL provides several verbs for performing arithmetic operations. These are designed to be readable and self-documenting.
ADD Statement
Used to add numeric values:
ADD A TO B- Adds A to B, result stored in BADD A B TO C- Adds A and B to CADD A TO B GIVING C- Adds A to B, stores result in C
SUBTRACT Statement
Used to subtract numeric values:
SUBTRACT A FROM B- Subtracts A from B, result in BSUBTRACT A FROM B GIVING C- Result stored in C
MULTIPLY Statement
Used to multiply numeric values:
MULTIPLY A BY B- Multiplies A by B, result in BMULTIPLY A BY B GIVING C- Result stored in C
DIVIDE Statement
Used to divide numeric values:
DIVIDE A INTO B- Divides B by A, result in BDIVIDE A INTO B GIVING C- Result stored in CDIVIDE A INTO B GIVING C REMAINDER D- With remainder
COMPUTE Statement
The COMPUTE statement allows complex arithmetic expressions using standard operators:
- + Addition
- - Subtraction
- * Multiplication
- / Division
- ** Exponentiation
Important Options
- ROUNDED - Rounds the result
- ON SIZE ERROR - Handles overflow conditions
Code Example
PROCEDURE DIVISION.
ARITHMETIC-EXAMPLES.
* ADD examples
ADD 10 TO WS-COUNT.
ADD WS-A WS-B TO WS-C.
ADD WS-PRICE TO WS-TOTAL GIVING WS-GRAND-TOTAL.
* SUBTRACT examples
SUBTRACT 5 FROM WS-COUNT.
SUBTRACT WS-DISCOUNT FROM WS-PRICE
GIVING WS-NET-PRICE.
* MULTIPLY examples
MULTIPLY WS-QTY BY WS-PRICE.
MULTIPLY WS-HOURS BY WS-RATE
GIVING WS-GROSS-PAY ROUNDED.
* DIVIDE examples
DIVIDE WS-TOTAL BY WS-COUNT GIVING WS-AVERAGE.
DIVIDE WS-AMOUNT BY 12
GIVING WS-MONTHLY
REMAINDER WS-REMAINING.
* COMPUTE examples
COMPUTE WS-RESULT = WS-A + WS-B - WS-C.
COMPUTE WS-AREA = 3.14159 * WS-RADIUS ** 2.
COMPUTE WS-TAX = WS-AMOUNT * 0.18 ROUNDED
ON SIZE ERROR
DISPLAY "OVERFLOW ERROR"
NOT ON SIZE ERROR
DISPLAY "TAX CALCULATED"
END-COMPUTE.
STOP RUN.