Reading — step 1 of 5
Learn
COBOL has dedicated verbs for each arithmetic operation. They read like English.
ADD
ADD 5 TO TOTAL.
ADD A TO B GIVING RESULT.
ADD A B C TO TOTAL. *> add multiple
ADD 1 TO X ON SIZE ERROR DISPLAY "overflow".
ADD ... TO X modifies X. ADD ... GIVING X puts the result in X (X needn't be initialized).
SUBTRACT
SUBTRACT 5 FROM TOTAL.
SUBTRACT A FROM B GIVING RESULT.
MULTIPLY / DIVIDE
MULTIPLY 2 BY X.
MULTIPLY A BY B GIVING RESULT.
DIVIDE A BY B GIVING RESULT.
DIVIDE A BY B GIVING QUOTIENT REMAINDER REM.
Note BY in MULTIPLY but INTO/BY in DIVIDE:
DIVIDE A INTO B GIVING X.→ X = B / ADIVIDE A BY B GIVING X.→ X = A / B
Keep them straight or you'll spend an afternoon debugging.
COMPUTE
For anything more complex, use COMPUTE — write expressions in normal infix:
COMPUTE RESULT = (A + B) * 2.
COMPUTE INTEREST = PRINCIPAL * RATE / 100.
COMPUTE AVG = SUM / N.
COMPUTE X = A ** 2 + B ** 2. *> exponentiation
Operators:
+ - * /— arithmetic**— exponentiation- Parentheses for grouping
ROUNDED and SIZE ERROR
COMPUTE PRICE ROUNDED = COST * 1.07.
ADD A TO TOTAL
ON SIZE ERROR DISPLAY "overflow"
NOT ON SIZE ERROR DISPLAY "ok".
ROUNDED— round to PIC's precision (default truncates)ON SIZE ERROR— handle overflow (result wouldn't fit in target)
Type considerations
COBOL math respects PIC. COMPUTE X = 7 / 2. with X PIC 9(3) gives 003 (truncated). With PIC 9(3)V99 you get 003.50.
PIC S9(...) allows negatives. Without S, results are unsigned (negative results may underflow weirdly).
For heavy math, consider COMP (binary integer) or COMP-3 (packed decimal) — both faster than display PIC for arithmetic.
Example: Compound interest
01 PRINCIPAL PIC 9(7)V99 VALUE 1000.00.
01 RATE PIC V99 VALUE .05. *> 5%
01 YEARS PIC 9(2) VALUE 10.
01 RESULT PIC 9(9)V99.
COMPUTE RESULT = PRINCIPAL * (1 + RATE) ** YEARS.
DISPLAY "after " YEARS " years: " RESULT.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…