Arithmetic Operators
+, -, *, /, and % (remainder).
4 minute read
Big idea
Operators do math on values: +, -, *, /, and % (the remainder).
The idea
| Operator | Means | Example | Result |
|---|---|---|---|
+ | add | 7 + 2 | 9 |
- | subtract | 7 - 2 | 5 |
* | multiply | 7 * 2 | 14 |
/ | divide | 7 / 2 | 3 |
% | remainder | 7 % 2 | 1 |
Two of these surprise everyone at first:
/between two whole numbers throws away the fraction.7 / 2is3, not3.5. The next lesson shows how to keep the.5.%gives what's left over after dividing.7 % 2is1because 2 goes into 7 three times, with 1 left over.
Try it
Change the numbers and press Run.
#include <stdio.h>
int main(void) {
int a = 17, b = 5;
printf("%d + %d = %d\n", a, b, a + b);
printf("%d - %d = %d\n", a, b, a - b);
printf("%d * %d = %d\n", a, b, a * b);
printf("%d / %d = %d\n", a, b, a / b);
printf("%d %% %d = %d\n", a, b, a % b);
return 0;
}output
17 + 5 = 22
17 - 5 = 12
17 * 5 = 85
17 / 5 = 3
17 % 5 = 2Run and edit it in the app.
%% inside printf prints a single % — a lone % would start a format code.
What % is good for
The remainder answers everyday questions:
- Even or odd?
n % 2is0for even numbers,1for odd ones. - Last digit?
n % 10—1234 % 10is4. - Minutes and seconds:
135seconds is135 / 60=2minutes and135 % 60=15seconds.
#include <stdio.h>
int main(void) {
int total = 200;
printf("%d min %d sec\n", total / 60, total % 60);
return 0;
}What does it print? Show the answer
3 min 20 secRun and edit it in the app.
Watch it
Think of it like
Sharing 17 sweets among 5 friends. 17 / 5 is how many each friend gets (3), and 17 % 5 is how many are left in the bag (2).
🕷️ Spidey-sense: Web-shooters hold 7 cartridges and I've got 23.
23 / 7= 3 full reloads,23 % 7= 2 spare. Division tells me the reloads, remainder tells me what's rattling around in my pocket.
Common mistake
Dividing by zero. x / 0 or x % 0 with whole numbers crashes the program — check the divisor first.
What does 29 % 4 give?
Key terms
- Operator — A symbol that does something to values, like
+or%. - Operand — A value an operator works on: in
7 + 2, the operands are7and2. - Remainder (
%) — What's left after dividing whole numbers; also called modulo.
Check yourself
What is 17 / 5 in C, when both are ints?
What is 17 % 5?
How can you tell whether n is even?