0

I got my greedy program to work and I mainly used for loops. I tried to recreate it with while loops, but I'm doing something wrong. Whenever the GetFloat() line is executed and the user gave a number, the terminal just stops doing anything. This is my loop:

while (owed > quarter)
{
    change++;
}

printf("%f\n", change);

I did declare the variables so that should not be it. Could someone help me please?:)

2
  • this is an example of what is referred to as an infinite loop. your program get stuck at the while loop because once the continuation condition of this loop is evaluated to true, it never becomes false as neither owed nor quarter ever change inside the loop.
    – kzidane
    Commented Nov 1, 2015 at 10:10
  • Great answer, Kareem. Can you change it to an answer instead of a comment? (and delete this comment too?)
    – Cliff B
    Commented Nov 1, 2015 at 20:42

1 Answer 1

1

Credit to Kareem for answering this question, but it has been 4 months and it hasn't been posted as an answer... in the interest of improving the CS50 knowledge base, I'm posting the answer here. (I arrived at this question by searching for unanswered questions to help with involving pset1.)

1     while (owed > quarter)
2 {
3     change++;
4 }

printf("%f\n", change);

Let's start at line 1.

while (owed > quarter)

When your computer evaluates this line, it will be either "true" or "false." If it is false, no big deal; the loop will not run, and you can move on with your code.

But let's see what happens if it evaluates to true. The computer will move on and execute whatever is inside the brackets:

{
    change++;
}

and so it will find your "change" variable and increase it by 1. Then it will proceed back to the original "while" condition to evaluate it again...

But nothing has changed! "owed" is still greater than "quarter." While it's true that "change" is increased by 1, "changed" is not being evaluated.

So the computer will find that "owed > quarter" evaluates to "true" again, and execute the loop a second time... then a third time...

And so on infinitely.

To get your virtual machine to quit running that program without closing your browser, you can press "Ctrl +C."

You must log in to answer this question.

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