Most of us are familiar with division, using it to perform a variety of ordinary tasks, such as comparing the relative cost of different product sizes (cost per unit) or tracking our car's fuel efficiency or mileage (in the non-metric U.S., miles per gallon). We're also accustomed to rounding the result to a convenient number of digits. But truncation is less familiar, sometimes leaving new programmers wondering if it's an error or at least an oversight. While truncation and modular arithmetic are uncommon in our daily activities, they often help computer scientists solve problems they face.
Operating systems divide secondary storage space (e.g., disk drives) into numbered blocks. Computer scientists have devised various schemes to track the free and in-use (i.e., allocated to a file) blocks. One scheme uses a single bit: 1 indicates the corresponding block is free, and 0 indicates it is allocated. The "free space management" example at the end of the chapter organizes the bits as an array of integers. It demonstrates how functions locate and manage the bits with integer division, modular arithmetic, and bitwise operations. While the problem is an authentic example of integer division and modular arithmetic, it requires advanced concepts and operations.
While money.cpp is a less authentic problem, it's also easier to understand. It converts the value of a given number of U.S. pennies into an equivalent value expressed as U.S. dollars, quarters, dimes, nickels, and pennies.
Based on U.S. currency, test cases for this program are quite trivial.
Input | Dollars | Quarters | Dimes | Nickels | Pennies | |
---|---|---|---|---|---|---|
Case 1 | 317 | 3 | 0 | 1 | 1 | 2 |
Case 2 | 489 | 4 | 3 | 1 | 0 | 4 |
#include <iostream> using namespace std; int main() { int pennies; // (a) cout << "Enter the number of pennies: "; cin >> pennies; cout << pennies << " pennies =" << endl; int dollars = pennies / 100; // (b) pennies = pennies % 100; int quarters = pennies / 25; pennies = pennies % 25; int dimes = pennies / 10; pennies = pennies % 10; int nickels = pennies / 5; pennies = pennies % 5; cout << dollars << " dollars" << endl; // (c) cout << quarters << " quarters" << endl; cout << dimes << " dimes" << endl; cout << nickels << " nickels " << endl; cout << pennies << " pennies" << endl; return 0; }
pennies / 100
that both operands are of type int, so the computer evaluates the division operation with integer arithmetic: 489/100 is 4, and saves it in dollars. The program calculates the numbers of quarters, dimes, and nickels in the same way, where 100 is replaced by 25, 10, and 5, respectively. The program updates the number of pennies with the modular operator: pennies % 100 creates four groups of 100 with 89 pennies leftover or remaining. The values are saved in pennies at the end of each sub-group. After calculating the number of nickels, the number of pennies is the leftover value that higher-value coins cannot represent.