Control Flow: if, else, switch, for, while, and do-while
Control the execution path of C programs using branching and looping constructs, with good habits for readability and correctness.
Inside this chapter
- if and else
- switch Statement
- Loops
- break and continue
- Loop Design Tips
- Real-World Usage Snapshot
Series navigation
Study the chapters in order for the clearest path from C basics to advanced memory, systems, debugging, and real-world development practice. Use the navigation at the bottom of each page to move smoothly through the full tutorial.
if and else
if (score >= 90) {
printf("Grade A\n");
} else if (score >= 75) {
printf("Grade B\n");
} else {
printf("Grade C\n");
}
Nested conditions should stay clear. If conditions become too large, it is often better to extract logic into helper functions.
switch Statement
switch (choice) {
case 1:
printf("Add\n");
break;
case 2:
printf("Delete\n");
break;
default:
printf("Invalid choice\n");
}
break is critical to avoid accidental fall-through, unless fall-through is intentionally used and clearly documented.
Loops
for (int i = 0; i < 5; i++) {
printf("%d\n", i);
}
while (count > 0) {
count--;
}
do {
printf("Runs at least once\n");
} while (0); break and continue
break exits the nearest loop or switch. continue skips the rest of the current loop iteration. Both are useful, but overuse can make logic harder to follow.
Loop Design Tips
- Make loop conditions obvious.
- Avoid modifying the loop variable unexpectedly inside the body.
- Protect against infinite loops.
- Keep loop body focused and readable.
Real-World Usage Snapshot
Control flow drives menus, parsers, device polling, network request processing, simulations, and algorithm implementation. Simple syntax becomes powerful when combined with clear logic design.