The problems lies here:
// What you see: // What the compiler sees:
while (amt >= 20) while (amt >= 20)
amt -= 20; amt -= 20;
i = i + 1; i = i + 1;
The result of that code will be to set i
to one (assuming it's originally zero, which it is in your case) no matter what value is in amt
.
By default, the body of a while
(or if
or for
...) is a single statement. You can give it a group of statements but you do that by enclosing them in braces:
while (amt >= 20) {
amt -= 20;
i = i + 1;
}
In addition, you upper bound checks are not necessary here. For example, the only way to reach:
while (amt >= 10 && amt <= 20)
is if amt
is already less than 20
. Otherwise it never would have left the previous loop. So you code can probably be better written as:
#include <stdio.h>
int main (void) {
int amt, twenties = 0, tens = 0, fives = 0, ones = 0;
printf("Enter a dollar amount : ");
if (scanf("%d" , &amt) != 1) {
fprintf(stderr, "Invalid input\n");
return 1;
}
if (amt < 0) {
fprintf(stderr, "Negative input\n");
return 1;
}
while (amt >= 20) { amt -= 20; twenties++; }
while (amt >= 10) { amt -= 10; tens++; }
while (amt >= 5) { amt -= 5; fives++; }
ones = amt;
printf("$20 bills : %d\n", twenties);
printf("$10 bills : %d\n", tens);
printf(" $5 bills : %d\n", fives);
printf(" $1 bills : %d\n", ones);
return 0;
}
You'll notice some other changes such as more descriptive variable names, formatting, user input checking, and keeping code small. These are not technically necessary but they are the result of a great many years of experience in writing (and reading code).
As an aside, you can also do this without repeated subtraction, by using integer division and remainders:
#include <stdio.h>
int main (void) {
int amt;
printf("Enter a dollar amount : ");
if (scanf("%d" , &amt) != 1) {
fprintf(stderr, "Invalid input\n");
return 1;
}
if (amt < 0) {
fprintf(stderr, "Negative input\n");
return 1;
}
int twenties = amt / 20; amt = amt % 20;
int tens = amt / 10; amt = amt % 10;
int fives = amt / 5; amt = amt % 5;
int ones = amt;
printf("$20 bills : %d\n", twenties);
printf("$10 bills : %d\n", tens);
printf(" $5 bills : %d\n", fives);
printf(" $1 bills : %d\n", ones);
return 0;
}