Chapter 06 of 24
6. Decisions and loops
Choose first, then repeat
A decision lets a program choose which instructions to run. A loop lets it repeat instructions. Both are controlled by a condition: a question whose answer is either true or false.
- Use
ifto choose an action, for example print a message only whenscore >= 50. - Use a loop when the same task must happen several times.
- Give the loop a starting state, a condition to continue, and an update that moves toward stopping.
Trace a loop by writing the variable values down for each pass. This makes off-by-one errors and loops that never stop easier to spot before adding more complicated logic.
Branching
#include <stdio.h>
int main(void)
{
int score = 85;
if (score >= 90) {
puts("A");
} else if (score >= 80) {
puts("B");
} else {
puts("Keep practicing");
}
return 0;
}
Use switch when selecting among integral or enumeration values:
#include <stdio.h>
int main(void)
{
int choice = 2;
switch (choice) {
case 1:
puts("Start");
break;
case 2:
puts("Settings");
break;
default:
puts("Unknown choice");
break;
}
return 0;
}
Without break, execution generally falls through into the next case.
Repetition
#include <stdio.h>
int main(void)
{
for (int i = 0; i < 5; ++i) {
printf("%d\n", i);
}
int remaining = 3;
while (remaining > 0) {
--remaining;
}
return remaining;
}
for: useful when initialization, condition, and update belong together.while: repeats while a condition is true.do ... while: runs the body at least once.break: exits the nearest loop orswitch.continue: advances to the next loop iteration.
Ensure a loop can make progress toward stopping; otherwise it may never end.
Planning a loop
Before writing a loop, name four things: its starting state, its stopping
condition, how each iteration changes the state, and what should happen when
it stops. For a counting loop, these correspond naturally to the three parts
of for:
int main(void)
{
int sum = 0;
for (int value = 1; value <= 5; ++value) {
sum += value;
}
return sum == 15 ? 0 : 1;
}
Here the initial value is 1, the loop continues through 5, and ++value
moves toward termination. The accumulated result is 15. If the update is
omitted or moves away from the stopping condition, the loop may run forever.
Use while when the number of iterations depends on an event or changing
condition, such as reading until end-of-file. Use do ... while when the
body must run once before testing, as with a menu displayed at least once.
Keep break and continue limited to cases where they make the loop easier
to understand; too many jumps can hide the loop's normal path.
switch is useful for a menu or an enum. Each case label is a possible
value, not a separate scope; use braces around a case's statements when
declaring local variables or to make a multi-step branch clear. Use default
to handle unexpected choices.
Checkpoint: Trace the sum loop by hand and write down value and sum
after each iteration. Then change the limit and predict the result before
running it.
Exercises: sum numbers from 1 to N; find a number using a guessing loop;
print a right triangle of stars.