/* THIS WILL COMPILE AND RUN, BUT IT'S A BAD DESIGN */
while (1)
{
scanf("%d", &score);
if
(score == -99) break;
sum += score;
}
A "structured" loop enters at the top and exits at the bottom.
Unstructured loops are harder to read and can not be proven correct.
/* THIS WILL COMPILE AND RUN, BUT IT'S A BAD DESIGN */
notdone = 1
while (notdone)
{
scanf("%d", &score);
if
(score == -99)
{
notdone = 0;
}
else
{
sum +=
score;
}
}
/* THIS IS THE PROPER CONSTRUCTION
Figure 5.10 Sentinel-Controlled while Loop
Compute the sum of a list of exam scores. */
#include <stdio.h>
#define SENTINEL -99
int main(void)
{
int sum = 0, /*
output - sum of scores input so far */
score; /* input - current score */
printf("Enter first score
(or %d to quit)> ", SENTINEL);
scanf("%d",
&score);
while (score != SENTINEL)
{
sum
+= score;
printf("Enter next score (%d to quit)> ", SENTINEL);
scanf("%d", &score);
}
printf("\nSum of exam scores
is %d\n", sum);
return (0);
}
/* AVOID THIS */
while (n != 0 && n > 0)
/* INSTEAD DO THIS */
while (n > 0)
/* AVOID THIS */
n = 1;
while (n >= 0)
{
if (n >= 0)
{
do something here;
}
else
{
when will this execute?
}
}