/* Coin-changing program */ #include #include #include const int C1 = 200, C2 = 100, C3 = 50, C4 = 20, C5 = 10, C6 = 5, C7 = 2, C8 = 1; int n1, n2, n3, n4, n5, n6, n7, n8; int ReadInput(int *amount) { int input = 0 ; do { printf("Enter the amount (in pence) to be returned to the user: "); while (scanf("%d", &input) !=1) { scanf("%*s") ; printf("That wasn't a number - please try again: "); } } while (input < 0 ) ; *amount = input ; // Set the value of amount to equal input return EXIT_SUCCESS ; } int CalculateCoins(int amount) { n1 = 0; n2 = 0; n3 = 0; n4 = 0; n5 = 0; n6 = 0; n7 = 0; n8 = 0; int pot = amount; // Total value of coins so far selected. while (pot > 0) { if (pot >= C1) { pot -= C1; ++n1; } else if (pot >= C2) { pot -= C2; ++n2; } else if (pot >= C3) { pot -= C3; ++n3; } else if (pot >= C4) { pot -= C4; ++n4; } else if (pot >= C5) { pot -= C5; ++n5; } else if (pot >= C6) { pot -= C6; ++n6; } else if (pot >= C7) { pot -= C7; ++n7; } else { /* pot >= C8. (Why do we know this?) */ pot -= C8; ++n8; } assert(n1*C1 + n2*C2 + n3*C3 + n4*C4 + n5*C5 + n6*C6 + n7*C7 + n8*C8 == (amount - pot) && pot <= amount); } return EXIT_SUCCESS; } int PrintResult(int amount) { printf("%dp may be returned using the following \n", amount); printf("combination of coins:\n"); if (n1) printf("%4d %dp coins,\n", n1, C1); if (n2) printf("%4d %dp coins,\n", n2, C2); if (n3) printf("%4d %dp coins,\n", n3, C3); if (n4) printf("%4d %dp coins,\n", n4, C4); if (n5) printf("%4d %dp coins,\n", n5, C5); if (n6) printf("%4d %dp coins,\n", n6, C6); if (n7) printf("%4d %dp coins,\n", n7, C7); if (n8) printf("%4d %dp coins.\n", n8, C8); return EXIT_SUCCESS; } int main(void) { int amount =0; if ( ReadInput(&amount) != EXIT_SUCCESS) { printf("Failure in ReadInput\n"); return EXIT_FAILURE; } if ( CalculateCoins(amount) != EXIT_SUCCESS) { printf("Failure in CalculateCoins\n"); return EXIT_FAILURE; } if ( PrintResult(amount) != EXIT_SUCCESS) { printf("Failure in PrintResult\n"); return EXIT_FAILURE; } return EXIT_SUCCESS; }