49.5k views
5 votes
Use the expression --manyItems (with the -- before manyItems) to rewrite the last two statements of remove (Figure 3.5 on page 132) as a single statement. If you are unsure of the difference between manyItems-- and --manyItems, then go ahead and peek at our answer at the back of this chapter. Use manyItems++ to make a similar alteration

to the add method.

1 Answer

5 votes

Final answer:

The question deals with using pre-decrement and post-increment operators to rewrite two statements in a remove and add method, respectively, in programming into single consolidated statements. For the remove method, use --manyItems in array[--manyItems] = null; for the add method, use manyItems++ in array[manyItems++] = newItem.

Step-by-step explanation:

The question asks how to consolidate the last two statements used in a remove method by using --manyItems. This notation is a decrement operator in many programming languages, and it decrements the variable's value by one. The difference between manyItems-- and --manyItems is that the former is a post-decrement while the latter is a pre-decrement. A post-decrement subtracts one from the variable after the statement is evaluated, whereas a pre-decrement subtracts one before the statement is evaluated. To rewrite the last two statements as one, you would use --manyItems where the original code probably looks something like:

And the single consolidated statement would use pre-decrement:

array[--manyItems] = null; // This both decrements and accesses the correct index in one step.

For the add method, to make a similar alteration, you would use manyItems++ in a single statement instead of after the action. So if the last two statements were:


  • array[manyItems] = newItem; // Adds the new item at the end of the array.

  • manyItems++;

You would combine them like so:

array[manyItems++] = newItem; // This adds the new item, then increments manyItems.

User Jinyu
by
7.9k points