SkinnyG33k SkinnyG33k - 2 months ago 5x
C Question

Why is my while loop not repeating in C?

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.

If I use

while (cents >= 25)
then the terminal prints starting coins and hangs just blinking. If I use
(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! ");
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):


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.