0

//My code prints all of the coins //I cannot seem to be able to use the variables that are inside the for loop, outside that loop. //Any Ideas?

int main(void)
{
    float f;
    do
    {
        printf("How much change is owed?\n");
        f = GetFloat();
    }
    while( f < 0);
    {
        double round(double f);
        int c = f * 100;
        for(int quarters = 0 ; quarters == c % 25 ; quarters++)
        {
            int change = c / 25;
            printf("%i\n", change);
        }
        for(int dime = 0; dime == c % 10; dime ++)
        {
            int change = c /10;
            printf("%i\n", change);
        }
        for(int nickle = 0; nickle == c % 5; nickle ++)
        {
            int change = c / 5;
            printf("%i\n", change);
        }
        for(int penny = 0; penny == c % 1; penny ++ )
        {
            int change = c / 1;
            printf("%i\n", change);
        }
    }


}
1

You are running into issues of scope. Very simply put, a variable only exists inside the curly braces that surround it. It will exist to lower levels of code (code blocks bound by curly braces) that the variable is outside of.

So, to use variables outside of a loop, they must simply be created outside the loop. the float f is a perfect example. They need not be loaded at that point, although they should be initialized with something when created, as a best practice.

As another example, you could create change just after f and would be able to use it in all of the for loops without having to create it over and over.

Just remember that the variable will now persist and will continue to contain whatever values are assigned to it until changed.

You would probably benefit from reviewing the class material on scope.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

1
  • OK. That makes sense. Will try it out. Thanks! Feb 12 '16 at 2:32

You must log in to answer this question.

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