Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

My function ReturnChange is supposed to take in change, coins array (int Coins[] = {100, 50, 20, 10, 5};) p.s they are in cents, and numCoins array (int NumCoins[] = {10, 10, 10, 10, 10};) and calculate the change. The change should be in coins. If coins finish i.e num coins than alternative coins have to be used.

private static int ReturnChange(double change, int[] Coins, int[] numCoins) {

    int i = 0;
    int totalcoins = 0;
    change = change * 100;
    do {

        totalcoins++;
        change -= 100;

    } while (change >= 100);
    System.out.println("1 dollar x " + totalcoins + "");
    i++;
    int coinsfifty = 0;
    do {
        coinsfifty++;
        change -= 50;

    } while (change >= 50);
    System.out.println("50 cents x " + coinsfifty + "");
    i++;
    int coinstwenty = 0;
    do {
        coinstwenty++;
        change -= 20;

    } while (change >= 20);
    System.out.println("20 cent x " + coinstwenty + "");
    i++;
    int coinsten = 0;
    do {
        coinsten++;
        change -= 10;

    } while (change >= 10);
    System.out.println("10 cent x " + coinsten + "");
    i++;
    int coinsfive = 0;
    do {

        coinsfive++;
        change -= 5;
    } while (change >= 5);
    System.out.println("5 cent x " + coinsfive + "");
    return 0;

}

the output when 4 is passed as change is :

1 dollar x 4
50 cents x 1
20 cent x 1
10 cent x 1
5 cent x 1

the output when 2.5 as example is passed in change:

1 dollar x 2
50 cents x 1
20 cent x 1
10 cent x 1
5 cent x 1

The problem: Need the others such as 50 cents etc to display zero in output 1, and display 0 for 20 cent onwards in output 2 and not one.

share|improve this question

1 Answer 1

up vote 0 down vote accepted

Well, you shouldnt've used do-while.
It's logically wrong since the code inside 'do' always runs at least once.

Simply replace your do-whiles with while like:

do {
    totalcoins++;
    change -= 100;
} while (change >= 100);

to

while(change >= 100) {
    totalcoins++;
    change -= 100;
}
share|improve this answer
    
i swear i used while it didnt work, i used it again after u mentioned it it works!!! i think i didnt remove the semi colon. thanks for yuor reply. may god increase your knowledge. –  Shuyaib Abdullah Aug 17 '13 at 8:15

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.