Repeat code automatically using loops, iteration counters, break, and continue statements.
1. The Hook Suppose your athletics coach tells you to run 10 laps around the college track ground. You start at lap 1, run around, count lap 2, run around, and stop when lap count reaches 10.
In programming, when you need to repeat a task multiple times, you use a Loop!
2. The 3 Loop Structures in C
1. `for` Loop: Best when you know the exact number of iterations in advance (for (int i = 1; i <= 5; i++)).
2. `while` Loop: Pre-test loop. Checks condition BEFORE executing body.
3. `do-while` Loop: Post-test loop. Executes body AT LEAST ONCE before checking condition.
3. Code Blueprint
#include <stdio.h>int main() { printf("Counting 1 to 5 using for loop:\n"); for (int i = 1; i <= 5; i++) { printf("Iteration %d\n", i); } return 0; } ```
4. Dry Run Trace
- i = 1: 1 <= 5 (True) -> Prints Iteration 1 -> i++ (i becomes 2).
- i = 2: 2 <= 5 (True) -> Prints Iteration 2 -> i++ (i becomes 3).
- ...
- i = 6: 6 <= 5 (False) -> Loop terminates!
5. Summary Today you learned how to automate repetitive tasks using loops!
C Runner