Opening the reading…
Opening the reading…
DSA FUNDAMENTALS › MATH BASICS
When you write 17 % 5, the % operator gives you the remainder left after dividing 17 by 5. It does not give you the integer division quotient. The quotient is 3, because three complete groups of 5 fit into 17, but the remainder is 2.
int remainder = 17 % 5; // remainder is 2
int quotient = 17 / 5; // quotient is 3int remainder = 17 % 5; // remainder is 2
int quotient = 17 / 5; // quotient is 3What value does 17 % 5 produce?
Checkpoints are not graded. They are here so you catch yourself before the quiz does — stuck, ask the tutor on the right.
The division relationship is dividend = quotient * divisor + remainder. For 17 and 5, substitute the quotient 3 and the remainder 2: 17 = 3 * 5 + 2. The right side becomes 15 + 2, which reconstructs the dividend 17 exactly. That reconstruction is why 2 is the remainder produced by 17 % 5.
DIAGRAM — NOT DRAWN YET
Seventeen counters are shown. Three outlined groups contain 5 counters each, using 15 counters in total. Two counters remain outside the groups and are labeled remainder 2, matching 17 % 5 = 2.
When the divisor is positive, the remainder must be at least 0 and smaller than the divisor. Because the divisor here is 5, the only possible remainder values are 0, 1, 2, 3, and 4. Therefore 5 cannot be the result of 17 % 5, and neither can any value larger than 5. The value 2 fits the required range.
| CONDITION | VALID VALUES |
|---|---|
| At least 0 | 0, 1, 2, 3, 4 |
| Smaller than 5 | 0, 1, 2, 3, 4 |
| 17 % 5 | 2 |
The % operator shares a precedence level with multiplication and division, so it is evaluated before addition. In 17 + 5 % 5, the modulo operation happens first: 5 % 5 is 0, so the expression becomes 17 + 0 and produces 17. Parentheses change that order. In (17 + 5) % 5, the addition happens first, producing 22, and then 22 % 5 produces 2.
int first = 17 + 5 % 5; // 17 + 0 = 17
int second = (17 + 5) % 5; // 22 % 5 = 2Fix this statement so the addition happens before modulo 5.
int result = 17 + 5 % 5;Checkpoints are not graded. They are here so you catch yourself before the quiz does — stuck, ask the tutor on the right.
The divisor in 17 % 5 must not be replaced by 0. There is no valid remainder from dividing by zero, so the expression 17 % 0 is not an ordinary calculation. The right operand of % must be nonzero.