Sample Chapter: Loops¶
Learning objectives¶
By the end of this chapter you can:
- Explain what a counting loop does.
- Write one in several languages.
- Relate loop cost to a summation.
Concept¶
A loop repeats a block of code. A counting loop runs once for each value of an index from a start to an end.
Syntax and example¶
Expected output:
Cost of a loop¶
Summing the work done by a loop that runs \(n\) times with cost \(i\) at step \(i\):
\[
T(n) = \sum_{i=1}^{n} i = \frac{n(n+1)}{2}
\]
Step-by-step¶
- Choose the start, end, and step.
- Write the loop header.
- Put the repeated work in the body.
- Run it and compare with the expected output.
Common mistakes¶
Off-by-one errors
range(1, 3) in Python stops at 2. Use range(1, 4) to include 3.
Why does my loop never end?
The loop variable is never updated, or the condition can never become false.
Exercises¶
- Print the numbers 10 down to 1.
- Print the sum of the first 100 integers and check it against \(\frac{n(n+1)}{2}\).
Summary¶
A counting loop repeats work for each index; its total cost is often a sum.