I have a problem with my code for "greedy.c". Essentially, the user is asked to enter an amount, but when the user enters an amount other than 0, the program stops and does not function any further, and I have to exit it using Ctrl-C. I have tried this using the Ubuntu host and the CS50 appliance, and the same crashing behaviour happens on both.

Here is the snippet of the code that I think is causing the problem. I reckon myself that the code is valid (but it may be that I've mainly programmed before in Java), but there may be an error in it that stops it from working.

#include <cs50.h>
#include <stdio.h>

int main(void)
    float amount = 0;
    while (amount <= 0) {
        printf("Change owed = $");
        amount = GetFloat();
        printf("%G", amount);

While the user is able to input the floating-point number, the program hangs, and the amount is not printed afterwards, like it is supposed to do. The terminal output and my code

Honestly, I have no idea why this is not working, but if anyone can help me, this will be appreciated.

Many thanks in advance, Jack

  • The problem is probably in the part of the while loop that isn't shown. However, you have another issue. Assuming you have the same do/while loops for nickels and pennies, you're going to have 4 extra coins no matter what. I'll let you work through your code with paper and pencil to see why this is so. A do/while loop ALWAYS executes at least once. A while loop must pass the conditional test every time before it executes the loop. – Cliff B Jul 17 '15 at 21:07
  • Thanks a lot for your suggestion. I have decided to use modulo now, as it will result in a cleaner solution that doesn't rely on loops. I probably won't need any help with this, but I'll post again if I need help. – jackyboy633 Jul 18 '15 at 19:01

Your do/while loop executes while amountInt >=25 (and other values). But you never update its value, so it's always going to be >= than the value it had when it entered the loop. That's why you get an infinite loop. The program doesn't really "hang", it's still executing your loop

  • I must be slipping. How did I miss that? You're using amount and amountInt for the same purpose when you shouldn't. Irene is absolutely on target. – Cliff B Jul 18 '15 at 7:39
  • Oh no! How did I miss that! Maybe, I should just read my code a little more! Thanks a lot to both of you, you've helped me a lot with my (admittedly very schoolboyish) error. ;-) The input works, there are a few logical errors that I have identified, but I should be able to continue on my own now. Thanks again, and I will make sure I name my variables correctly in the future! – jackyboy633 Jul 18 '15 at 18:49

You must log in to answer this question.

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