MainframeMaster

COBOL Tutorial

Basic Arithmetic Operations

Progress0 of 0 lessons

Introduction to COBOL Arithmetic

COBOL provides several specialized verbs for arithmetic operations, giving programmers flexibility in how calculations are performed. Each arithmetic verb has its own syntax variations to handle different calculation scenarios.

Common Features of Arithmetic Operations

  • ROUNDED phrase: Optionally rounds results instead of truncating
  • ON SIZE ERROR: Detects and handles arithmetic overflow conditions
  • NOT ON SIZE ERROR: Executes when no overflow occurs
  • END-verb: Explicit scope terminators (END-ADD, END-SUBTRACT, etc.)
  • Intermediate results: COBOL maintains sufficient precision during calculations

The Five Main Arithmetic Verbs

VerbPrimary PurposeKey Variations
ADDSum valuesADD TO, ADD GIVING
SUBTRACTFind differencesSUBTRACT FROM, SUBTRACT GIVING
MULTIPLYMultiplicationMULTIPLY BY, MULTIPLY GIVING
DIVIDEDivisionDIVIDE INTO, DIVIDE BY GIVING, REMAINDER
COMPUTEFormula evaluationSupports math expressions with operators

ADD Statement

The ADD statement sums two or more numeric values. It supports different formats for various addition scenarios, from basic sums to more complex aggregations.

ADD Statement Formats

Format 1: ADD TO

cobol
1
2
3
4
ADD {identifier-1|literal-1} ... TO identifier-2 [ROUNDED] ... [ON SIZE ERROR imperative-statement-1] [NOT ON SIZE ERROR imperative-statement-2] [END-ADD]

Format 2: ADD GIVING

cobol
1
2
3
4
5
ADD {identifier-1|literal-1} ... TO {identifier-2|literal-2} ... GIVING identifier-3 [ROUNDED] ... [ON SIZE ERROR imperative-statement-1] [NOT ON SIZE ERROR imperative-statement-2] [END-ADD]

Format 3: ADD CORRESPONDING

cobol
1
2
3
4
ADD CORRESPONDING|CORR identifier-1 TO identifier-2 [ROUNDED] [ON SIZE ERROR imperative-statement-1] [NOT ON SIZE ERROR imperative-statement-2] [END-ADD]

ADD Statement Examples

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
* Example 1: Basic ADD TO ADD 1 TO COUNTER. * Example 2: Multiple operands ADD SUBTOTAL SALES-TAX SHIPPING-COST TO TOTAL-AMOUNT. * Example 3: ADD GIVING (preserves original values) ADD HOURS OVERTIME GIVING TOTAL-HOURS. * Example 4: Multiple receiving fields ADD WHOLESALE-COST MARKUP TO SELLING-PRICE ROUNDED DISPLAY-PRICE ROUNDED. * Example 5: Error handling ADD SUBTOTAL TAX TO TOTAL-COST ON SIZE ERROR DISPLAY "Arithmetic overflow occurred" PERFORM ERROR-ROUTINE NOT ON SIZE ERROR PERFORM NORMAL-PROCESSING END-ADD. * Example 6: ADD CORRESPONDING ADD CORRESPONDING OLD-TOTALS TO NEW-TOTALS.

Key Points About ADD

  • ADD TO: Modifies the receiving field (identifier-2)
  • ADD GIVING: Preserves all source operands, storing the result separately
  • ADD CORRESPONDING: Adds only the elementary items with matching names
  • You can add multiple literals and identifiers in a single statement
  • The ROUNDED phrase applies separately to each receiving field
  • Without ROUNDED, decimal overflow is truncated, not rounded
  • Scope terminators (END-ADD) are required in nested IF statements

SUBTRACT Statement

The SUBTRACT statement calculates the difference between numeric values. Like ADD, it offers various formats to handle different subtraction scenarios.

SUBTRACT Statement Formats

Format 1: SUBTRACT FROM

cobol
1
2
3
4
SUBTRACT {identifier-1|literal-1} ... FROM identifier-2 [ROUNDED] ... [ON SIZE ERROR imperative-statement-1] [NOT ON SIZE ERROR imperative-statement-2] [END-SUBTRACT]

Format 2: SUBTRACT GIVING

cobol
1
2
3
4
5
SUBTRACT {identifier-1|literal-1} ... FROM {identifier-2|literal-2} GIVING identifier-3 [ROUNDED] ... [ON SIZE ERROR imperative-statement-1] [NOT ON SIZE ERROR imperative-statement-2] [END-SUBTRACT]

Format 3: SUBTRACT CORRESPONDING

cobol
1
2
3
4
SUBTRACT CORRESPONDING|CORR identifier-1 FROM identifier-2 [ROUNDED] [ON SIZE ERROR imperative-statement-1] [NOT ON SIZE ERROR imperative-statement-2] [END-SUBTRACT]

SUBTRACT Statement Examples

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
* Example 1: Basic SUBTRACT FROM SUBTRACT 1 FROM COUNTER. * Example 2: Multiple items to subtract SUBTRACT RETURNS DISCOUNTS FROM TOTAL-SALES. * Example 3: SUBTRACT GIVING (preserves original values) SUBTRACT DEDUCTIONS FROM GROSS-PAY GIVING NET-PAY. * Example 4: Multiple receiving fields SUBTRACT USED-QUANTITY FROM INITIAL-QUANTITY GIVING REMAINING-QUANTITY ROUNDED DISPLAY-QUANTITY ROUNDED. * Example 5: Error handling SUBTRACT WITHDRAWALS FROM ACCOUNT-BALANCE ON SIZE ERROR DISPLAY "Insufficient funds" PERFORM OVERDRAFT-ROUTINE END-SUBTRACT. * Example 6: SUBTRACT CORRESPONDING SUBTRACT CORRESPONDING EXPENSE-ITEMS FROM BUDGET-ITEMS.

Key Points About SUBTRACT

  • SUBTRACT FROM: The receiving field is reduced by the sum of all listed operands
  • SUBTRACT GIVING: The difference is calculated and stored in a separate field
  • SUBTRACT CORRESPONDING: Only subtracts items with matching names
  • When subtracting multiple items, they are summed first, then subtracted from the target
  • Negative results are handled according to the sign of the receiving field
  • For financial applications, use SUBTRACT GIVING for audit trails
  • Always check for potential negative balances in financial applications

MULTIPLY Statement

The MULTIPLY statement performs multiplication of numeric values. It provides different formats to handle various multiplication scenarios.

MULTIPLY Statement Formats

Format 1: MULTIPLY BY

cobol
1
2
3
4
MULTIPLY {identifier-1|literal-1} BY identifier-2 [ROUNDED] ... [ON SIZE ERROR imperative-statement-1] [NOT ON SIZE ERROR imperative-statement-2] [END-MULTIPLY]

Format 2: MULTIPLY GIVING

cobol
1
2
3
4
5
MULTIPLY {identifier-1|literal-1} BY {identifier-2|literal-2} GIVING identifier-3 [ROUNDED] ... [ON SIZE ERROR imperative-statement-1] [NOT ON SIZE ERROR imperative-statement-2] [END-MULTIPLY]

MULTIPLY Statement Examples

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
* Example 1: Basic MULTIPLY BY MULTIPLY 2 BY QUANTITY. * Example 2: Using variables MULTIPLY UNIT-PRICE BY QUANTITY. * Example 3: MULTIPLY GIVING (preserves original values) MULTIPLY HOURS BY HOURLY-RATE GIVING GROSS-PAY. * Example 4: Multiple receiving fields MULTIPLY UNIT-PRICE BY QUANTITY GIVING EXTENDED-PRICE ROUNDED DISPLAY-AMOUNT ROUNDED. * Example 5: Error handling MULTIPLY QUANTITY BY UNIT-PRICE GIVING TOTAL-PRICE ON SIZE ERROR DISPLAY "Overflow in price calculation" PERFORM ERROR-ROUTINE END-MULTIPLY. * Example 6: Calculate discount MULTIPLY TOTAL-PRICE BY 0.10 GIVING DISCOUNT-AMOUNT ROUNDED.

Key Points About MULTIPLY

  • MULTIPLY BY: Modifies the receiving field directly
  • MULTIPLY GIVING: Preserves operands, storing result separately
  • Unlike ADD/SUBTRACT, MULTIPLY only works with two operands at a time
  • For multiple multiplication, nest statements or use COMPUTE
  • Intermediate results maintain enough digits for precision
  • Watch for potential overflow in receiving fields
  • For financial calculations, consider scaling factors for percentages

DIVIDE Statement

The DIVIDE statement performs division operations. It offers several formats for different division scenarios, including the ability to capture the remainder.

DIVIDE Statement Formats

Format 1: DIVIDE INTO

cobol
1
2
3
4
DIVIDE {identifier-1|literal-1} INTO identifier-2 [ROUNDED] ... [ON SIZE ERROR imperative-statement-1] [NOT ON SIZE ERROR imperative-statement-2] [END-DIVIDE]

Format 2: DIVIDE BY GIVING

cobol
1
2
3
4
5
DIVIDE {identifier-1|literal-1} BY {identifier-2|literal-2} GIVING identifier-3 [ROUNDED] ... [ON SIZE ERROR imperative-statement-1] [NOT ON SIZE ERROR imperative-statement-2] [END-DIVIDE]

Format 3: DIVIDE INTO GIVING

cobol
1
2
3
4
5
DIVIDE {identifier-1|literal-1} INTO {identifier-2|literal-2} GIVING identifier-3 [ROUNDED] ... [ON SIZE ERROR imperative-statement-1] [NOT ON SIZE ERROR imperative-statement-2] [END-DIVIDE]

Format 4: DIVIDE with REMAINDER

cobol
1
2
3
4
5
6
DIVIDE {identifier-1|literal-1} INTO {identifier-2|literal-2} GIVING identifier-3 [ROUNDED] REMAINDER identifier-4 [ON SIZE ERROR imperative-statement-1] [NOT ON SIZE ERROR imperative-statement-2] [END-DIVIDE]

Format 5: DIVIDE BY with REMAINDER

cobol
1
2
3
4
5
6
DIVIDE {identifier-1|literal-1} BY {identifier-2|literal-2} GIVING identifier-3 [ROUNDED] REMAINDER identifier-4 [ON SIZE ERROR imperative-statement-1] [NOT ON SIZE ERROR imperative-statement-2] [END-DIVIDE]

DIVIDE Statement Examples

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
* Example 1: Basic DIVIDE INTO DIVIDE 2 INTO AMOUNT. * Example 2: DIVIDE BY GIVING DIVIDE TOTAL-AMOUNT BY NUM-ITEMS GIVING PRICE-PER-ITEM. * Example 3: DIVIDE INTO GIVING DIVIDE NUM-ITEMS INTO TOTAL-AMOUNT GIVING PRICE-PER-ITEM. * Example 4: DIVIDE with REMAINDER DIVIDE 7 INTO DAYS GIVING WEEKS REMAINDER REMAINING-DAYS. * Example 5: Error handling for division by zero DIVIDE QUANTITY INTO TOTAL-COST GIVING UNIT-COST ON SIZE ERROR DISPLAY "Error: Division by zero or overflow" MOVE 0 TO UNIT-COST END-DIVIDE. * Example 6: Calculating percentages DIVIDE AMOUNT-SOLD BY TOTAL-SALES GIVING PERCENTAGE ROUNDED.

Key Points About DIVIDE

  • DIVIDE INTO: The second operand is divided by the first and the result replaces the second operand
  • DIVIDE BY/INTO GIVING: Preserves the operands, storing result separately
  • REMAINDER: Captures the remainder after integer division
  • The ON SIZE ERROR phrase can catch division by zero
  • Always check for zero denominators to prevent runtime errors
  • For financial applications, consider scaling for exact results
  • The ROUNDED phrase is especially important in division operations

DIVIDE INTO vs. DIVIDE BY

The DIVIDE statement can be confusing because of its syntax options. Here's a clear explanation:

  • DIVIDE A INTO B: Calculates B ÷ A (B divided by A)
  • DIVIDE A BY B GIVING C: Calculates A ÷ B (A divided by B)
  • DIVIDE A INTO B GIVING C: Calculates B ÷ A (B divided by A)

The word order can be counterintuitive, so be careful when writing division operations.

COMPUTE Statement

The COMPUTE statement provides a more algebraic approach to calculations, allowing the use of mathematical expressions similar to other programming languages. It's especially useful for complex formulas.

COMPUTE Statement Format

cobol
1
2
3
4
COMPUTE identifier-1 [ROUNDED] ... = arithmetic-expression [ON SIZE ERROR imperative-statement-1] [NOT ON SIZE ERROR imperative-statement-2] [END-COMPUTE]

The arithmetic-expression can use operators and parentheses for complex calculations.

Arithmetic Operators in COMPUTE

OperatorOperationExample
+AdditionA + B
-SubtractionA - B
*MultiplicationA * B
/DivisionA / B
**ExponentiationA ** 2

COMPUTE Statement Examples

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
* Example 1: Basic arithmetic COMPUTE TOTAL = SUBTOTAL + TAX. * Example 2: Complex formula COMPUTE AREA = 3.14159 * RADIUS ** 2. * Example 3: Financial calculation COMPUTE INTEREST-AMOUNT = PRINCIPAL * RATE * TIME / 365. * Example 4: Multiple assignments COMPUTE WEEKLY-PAY ROUNDED MONTHLY-PAY ROUNDED = HOURS-WORKED * HOURLY-RATE. * Example 5: Using parentheses to control order of operations COMPUTE DISCOUNT-PRICE = RETAIL-PRICE * (1 - DISCOUNT-RATE). * Example 6: Error handling COMPUTE AVERAGE = TOTAL / COUNT ON SIZE ERROR DISPLAY "Division by zero or overflow" MOVE 0 TO AVERAGE END-COMPUTE.

Order of Operations in COMPUTE

  1. Expressions in parentheses are evaluated first
  2. Exponentiation (**) is performed next
  3. Multiplication (*) and division (/) are performed left to right
  4. Addition (+) and subtraction (-) are performed left to right
  5. Unary operators (+ and -) have the highest precedence

When in doubt, use parentheses to make the order of operations explicit.

COMPUTE vs. Individual Arithmetic Statements

FeatureCOMPUTEIndividual Statements
Readability for complex formulasBetterRequires multiple statements
Execution efficiencyMay be less efficientMay be more efficient
Operator precedence controlSupports parenthesesMust use intermediate results
Exponentiation supportYesNo
Clarity for simple operationsLess explicitMore explicit

Common Features and Best Practices

All COBOL arithmetic operations share certain features and considerations that are important for writing reliable and maintainable code.

ROUNDED Phrase

The ROUNDED phrase applies standard rounding to the result before it is stored in the receiving field.

cobol
1
2
3
4
5
6
7
* Without ROUNDED (truncation occurs) COMPUTE RESULT = 2.6. * RESULT = 2.6 COMPUTE AMOUNT = 10.56 / 3. * AMOUNT = 3.52 (truncated) * With ROUNDED (rounding occurs) COMPUTE RESULT ROUNDED = 2.6. * RESULT = 3 COMPUTE AMOUNT ROUNDED = 10.56 / 3. * AMOUNT = 3.52 (rounded)

The ROUNDED phrase is especially important for financial calculations where accurate rounding is required.

ON SIZE ERROR Phrase

The ON SIZE ERROR phrase handles situations where the result cannot fit in the receiving field or division by zero occurs.

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
* Example 1: Handling numeric overflow ADD LARGE-NUM-1 LARGE-NUM-2 GIVING RESULT ON SIZE ERROR DISPLAY "Result too large for receiving field" PERFORM ERROR-ROUTINE END-ADD. * Example 2: Handling division by zero DIVIDE DIVISOR INTO DIVIDEND GIVING QUOTIENT ON SIZE ERROR DISPLAY "Division by zero or result too large" MOVE 0 TO QUOTIENT NOT ON SIZE ERROR DISPLAY "Division successful" END-DIVIDE.

Always include error handling for critical calculations to prevent program crashes and data corruption.

Scope Terminators

Explicit scope terminators (END-ADD, END-SUBTRACT, etc.) improve code readability and are required in certain contexts.

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
* Without scope terminator (ambiguous nesting) IF AMOUNT > 1000 ADD TAX TO AMOUNT ON SIZE ERROR DISPLAY "Error" ELSE DISPLAY "Small amount". * With scope terminator (clear nesting) IF AMOUNT > 1000 ADD TAX TO AMOUNT ON SIZE ERROR DISPLAY "Error" END-ADD ELSE DISPLAY "Small amount" END-IF.

Always use scope terminators for better readability and to avoid scope ambiguity.

Best Practices for Arithmetic Operations

  • Ensure receiving fields have adequate size to prevent overflow
  • Use ON SIZE ERROR for all critical calculations
  • Use ROUNDED when precision is important
  • Use COMPUTE for complex formulas
  • Use individual statements (ADD, SUBTRACT, etc.) for simple operations
  • Always check for division by zero before performing division
  • Use explicit scope terminators for clarity
  • Document the calculation logic with comments
  • Consider intermediate fields for complex multi-step calculations
  • Be consistent in your approach to similar calculations

Exercises: Basic Arithmetic Operations

Exercise 1: Sales Tax Calculation

Write COBOL statements to calculate sales tax and final price for a purchase.

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
* Given these data items: 01 PURCHASE-DATA. 05 ITEM-PRICE PIC 9(5)V99. 05 QUANTITY PIC 9(3). 05 DISCOUNT-PERCENTAGE PIC 9(2)V99. 05 TAX-RATE PIC 9(2)V99 VALUE 8.50. 01 CALCULATION-RESULTS. 05 SUBTOTAL PIC 9(7)V99. 05 DISCOUNT-AMOUNT PIC 9(5)V99. 05 TAXABLE-AMOUNT PIC 9(7)V99. 05 TAX-AMOUNT PIC 9(5)V99. 05 TOTAL-PRICE PIC 9(7)V99. * Your task: * 1. Calculate SUBTOTAL (ITEM-PRICE * QUANTITY) * 2. Calculate DISCOUNT-AMOUNT based on DISCOUNT-PERCENTAGE * 3. Calculate TAXABLE-AMOUNT (SUBTOTAL - DISCOUNT-AMOUNT) * 4. Calculate TAX-AMOUNT based on TAX-RATE * 5. Calculate TOTAL-PRICE (TAXABLE-AMOUNT + TAX-AMOUNT) * 6. Include appropriate error handling and rounding

Exercise 2: Loan Payment Calculator

Write a COBOL program segment to calculate monthly loan payments.

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
* Given these data items: 01 LOAN-DATA. 05 PRINCIPAL-AMOUNT PIC 9(7)V99. 05 ANNUAL-INTEREST-RATE PIC 9(2)V99. 05 LOAN-TERM-YEARS PIC 9(2). 01 CALCULATION-RESULTS. 05 MONTHLY-INTEREST-RATE PIC 9(2)V9(6). 05 LOAN-TERM-MONTHS PIC 9(3). 05 MONTHLY-PAYMENT PIC 9(7)V99. 05 TOTAL-PAYMENTS PIC 9(9)V99. 05 TOTAL-INTEREST PIC 9(7)V99. * Your task: * 1. Calculate MONTHLY-INTEREST-RATE from ANNUAL-INTEREST-RATE * 2. Calculate LOAN-TERM-MONTHS from LOAN-TERM-YEARS * 3. Calculate MONTHLY-PAYMENT using the formula: * P * r * (1 + r)^n / ((1 + r)^n - 1) * Where P is principal, r is monthly rate, n is term in months * 4. Calculate TOTAL-PAYMENTS (MONTHLY-PAYMENT * LOAN-TERM-MONTHS) * 5. Calculate TOTAL-INTEREST (TOTAL-PAYMENTS - PRINCIPAL-AMOUNT) * 6. Include appropriate error handling and rounding

Exercise 3: Inventory Valuation

Write COBOL statements to calculate inventory values and statistics.

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
* Given these data structures: 01 INVENTORY-RECORD. 05 ITEM-ID PIC X(10). 05 QUANTITY-ON-HAND PIC 9(5). 05 COST-PER-UNIT PIC 9(3)V99. 05 SELLING-PRICE PIC 9(3)V99. 01 INVENTORY-TOTALS. 05 TOTAL-ITEMS PIC 9(5) VALUE ZERO. 05 TOTAL-INVENTORY-COST PIC 9(9)V99 VALUE ZERO. 05 TOTAL-RETAIL-VALUE PIC 9(9)V99 VALUE ZERO. 05 AVERAGE-COST PIC 9(5)V99. 05 AVERAGE-PRICE PIC 9(5)V99. 05 POTENTIAL-PROFIT PIC 9(9)V99. 05 PROFIT-MARGIN PIC 9(3)V99. * Your task: * 1. For each inventory record, accumulate: * - TOTAL-ITEMS (add QUANTITY-ON-HAND) * - TOTAL-INVENTORY-COST (add QUANTITY-ON-HAND * COST-PER-UNIT) * - TOTAL-RETAIL-VALUE (add QUANTITY-ON-HAND * SELLING-PRICE) * 2. Calculate AVERAGE-COST (TOTAL-INVENTORY-COST / TOTAL-ITEMS) * 3. Calculate AVERAGE-PRICE (TOTAL-RETAIL-VALUE / TOTAL-ITEMS) * 4. Calculate POTENTIAL-PROFIT (TOTAL-RETAIL-VALUE - TOTAL-INVENTORY-COST) * 5. Calculate PROFIT-MARGIN as percentage (POTENTIAL-PROFIT / TOTAL-INVENTORY-COST * 100) * 6. Include appropriate error handling (especially for division by zero)

Frequently Asked Questions

Test Your Knowledge

1. Which COBOL statement allows you to use mathematical expressions and operators similar to other programming languages?

  • ADD
  • COMPUTE
  • CALCULATE
  • EVALUATE

2. What happens when you use the ROUNDED phrase in an arithmetic operation?

  • The result is always rounded up to the nearest whole number
  • The result is always rounded down to the nearest whole number
  • The result is rounded to fit the receiving field using standard rounding rules
  • The result is truncated to fit the receiving field

3. What does the ON SIZE ERROR clause handle in arithmetic operations?

  • When the result contains more significant digits than the receiving field can hold
  • When division by zero occurs
  • When an invalid operation is attempted
  • All of the above

4. In the ADD statement, what does the TO keyword indicate?

  • The fields to be added together
  • The receiving field where the result will be stored
  • Both the source field to be added and the receiving field
  • The starting value for the addition

5. What is the correct COBOL statement to divide TOTAL-AMOUNT by ITEM-COUNT and store the result in AVERAGE-PRICE?

  • DIVIDE TOTAL-AMOUNT INTO ITEM-COUNT GIVING AVERAGE-PRICE
  • DIVIDE ITEM-COUNT INTO TOTAL-AMOUNT GIVING AVERAGE-PRICE
  • DIVIDE TOTAL-AMOUNT BY ITEM-COUNT GIVING AVERAGE-PRICE
  • COMPUTE AVERAGE-PRICE = TOTAL-AMOUNT / ITEM-COUNT