EN ES
Programming Concept

Loops

While, for, do-while, and foreach loops; nesting, infinite loops, and loop equivalency.

Chapter 4 (pp. 95–132) of Computer Science I.

Topics

SectionPageContent
While Loops97Condition-first iteration.
For Loops99Counter-based iteration.
Do-While Loops100Execute-then-test.
Foreach Loops102Collection iteration.
Other Issues103Nested loops, infinite loops, common errors, equivalency of loops.
Problem Solving With Loops106Applying iteration to problems.
Examples107For 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.