M. B. M. B. - 11 months ago 60
C Question

True or False in c programming pertaining to while loop

Can someone explain true false in c programming pertaining to this while loop?

If 0 is false Done=0, and

while (!Done)
is suppose to be true and done = 1 is also true, then how does done=1 cause the loop to "break" or exit?

case '1':
printf("Beverage $8.00\n");
total+= 8;

case '2':
printf("Candy $3.00\n");
total+= 3;

case '3':
printf("Sandwich $5.00\n");
total+= 5;

case '4':
printf("Hot Dog. $2.00\n");
total+= 2;

case '5':
printf("Popcorn $6.00\n");
total+= 6;

case '=':
printf("Your choices are finished.\n");
printf("The total is:$%.2f\n", total);
printf("Please pay the cashier.\n");

printf("I don't understand your choice, please try again.\n");
return (0);

Answer Source

Welcome to StackOverflow M.B.

A while loop in C evaluates whatever is in it as either true or false, before every loop.

One of the guarantees you get when programming in C is that only 0 is false, and everything else is true. That means that foobar is true, 64 is true, -1 is true, and in your case, 1 is true.

Because of this, the ! operator (the not symbol), it changes anything that is true into a 0, and changes a 0 into a 1.

Therefore, what your while loop is really doing is saying:
"While not done"
or "While done is not true"
or "While done is false"
or "While done is 0"

So when your last case statement of '=' is hit, and the code done=1; is run, you code will exit the next time it comes around and checks the condition for the while loop.