The answers for b, c, and d in Chapter 4, Exercise 5 are incorrect
The Question
What is the value of each of the following expressions in C89? (Give all possible values if an expression may have more than one value.)
(a) 8 % 5
(b) -8 % 5
(c) 8 % -5
(d) -8 % -5
The correct answers
(a) 3
(b) -3 or 2
(c) 3 or -2
(d) 3 or 2
Explanation
To solve for a % b, we must first look at a / b and at how c89 handles a / b.
a % b can be found using a / b as a starting point. We can say that
a % b = a - (b * (a / b)) (Source: C89 3.3.5)
Solving for (a), where a = 8 and b = 5:
Both a and b are positive integers, so we know that 8 / 5 will result in 1
8 % 5 = 8 - (5 * (8 / 5))
8 % 5 = 8 - (5 * 1)
8 % 5 = 8 - 5
8 % 5 = 3
So what if a or b were negative?
In C89, how negative numbers are handled will be implementation dependent. Specifically, the value will be rounded up or rounded down.
Taking (b) as an example, where a = -8 and b = 5
-8 / 5 evaluates to -1 or -2
Putting it into the equation:
for -1
- 8 % 5 = -8 - (5 * (-1))
- 8 % 5 = -8 - (-5)
- 8 % 5 = -8 + 5
- 8 % 5 = -3
for -2
- 8 % 5 = -8 - (5 * (-1))
- 8 % 5 = -8 - (-10)
- 8 % 5 = -8 + 10
- 8 % 5 = 2
And thus, the answer to (b) is -3 or 2
The answers for b, c, and d in Chapter 4, Exercise 5 are incorrect
The Question
What is the value of each of the following expressions in C89? (Give all possible values if an expression may have more than one value.)
(a) 8 % 5
(b) -8 % 5
(c) 8 % -5
(d) -8 % -5
The correct answers
(a)
3(b)
-3or2(c)
3or-2(d)
3or2Explanation
To solve for
a % b, we must first look ata / band at how c89 handlesa / b.a % bcan be found usinga / bas a starting point. We can say thata % b = a - (b * (a / b)) (Source: C89 3.3.5)
Solving for (a), where
a = 8andb = 5:Both
aandbare positive integers, so we know that8 / 5will result in18 % 5 = 8 - (5 * (8 / 5))
8 % 5 = 8 - (5 * 1)
8 % 5 = 8 - 5
8 % 5 = 3
So what if
aorbwere negative?In C89, how negative numbers are handled will be implementation dependent. Specifically, the value will be rounded up or rounded down.
Taking (b) as an example, where
a = -8andb = 5-8 / 5evaluates to-1or-2Putting it into the equation:
for -1
- 8 % 5 = -8 - (5 * (-1))
- 8 % 5 = -8 - (-5)
- 8 % 5 = -8 + 5
- 8 % 5 = -3
for -2
- 8 % 5 = -8 - (5 * (-1))
- 8 % 5 = -8 - (-10)
- 8 % 5 = -8 + 10
- 8 % 5 = 2
And thus, the answer to (b) is
-3or2