Arithmetic and Integer Division
Work out a receipt
Variables let the program remember numbers. An expression combines values to calculate another value, such as items * price + fee. The symbols that do the work are operators.
| Operator | Meaning | Example |
|---|---|---|
+ | Add | 3 + 2 |
- | Subtract | 3 - 2 |
* | Multiply | 3 * 2 |
/ | Divide | 7 / 2 |
% | Integer remainder | 7 % 2 |
In the receipt below, multiplication has higher precedence than addition, so items * price + fee groups as (items * price) + fee. Multiply the item count by the price, then add the fee. Precedence determines grouping; it is not a general rule about which operand C evaluates first.
#include <stdio.h>
int main(void) {
int items = 3;
int price = 4;
int fee = 2;
int total = items * price + fee;
printf("Total: %d\n", total);
return 0;
}
Run the program and check that it prints Total: 14. The expression is evaluated when total is initialized. It is not a formula that automatically recalculates whenever another variable changes.
Whole groups and leftovers
#include <stdio.h>
int main(void) {
int groups = 7 / 2;
int leftover = 7 % 2;
printf("Groups: %d, leftover: %d\n", groups, leftover);
return 0;
}
With two integer operands, / gives an integer result: 7 / 2 is 3. The % operator answers a different question: 7 % 2 leaves 1. Think of seven items packed two per group: three full groups and one leftover.
For positive numbers, this drops the fractional part. More generally, integer division truncates toward zero, so a negative fractional result loses its fractional part too. Never divide or take a remainder by integer zero; C does not define a valid result.
Parentheses can change the grouping: 3 + 2 * 4 gives 11, but (3 + 2) * 4 gives 20. They make your intended calculation clear.
The next lesson shows how to request fractional division. Later, total += fee; will be useful shorthand for total = total + fee;: both add to a value that must already be initialized.