Chapter 4 (pp. 95–132) of Computer Science I.
Topics
| Section | Page | Content |
|---|---|---|
| While Loops | 97 | Condition-first iteration. |
| For Loops | 99 | Counter-based iteration. |
| Do-While Loops | 100 | Execute-then-test. |
| Foreach Loops | 102 | Collection iteration. |
| Other Issues | 103 | Nested loops, infinite loops, common errors, equivalency of loops. |
| Problem Solving With Loops | 106 | Applying iteration to problems. |
| Examples | 107 | For vs While, Primality Testing, Paying the Piper. |
Key Ideas
- All loop forms are equivalent in expressive power; choice is stylistic/clarity.
- Infinite loops and off-by-one errors are the classic failure modes.
- Paying the Piper and nested-loop examples recur across language parts.
- Foreach ties into arrays & collections.
Examples
Summation with while
sum ← 0
i ← 1
while i ≤ n:
sum ← sum + i
i ← i + 1
Accumulates 1..n.
Factorial with for
fact ← 1
for i from 2 to n:
fact ← fact × i
The same result as a while loop — loop forms are equivalent.
In Java
int sum = 0;
for (int i = 1; i <= n; i++) // sum 1..n
sum += i;
long fact = 1;
for (int i = 2; i <= n; i++) // n!
fact *= i;
Citations
[1] Computer Science I, Ch. 4, pp. 95–132.