In: Computer Science
Hints: use if / else if / else... use % and /... use a while loop or a do while loop
example:
Please enter the number of cents, from 1 through 99,
or enter a negative number to quit: 31
Quarters: 1 Dimes: 0 Nickels: 1
Pennies: 1
Please
enter the number of cents, from 1 through 99, or enter a negative
number to quit: 89
Quarters: 3
Dimes: 1 Nickels: 0 Pennies: 4
Please
enter the number of cents, from 1 through 99, or enter a negative
number to quit: 121
Your entered a value outside the
range.
Please enter the number of cents, from 1 through 99, or enter a
negative number to quit: 0
Your entered a value outside the range.
Please
enter the number of cents, from 1 through 99, or enter a negative
number to
quit: 18
Quarters: 0 Dimes: 1 Nickels: 1 Pennies: 3
Your entered a value outside the
range.
Please enter the number of cents, from 1 through 99, or enter a
negative number to
quit: -666
Thanks for using my program. Good
bye.
Steps to follow:
Code:
#include <stdio.h>
void minCoins(int value)
{
// coin value array representing indices 0 - quarters, 1 - dimes, 2 - nickels, 3 - pennies.
int coin_value[4] = {25, 10, 5, 1};
// result array to store number of coins for each coin type in same order
int coin_num[4] = {0, 0, 0, 0};
// using for loop and divide & modulus operator to get number of coins & remaining value respectively
// for every coin type
for (int i = 0; i < 4; i++) {
coin_num[i] = value / coin_value[i];
value = value % coin_value[i];
}
// Output of total no. of coins with each coin type number
printf("Quarters: %d ", coin_num[0]);
printf("Dimes: %d ", coin_num[1]);
printf("Nickels: %d ", coin_num[2]);
printf("Pennies: %d \n", coin_num[3]);
}
int main() {
int num;
while (1) {
printf("Please enter the number of cents, from 1 through 99, or enter a negative number to quit: ");
scanf("%d", &num);
if (num < 0) {
printf("Thanks for using my program. Good bye.");
break;
}
else {
if (num > 0 && num < 100)
minCoins(num);
else
printf("Your entered a value outside the range.\n");
}
}
return 0;
}
Output: