Loops & Control Flow
Loops dictate iteration routines repeating blocks as long as a condition evaluates to true. C supports for, while, and do-while patterns.
1 Loop Structures & Iteration Steps
Choosing the correct loop construct improves code readability:
- for: Best for static iteration sizes where initializers, conditions, and increments are grouped.
- while: Best when the boundary conditions are checked before executing statement blocks.
- do-while: Executes statement blocks first, and then verifies boundary conditions. Always executes at least one time.
2 Loop Control Tracing
Let's run a program printing iterations and checking flow behaviors with loop control actions:
C — Loops & break/continue
▶ Run Code
#include <stdio.h>
int main() {
// For loop demonstration
printf("For sequence: ");
for (int i = 1; i <= 5; i++) {
printf("%d ", i);
}
printf("\n");
// While loop with loop control bypasses
printf("While sequence (skipping 3, stopping at 7): ");
int count = 1;
while (count <= 10) {
if (count == 3) {
count++;
continue; // Skip rest of block, check condition again
}
if (count == 7) {
break; // Terminate loop block completely
}
printf("%d ", count);
count++;
}
printf("\n");
return 0;
}
3 Code Challenge
Challenge: Write a program that computes the factorial of an integer (e.g. `5` -> factorial = 5*4*3*2*1 = 120). Implement this computation using a `while` loop, and print the final result.