Question

I'm just getting into C and I am having some troubles. I'm having a heck of a time figuring out why this while loop won't repeat. I made the same loop in JavaScript and it repeats out the proper output. http://jsfiddle.net/rFghh/

If I use while (cents >= 25) then the terminal prints starting coins and hangs just blinking. If I use <=25 (as below) it prints one iteration. Any idea's on what i'm doing wrong??

/**
 * Greedy, given a change amount, figures out the min number of coins needed
 */

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

int main(int argc, char const *argv[])
{
    // declare variables
    int cents = 0;
    int coins = 0;

    // ask user for amount of money, accepts a float value
    // convert input to cents and round to nearest int
    printf("O hai! ");
    do 
    {
        printf("How much change is owed? ");
        cents = round(100 * GetFloat());
    // if input is negative then ask again
    } while (cents <= 0);

    printf("Starting Cents: %d, coins are: %d\n", cents, coins);

    // Check if you can use a quarter
    while (cents <= 25);
    {
        printf("Cents before decrement: %d\n", cents);
        cents = cents - 25;
        printf("Cents after decrement: %d\n", cents);
        coins = coins + 1;
    }

    printf("FINAL Cents: %d, coins are: %d\n", cents, coins);

    return 0;
}



jharvard@appliance (~/cs50/Week_1/pset1): make greedy && ./greedy
clang -ggdb3 -O0 -std=c99 -Wall -Werror    greedy.c  -lcs50 -lm -o greedy
O hai! How much change is owed? 1.25
Starting Cents: 125, coins are: 0
Cents before decrement: 125
Cents after decrement: 100
FINAL Cents: 100, coins are: 1
jharvard@appliance (~/cs50/Week_1/pset1): 
Was it helpful?

Solution

The code does not do what you think it does. This line:

while (cents <= 25);
{ ::: }

is equivalent to this:

while (cents <= 25)
{
    ;
}
{ ::: }

So that will iterate forever executing an empty-statement that never changes cents. Fix it by removing the semicolon, and by reevaluating your logic.

OTHER TIPS

You have a semi-colon at the end of while statement: -

while (cents <= 25);  <-- Here's the semi-colon. Remove it.

Your check for quarters needs to be fixed. This should actually probably be a separate function, but the quick fix would be:

while (cents >= 25)  //should be greater than or equal to and get rid of semicolon 
{
    printf("Cents before decrement: %d\n", cents);
    cents = cents - 25;
    printf("Cents after decrement: %d\n", cents);
    coins++;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top