atltbone
atltbone

Reputation: 285

Variable used in loop condition not modified in loop body

I'm pretty new to C, but I am just trying to use a for loop to subtract 25 from the value of int change, assuming the value is already greater than 25. The error message I get is

"error: variable 'change' used in loop condition not modified in loop body [-Werror,-Wfor-loop-analysis]"

Which confuses me since don't I modify the variable 'change' in loop body by specifying change -25?

int main(void)
{
    float n;
    do
    {
        n = get_float("How much change do I owe you?: ");
    }
    while (n < 0);

    for (int change = n * 100; change >= 25; change - 25)
    {
        printf("%i", change);
    }
}

Upvotes: 7

Views: 16580

Answers (2)

Stacy Alvey
Stacy Alvey

Reputation: 1

If what you are trying to accomplish is to print out the number of coins needed to make n==0, just know you are currently printing out the end product of the loop, which would be the remainder. The only reason I know this is because I made the same mistake while taking the cs50 course

Upvotes: 0

Uwe Keim
Uwe Keim

Reputation: 40736

(As of request, here is my comment as an answer)

Your loop for (int change = n * 100; change >= 25; change - 25) never modifies the variable change.

You simply subtract 25 from the value of of the variable change, returning the result and immediately discarding it again.

So instead of

change - 25

Use

change -= 25

Which is short for

change = change - 25

Please see the the Wikipedia page about the for loop to learn more about the syntax.

Excerpt from there:

for (initialization; condition; increment/decrement)
    statement

So the third part in the for loop should be the increment/decrement.

Upvotes: 8

Related Questions