M. B. M. B. - 1 month ago 13
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?

done=0;
while(!done)
{
c=getchar();
switch(c)
{
case '1':
printf("Beverage $8.00\n");
total+= 8;
break;

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

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

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

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

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

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

Answer

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.