Integer CS Thinking Example 4

Follow the full solution, then compare it with the other examples linked below.

Example 4

medium
A vending machine program stores the price as 175 (meaning $1.75 in cents). A customer inserts 200 cents. Using only integer arithmetic (DIV for integer division, MOD for remainder), calculate the change in dollars and remaining cents.

Solution

  1. 1
    Step 1: change_cents = 200 โˆ’ 175 = 25.
  2. 2
    Step 2: dollars = 25 DIV 100 = 0.
  3. 3
    Step 3: cents = 25 MOD 100 = 25.

Answer

Change is 0 dollars and 25 cents. Integer arithmetic avoids the rounding errors that can occur with decimal (floating-point) money calculations.
Storing money as an integer number of cents is a common practice because integer arithmetic is exact, whereas floating-point can produce tiny rounding errors (e.g., 0.1 + 0.2 โ‰  0.3 in many languages).

About Integer

A data type that represents whole numbers (positive, negative, or zero) without decimal points. Integers are stored exactly in memory and support arithmetic operations like addition, subtraction, multiplication, and integer division.

Learn more about Integer โ†’

More Integer Examples