Intro to Arithmetic Operations with COMPUTE

Introduction to Arithmetic Operations with COMPUTE

Welcome back! So far, we've learned how to handle multiple group items and perform basic arithmetic operations within them. Now, let's dive into a significant aspect of COBOL programming: arithmetic operations using the COMPUTE statement. Understanding these operations is essential for programming tasks that involve financial calculations, interest computations, or any scenario where precision is key.

What You'll Learn

In this lesson, you'll learn how to:

  1. Use the COMPUTE statement to perform arithmetic operations.
  2. Display the results of these computations effectively.

For example, by the end of this lesson, you will be comfortable with code like this:

COBOL
IDENTIFICATION DIVISION.
PROGRAM-ID. ComputeDemo.
DATA DIVISION.
WORKING-STORAGE SECTION.

01 Customer.
    02 Account-Balance PIC S9(5)V99 VALUE 100.00.
    02 Deposit PIC S9(5)V99 VALUE 45.00.
    02 New-Balance PIC S9(5)V99.

01 TAX PIC S9(3)V99 VALUE 0.1.

PROCEDURE DIVISION.
    COMPUTE New-Balance = Account-Balance + Deposit - TAX.
    DISPLAY 'New Balance: ' New-Balance.

    STOP RUN.

In this code snippet, we calculate the new balance of a customer's account by adding a deposit and subtracting a tax amount. The COMPUTE statement simplifies this arithmetic operation, making it easier to understand and maintain. It uses mathematical operators, keeping the code concise and readable.

Practical Applications

Using arithmetic operations is fundamental in various real-world scenarios. From banking systems managing account balances to any application requiring financial calculations, precision is crucial. The COMPUTE statement is your tool for performing these precise mathematical operations easily and effectively.

For instance, consider a situation where you need to update the balance of a customer's account after a deposit. You must also factor in a tax deduction. The COMPUTE statement simplifies this process by allowing you to perform the arithmetic operation in a single, clear line of code.

In our sample code, we calculate the new balance by adding a deposit to an existing account balance and then subtracting a tax amount. This kind of calculation is common in financial and business applications, making your understanding of the COMPUTE statement invaluable.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal