## Invitation to Computer Science 8th Edition

Published by Cengage Learning

# Chapter 2 - 2.3 - Examples of Algorithmic Problem Solving - Practice Problems - Page 64: 4

#### Answer

The original algorithm fails when b < 0 because count is never less than b. If b < 0, change the value of b to -b, but set the value of a variable called bnegative to YES to remember that b was negative. After the product is computed, the sign of product will be incorrect if b was negative, so change the sign. Here is a pseudocode version that works for all integer values of a and b: Get values for a and b Set the value of bnegative to NO If (either a = 0 or b = 0) then $\ \ \ \$ Set the value of product to 0 Else $\ \ \ \$ If b < 0 then $\ \ \ \ $$\ \ \ \ Set the value of b to -b \ \ \ \$$\ \ \ \$ Set the value of bnegative to YES $\ \ \ \$ Set the value of count to 0 $\ \ \ \$ Set the value of product to 0 $\ \ \ \$ While (count < b) do $\ \ \ \ $$\ \ \ \ Set the value of product to (product + a) \ \ \ \$$\ \ \ \$ Set the value of count to (count + 1) $\ \ \ \$ End of the loop If (bnegative = YES) then $\ \ \ \$ Print the value of -product Else $\ \ \ \$ Print the value of product Stop

#### Work Step by Step

The original algorithm fails when b < 0 because count is never less than b. If b < 0, change the value of b to -b, but set the value of a variable called bnegative to YES to remember that b was negative. After the product is computed, the sign of product will be incorrect if b was negative, so change the sign. Here is a pseudocode version that works for all integer values of a and b: Get values for a and b Set the value of bnegative to NO If (either a = 0 or b = 0) then $\ \ \ \$ Set the value of product to 0 Else $\ \ \ \$ If b < 0 then $\ \ \ \ $$\ \ \ \ Set the value of b to -b \ \ \ \$$\ \ \ \$ Set the value of bnegative to YES $\ \ \ \$ Set the value of count to 0 $\ \ \ \$ Set the value of product to 0 $\ \ \ \$ While (count < b) do $\ \ \ \ $$\ \ \ \ Set the value of product to (product + a) \ \ \ \$$\ \ \ \$ Set the value of count to (count + 1) $\ \ \ \$ End of the loop If (bnegative = YES) then $\ \ \ \$ Print the value of -product Else $\ \ \ \$ Print the value of product Stop

After you claim an answer you’ll have 24 hours to send in a draft. An editor will review the submission and either publish your submission or provide feedback.