Pretest Logic controlled loops - While loops
General information
- While loops execute 0 or more times.
- While loops have 1 or more loop control variables.
- The data type of the loop control variable can be any legal type;
including float.
- While loops should have at least 1 comparison for each loop control
variable.
- Inside the body of the while loop, there should be at least one statement
to change a loop control variable. There should be at least one
statement for each loop control variable.
- The comparison expressions can be simple (x < 10) or compound
((x < 10) && (x > 0)).
- While loops should be used whenever the code in the body of the loop
only needs to execute under certain conditions but may not need to
execute at all.
Basic Outline of a while loop.
while (some expression evaluates to true)
single_statement;
while (some expression evaluates to true)
{
statement(s);
}
Examples
count = 0;
while (count < 20)
{
printf("\n%d ", count);
count = count + 2;
}
scanf("%d", &count);
while (count < 20)
{
printf("\n%d ", count);
count = count + 2;
}
scanf("%d", &value);
while (value < 0)
{
printf("\nError - try again. Value must be >= 0");
scanf("%d", &value);
}