Creating Program to find fewest coins possible from Cent Input

Hello, fairly fresh coder that is learning to create a program that will output the fewest coins possible from any given cent input between 0 and 99. I don't need to add any limits to this code which is why you don't see anything limiting between 0 and 99.

Here is what I have, but I can't seem to figure out how to properly use a modulus to carry over the leftover number from the previous calculation.

I appreciate any advice you can offer! I think I am pretty close, but am at a wall with the % modulus. I know I can calculate the previous number using long arithmetic but I would like to figure out how to make it shorter with the % modifier.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
using namespace std;

int main()
{
    int cents; 
    const int quarter = 25; 
    const int dime = 10;
    const int nickel = 5;
    const int penny = 1;
    
    // Get the amount of cents
    cout << "Please enter an amount in cents less than a dollar." << endl;
    cin >> cents;

    // Calculate how many of each coin you can get from cent input
    int Q = cents % quarter;
    int D = Q % dime;
    int N = D % nickel;
    int P = N % penny;

    // Display the coins you can get from cent input
    cout << "Your change will be:" << endl;
    cout << "Q: " << Q << endl;
    cout << "D: " << D << endl;
    cout << "N: " << N << endl;
    cout << "P: " << P << endl;

    return 0;

}
Line 17: You calculate the number of quarters correctly, but your other calculations are faulty.

e.g. Line 18 You're taking the umber of quarters and using the modulo operator on that to determine the number of dimes. You want to subtract the value of the number of quarters from cents, then use % dime on that.
1
2
3
  cents -= Q * quarter;  // calculate how much is left after issuing quarters
  D = cents % dime;
  //  Do the same for the remaining coins 



Topic archived. No new replies allowed.