
What is the smallest number of coins (or notes) that are required to give a specified amount of change? This is the next problem we will address.
To solve this problem we use basically the same process a shop keeper would when giving change to customers. That is we look for the largest denomination coin/note that is less than the amount of change still required to be paid. We repeat this process until all the change is paid.
package com.learnjava.math; import java.util.Scanner; public class MoneyBreakdown { /** * @param args */ public static void main(String[] args) { final int[] denominations = { 500, 200, 100, 50, 20, 10, 5, 2, 1 }; Scanner scanner = new Scanner(System.in); // Get the amount to breakdown from user System.out.print("Enter amount (in cents): "); int amount = scanner.nextInt(); // Determine how many of each denomination are required int[] count = breakdown(denominations, amount); // Output the result for (int i=0; i<denominations.length; i++) { if (count[i]>0) { System.out.println(count[i]+" x "+denominations[i]); } } } private static int[] breakdown(int[] denominations, int amount) { int[] count = new int[denominations.length]; // Loop through each denomination (starting at largest) for (int i=0; i<denominations.length; i++) { // Use one of that denomination until we need something smaller while (amount>=denominations[i]) { count[i]++; amount -= denominations[i]; } } return count; } }
I don’t understand the denominations array
The denominations array is used to represent all the denominations of currency available to make up the change, and the values represent cents. In this example it contains 500 ($5), 200 ($2), 100 ($1), 50, 20, 10, 5, 2, 1. The breakdown on change will only contain denominations that appear in that array.
If you require different denominations then you will need to change the values in that array. Let me know if you need a hand.
i need helped with my assgn. java change breakdown.
please helped
What problem are you having exactly?
how to run it
You will need to download the code as MoneyBreakdown.java and compile that
In the code this part:
int[] count = breakdown(denominations, amount);
Could please explain it? Couldnt really understand the breakdown(denominations, amount) and why its assigned to an array called count.
Thanks 🙂
The breakdown() method loops through the available denominations and returns the number of each denomination used to make up amount. count is the array return containing the ‘count’ of each denomination.
eg. breakdown([1,5,10], 57) would return [2,1,5]
Which translates to 2 x 1, 1 x 5, 5 x 10
hi i have a class assignment of a coke machine that all beverages cost 1.00 but only takes 5, 10, 25, 50 coins and should reject anything odd like 33 cent I need help with this part of the program.