CS210 · Block 1 · Lesson 5

Loops

while · do-while · for · break · continue · counting / accumulating / searching patterns
At a glance: Programs that decided things in Lesson 4 now decide them repeatedly. You will meet C's three loop forms (while, do-while, for), the two flow control statements (break and continue), and the three patterns that come up over and over in real code: counting, accumulating, and searching. The Loop Tracer in Section 5 lets you step one iteration at a time and watch variables change. The lab applies the same patterns to an aviation fuel log.
Contents
  1. Lesson Objectives
  2. Assigned Readings
  3. Pre-Class Work
  4. Lesson Materials and Overview
  5. In-Class Work
  6. After Class
1. Lesson Objectives

By the end of this lesson, cadets will be able to:

  1. Implement iterative logic using while, do-while, and for loops. (Outcome 1)
  2. Apply break and continue to control loop flow. (Outcome 1)
  3. Choose appropriate loop constructs for counting, accumulating, and searching tasks. (Outcomes 1, 3)
2. Assigned Readings

Complete before class. These set the vocabulary we will use.

Source Sections Why
Beej-C Chapter 3 (the loop sections: while, do-while, for) All three loop forms with C syntax.
King, C Programming: A Modern Approach Chapter 6 (Loops) Optional deeper dive with more worked examples and pattern catalog.
3. Pre-Class Work
Do this first
Plan on 25 to 40 minutes. The reading is short. Bring a clean head: most of the learning happens by stepping through loops in the In-Class section.

Pre-Class Checklist

1
Read Beej-C Chapter 3 loop sections
Focus on these terms (you should be able to write a one-sentence definition for each):
  • while loop and the difference from do-while
  • for loop and its three parts (init, condition, update)
  • break and continue
  • Infinite loop and off-by-one error
2
Warm up: predict what these print
Read each snippet on paper. Write down what you think it prints. We will check your predictions with the Loop Tracer in class.
int i = 0;
while (i < 3) {
    printf("%d ", i);
    i++;
}
int sum = 0;
for (int i = 1; i <= 4; i++) {
    sum += i;
}
printf("%d\n", sum);
If both feel obvious, the lesson will move quickly. If either felt tricky, plan to focus on the corresponding round in the Loop Tracer.
3
Skim the In-Class section below
The Loop Tracer has 8 rounds. Note that the last two are bug-spotting (off-by-one, infinite loop). You do not need to do anything with the widget yet; just see what it looks like.
4. Lesson Materials and Overview

Lesson 4 taught your programs to decide. Lesson 5 teaches them to decide again and again. Every loop in C is built from the same three parts: an initial state, a condition that says when to keep going, and an update that moves the state forward. The three loop forms just rearrange those parts. Once that clicks, the bugs become predictable and the right loop form for any job becomes obvious.

Jump to
Slides Reference card Anatomy of a loop while do-while for break / continue Three patterns Common bugs DFCS standard

Slides

The Lesson 5 deck walks through the three loop forms, the two flow control statements, the three patterns, and the four common bugs. The deck is the spine of the in class lecture; the Loop Tracer is where you watch every concept play out one step at a time.

Open Lesson 5 slides →

Reference card: print-debugging

A single page reference for finding wrong output bugs in your loops. Keep it open in another tab while you work on Lab 05. Real debugger and valgrind training arrives at Lesson 16, for bugs the source code does not make visible.

Open print-debugging reference card →

The three parts every loop has

Every loop you will ever write has three parts. Identifying them up front is the fastest way to debug a loop that misbehaves.

  • Initialization. The starting state of whatever the loop tracks: a counter, an accumulator, an index, a flag.
  • Condition. The expression checked before (or after) each iteration. While the condition is true, the loop keeps running. When it becomes false, the loop exits.
  • Update. What changes at the end of each iteration so the condition eventually becomes false. If the state never moves toward the exit, you have an infinite loop.

All three loop forms (while, do-while, for) have those three parts. They differ only in where the parts go and when the condition gets checked.

while: check first, then run

A while loop checks its condition at the top of each iteration. If the condition is false the first time, the body never runs at all.

int i = 0;   // initialization
while (i < 5) {   // condition
    printf("%d\n", i);
    i++;   // update
}

Use while when you do not know in advance how many iterations you need: reading until end of input, retrying until success, simulating until a condition is reached.

do-while: run first, then check

A do-while loop runs the body once before checking the condition. The body always runs at least once.

int n;
do {
    printf("Enter a positive number: ");
    scanf("%d", &n);
} while (n <= 0);

Use do-while when the body has to run at least once before you have anything to check. The classic case is input validation: you cannot check whether the user typed a valid number until they have typed something.

Note the semicolon after the while (...) at the end. It is required, and forgetting it is a common compile error.

for: all three parts on one line

A for loop puts initialization, condition, and update on the same line. The body is just the body. This is C's loop of choice when you know how many iterations you want.

for (int i = 0; i < 5; i++) {
    printf("%d\n", i);
}
Part of for (a; b; c) When it runs
a (init) Once, before the first iteration.
b (condition) Before each iteration (including the first). If false, the loop exits.
c (update) After each iteration, before the next condition check.

The variable declared in the init part (here int i) is scoped to the loop. It does not exist after the loop ends. This is what you want; it makes scoping bugs harder.

break and continue: redirecting flow

break exits the loop immediately. Control jumps to the first statement after the loop's closing brace. Use it when you have found what you were looking for and want to stop early.

for (int i = 0; i < n; i++) {
    if (a[i] == target) {
        found_at = i;
        break;   // stop searching
    }
}

continue skips the rest of the current iteration and jumps to the next iteration's condition check. The loop keeps running; only this trip through the body is cut short.

for (int i = 1; i <= 10; i++) {
    if (i % 2 == 0) {
        continue;   // skip evens
    }
    sum += i;
}
Use sparingly
Both break and continue hide control flow. A reader has to look inside the body to know when the loop exits, instead of just reading the condition. Use them when they make the code clearer (early-exit searches, skip-the-bad-cases filters) but do not reach for them as the first solution.

The three loop patterns you will use constantly

Almost every loop you write in CS210 fits one of three patterns. Identifying which pattern you need is the first design decision.

Pattern What it tracks Typical loop form
Counting A counter (how many times). Print a table, loop N times, walk an array of known size. for (the count goes in the header).
Accumulating A running total or running max / min. Initialize the accumulator before the loop. for over a known range or while while-more-input.
Searching A flag or index that says "found it." Set a sentinel value before the loop; update and break on the first match. for with an early break.

The lab tonight uses all three: a do-while to validate input, a counting for to read N flight entries, and accumulators tracking total fuel, total hours, and the maximum burn flight.

Four bugs that bite every new C programmer

Off-by-one
You wrote i < 5 but you wanted the loop to include 5. Or you wrote i <= n when iterating an array of size n. The body runs one too many or one too few times.
Fix: Always trace the first and last iteration by hand. What is i on entry? What is i on the last iteration the body runs? Compare to what you wanted.
Infinite loop
The loop variable never moves toward the exit. The condition stays true forever; the program hangs.
Fix: If your terminal hangs on a loop, press Ctrl+C to kill the program. Then check: does something inside the body move the loop variable toward the false case?
Accumulator not initialized
You forgot to set int sum; to 0 before the loop. C does not zero locals for you; sum holds whatever bits happened to be there. Output is a huge garbage number, and worse, it changes between runs.
Fix: Always initialize. int sum = 0; Never int sum; when you mean zero.
Stray semicolon after for(...)
You typed for (int i = 0; i < 5; i++); with a semicolon right after the parentheses. That semicolon is the loop body. Your real body (the next block) runs exactly once with i = 5 after the empty loop finishes. The compiler does not warn you.
Fix: Never put a semicolon directly after for (...) or while (...). The opening brace goes there.

DFCS C Programming Standard

Loops introduce five rules from the DFCS C Programming Standard. The standard is the course style guide; you can find the full text in the Resources section.

  • §7.3 — no ++ or -- inside a complex expression. Increment on its own line.
  • §7.5 — no single line loops. Always use braces, even when the body is one statement.
  • §7.6 — avoid break in loops. (Inside switch is fine and expected.) Most search loops can be rewritten with a flag in the condition.
  • §7.7 — avoid continue. Wrap the work in an if instead.
  • §7.8 — never use goto.

The two that need the most care: §7.6 and §7.7. break and continue work, you will see them in real code, and you need to read them. The standard is not zero tolerance. It is no overuse. Reach for the cleaner alternative first; use the keyword only when it is genuinely clearer than the rewrite.

5. In-Class Work

In-Class Checklist

  • Lecture: anatomy, three forms, break / continue, patterns, bugs. ~25 minutes. Slides + worked examples.
  • Loop Tracer walkthrough. ~20 minutes. Step through 8 rounds: while, for, do-while, nested, break, continue, off-by-one bug, infinite-loop bug.
  • Lab 05: VFR Fuel Log. ~30 minutes. Read flight entries; print totals, average, max-burn flight, and count over threshold.

Loop Tracer

Step through each round. Watch the loop variable change, watch the accumulator grow, watch break and continue redirect the flow. The state pane on the right tracks everything.

Before you begin

Enter your name. It will appear on the completion screen so you can include it in your screenshot for the Blackboard reflection quiz.

CS210 Lesson 5 · Loop Tracer

Step through each iteration. Watch the loop variable change, watch the accumulator grow, watch break and continue redirect the flow. The right pane shows the program's state after each step.
Round 0 of 8
Section 1: Basic loop forms
Current round
Loading...
How this works: The yellow highlight on the left shows which line C is about to execute. Click Step to advance one line at a time, or Run to end to play the rest of the loop through. The right pane tracks every variable and the output buffer. When a loop exits, the reason (condition false, break, end of range) appears in the state pane.

Lab 05: VFR Fuel Log

Read a flight log from stdin and report summary statistics. Each entry is one flight: hours flown and gallons burned. You decide which loop forms to use and which loop patterns each summary needs.

Lab logistics
  • Autograded on Gradescope.
  • 3 graded submissions.
  • Worth 2 points. Due before Lesson 6.

Open the README in your repo for the full spec, the input and output format, the exact strings to print, and the test cases.

6. After Class
  • Finish Lab 05 if you did not complete it in class. Submit through GitHub Classroom before Lesson 6.
  • Read Beej-C Chapter 4 (Functions) for Lesson 6.
  • Replay the Loop Tracer. Try predicting each round's output before pressing Run.
  • Heads up: Quiz 2 at Lesson 7 covers Lessons 5 and 6 together.
Need help? Schedule EI with your instructor. Bring specific code or specific screenshots, and the exact error message or output you do not understand. Specific questions get unstuck quickly.