newbieZ
newbieZ

Reputation: 31

What can I do to basically "combine" these for-loops?

Hi, I'm new to C and programming in general, but have heard that code should not be repeated if possible, which makes a lot of sense, however I have no idea how to make this code less repetetive. Any input would be greatly appreciated.

int main(void)
{
    float dollars = 0;
    float real_value = 0; 
    int cents = 0;
    int coin_counter = 0;
    do
    {
        dollars = get_float("change owed: ");
        cents = round(dollars*100);   
    }
    while(dollars<0);

I'd like these four for-loops to maybe be one, if possible?

     for(int i = 0; cents>=25; i++)
     {
         cents = cents - 25;
         real_value = cents;
         coin_counter++;
     }
     for (int i = 0; cents>=10; i++)
     {
         cents = cents - 10;
         real_value = cents;
         coin_counter++;
     }
     for (int i = 0; cents >= 5; i++)
     {
         cents = cents - 5;
         real_value = cents;
         coin_counter++;
     }
     for (int i = 0; cents >= 1; i++)
     {
         cents = cents - 1;
         real_value = cents;
         coin_counter++;
     }
    printf("coins: %i\n",coin_counter);
    printf("leftovers: %f\n", real_value);
}
    

Upvotes: 1

Views: 52

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 311048

All what you need is to make the conditions of the for loops to depend on some variable.

For example

int nominal_value[] = { 25, 10, 5, 1 };
const size_t N = sizeof( nominal_value ) / sizeof( *nominal_value );

for ( size_t i = 0; i < N; i++ )
{ 
    for(int i = 0; cents>=nominal_value[i]; i++)
     {
         cents = cents - nominal_value[i];
         real_value = cents;
         coin_counter++;
     }
}

Pay attention to that it seems this statement

real_value = cents;

does not make a sense. Maybe the body of the inner loop should be changed. For example this statement could be placed after the inner loop or even after the outer loop.

Upvotes: 2

Related Questions