The program is ignoring Stop when amt is 0 until after 10 numbers have been entered. The program also doesn’t stop after 10 numbers have been entered. Where is my error?
main() {
int amt;
int tot = 0; /* running total */
int i = 0; /* counts number of times in loop */
while (amt!=0 || i < 10)
{
printf("Enter a number (enter 0 to stop): ");
scanf("%d", &amt);
tot = tot + amt;
i++;
}
printf("The sum of those %d number is %d.\n", i, tot);
}
Your test is happening before
amtis assigned. Thus its results are undefined. This test should be moved to the end of the iteration, i.e. ado/while. Whilst you could assignamtto some non-zero value this feels slightly untidy to me.And surely you mean to use logical AND rather than logical OR? You only want to continue iterating if both
amtis non-zero ANDi<10.Of course, if you did move the test to the end of the iteration then you would have to account for the fact that
ihad been incremented inside the loop.