123
123

Reputation: 8951

Calculate Change Without If/While/For Statement or any data structures

I am trying to write a program that generates the minimum amount of change (quarters, nickels, dimes, pennies), but with the stipulation that I can't use any kind of if, for, while statements.

I'm sure this is possible, but I'm extremely limited, and can't seem to figure out how to make this work without breaking the rules.

The following code works, accept when it runs into a value of 0, and then it breaks while trying to use the modulus on 0 ( I think):

#include <iostream>

int main() {

    int cents;

    std::cout << "Enter an amount in cents less than a dollar:" << std::endl;
    std::cin >> cents;

    int quarters = cents/25;
    int remainder = cents % (quarters*25);
    int dimes = remainder/10;
    remainder = remainder % (dimes*10);
    int nickels = remainder/5;
    remainder = remainder % (nickels*5);
    int pennies = remainder/1;

    std::cout << "Your change will be: " << "\n Q: " << quarters << "\n D: " << dimes << "\n N: " << nickels << "\n P: " << pennies;

    return 0;
}

Upvotes: 0

Views: 173

Answers (3)

Matt
Matt

Reputation: 2802

To do this without using if you can to shrink cents by the found coins and continue from there. For example:

int quarters = cents / 25;
cents -= quarters * 25;

Continue like that.

Upvotes: 1

123
123

Reputation: 8951

You can do this without multiplying each coin by its number of occurrences. (The modulus does what you're trying to do naturally anyways.)

int quarters = cents/25;
int remainder = cents % 25;
int dimes = remainder/10;
remainder = remainder % 10;
int nickels = remainder/5;
remainder = remainder % 5;
int pennies = remainder/1;

This way, you will not be using modulus on the number 0 in any situation.

Upvotes: 4

xinaiz
xinaiz

Reputation: 7788

In this line:

    remainder = remainder % (dimes*10);

You allow remainder to become 0. That will cause division by zero here:

    int nickels = remainder/5; //0
    remainder = remainder % (nickels*5); // modulo 0 % 0

Upvotes: 1

Related Questions