Skip to content

Chapter 4 Exercise 5 - b, c, and d are incorrect #140

Description

@TheLastGinger

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions