Programming Example-2 ~ Make Change
PROGRAMMING EXAMPLE-2: Make Change.
Write a program that takes as input any change expressed in cents. It should then compute the number of half-dollars, quarters, dimes, nickels, and pennies to be returned, returning as many half-dollars as possible, then quarters, dimes, nickels, and pennies, in that order. For example, 483 cents should be returned as 9 half dollars, 1 quarter, 1 nickel, and 3 pennies.
Input Change in cents.
Output Equivalent change in half-dollars, quarters, dimes, nickels, and pennies.
Suppose the given change is 646 cents. To find the number of half-dollars, you divide 646 by 50, the value of a half-dollar, and find the quotient, which is 12, and the remainder, which is 46. The quotient, 12, is the number of half-dollars, and the remainder, 46, is the remaining change.
Next, divide the remaining change by 25 to find the number of quarters. Since the remaining change is 46, division by 25 gives the quotient 1, which is the number of quarters, and a remainder of 21, which is the remaining change. This process continues for dimes and nickels. To calculate the remainder in an integer division, you use the mod operator, %.
Applying this discussion to 646 cents yields the following calculations:
1. Change = 646
2. Number of half-dollars = 646 / 50 = 12
3. Remaining change = 646 % 50 = 46
4. Number of quarters = 46 / 25 = 1
5. Remaining change = 46 % 25 = 21
6. Number of dimes = 21 / 10 = 2
7. Remaining change = 21 % 10 = 1
8. Number of nickels = 1 / 5 = 0
9. Number of pennies = remaining change = 1 % 5 = 1
This discussion translates into the following algorithm:
1. Get the change in cents.
2. Find the number of half-dollars.
3. Calculate the remaining change.
4. Find the number of quarters.
5. Calculate the remaining change.
6. Find the number of dimes.
7. Calculate the remaining change.
8. Find the number of nickels.
9. Calculate the remaining change, which is the number of pennies.
Comments
Post a Comment