0

i'm a little bit confused why does it happening, but i can't iterate through enum variable in my cs50 ide. here is my code:

enum coins 
{
    quarters = 25, dimes = 10,
    nickels = 5, pennies = 1
};
int k = 0;
for (int c = quarters; c <= pennies; c++)
{
    while (n >= c)
    {
        n -= c;
        k ++;
    }
}

it even doesn't come into the 'for' cycle. why and how could it be fixed? thanks :)

2
  • What's the exact error message? Also, for loops over enums probably don't work well for assigned values. So you're writing for (int c = 25; c <= 1; c++), which of course will never run. – Blauelf Jul 19 '18 at 11:53
  • @Blauelf no error, just nothing happens - this loop ignores while execution. Well, i get it now, thx! And how to iterate over sequence in C? – Sonya Mincheva Jul 19 '18 at 13:46
1

Enums are ints with fancy names, so you are doing

for (int c = 25; c <= 1; c++)

which never enters the loop.

This kind of iteration does only work if your values are contiguous.

If you want to iterate, I'd suggest an array instead.

    int coins[] = { 25, 10, 5, 1 };
    for (int i = 0; i < sizeof(coins)/sizeof(*coins); i++)
    {
        int current_coin = coins[i];
        // ...

sizeof(coins)/sizeof(*coins) is size of the whole array divided by the size of one of its elements (*coins is equivalent to coins[0]), resulting in the number of elements.

1

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .