Chapter 4 – Loops Comprehensive Study Notes
4.1 Loop Concepts and Motivation
- Core metaphor
- Parents driving a baby around the block until the baby sleeps illustrates repeating the same action until a condition becomes false ("baby is awake → keep driving").
- Decision point can be before or after each iteration (top vs. bottom of the street).
- Terminology
- Loop body – statements that run repeatedly.
- Loop expression / decision expression – Boolean test checked each time.
- Iteration – one full execution of the body.
- Q&A highlights from activities
- First baby check: baby was awake → loop begins.
- Number of loops equals the count of times the parents circled until the expression "baby-awake == True" became False.
- Decision point location affects whether the loop executes at least once.
4.2 Loop Basics and Control Flow
- Flowchart anatomy (example: doubling powers of 2 until user enters )
- Initialization:
curPower = 2,userNum = Get next input. - Loop expression:
userNum == 1(iterates while true). - Body: print power, newline, double
curPower, get new input.
- Initialization:
- Key rules
- Expression is evaluated before running the body in a while/for loop.
- Once inside the body, statements run to completion even if the expression would switch to false part-way.
- Common “loop-until-done” pattern: ask user at end of body whether to continue.
- Celsius→Fahrenheit example
- Conversion: .
userChoicecontrols continuation; loop always iterates at least once becauseuserChoiceinitially set to .- Each pass adds to
celsiusValue.
- Getting input before and after loop – avoids dummy initialization.
4.3 More Loop Examples (Sentinel Values & GCD)
- Sentinel value – special terminator not processed in the computation (e.g., list ends with or ).
- Average until sentinel
- Variables:
sum,num,val. - Pseudocode:
val = Get input(may be sentinel).while val > -1→ add tosum, incrementnum, get next.- After loop:
avg = sum / num.
- Variables:
- Counting negatives
countstarts at ; increment wheneverval < 0.
- Finding maximum
- Initialize
max = -1; for each positiveval, ifval > maxthenmax = val. - Order of inputs does not affect final max.
- Initialize
- Euclid’s GCD
- Ensure ; if not, swap.
- Loop while
numA % numB > 0→ rem = numA % numBnumA = numBnumB = rem- Finishes with both variables equal to .
4.4 Looping Times
- Pattern (while version)
- Initialization:
i = 0. - Expression:
i < N. - Update:
i = i + 1(at end of body).
- Initialization:
- Savings-with-interest example
- For years:
currSavings = currSavings * (1 + rate)then print. - Rate might be expressed as percent/100.
- For years:
- First input counts list length
- Example input:
4 10 1 6 3→ loop iterates times.
- Example input:
4.5 Loop Examples Beyond Simple Counting
- Output sequences by tweaking the three parts
- Multiples of from to : init , expression , update .
- Temperature table → step using variable
currC.
- Data analysis pattern
- Maintain running statistic (sum, max, count) updated each iteration.
4.6 Choosing While vs For
- Heuristic table
- Number of iterations known before loop → for.
- Iterations depend on data encountered during loop → while.
- Examples
- “Iterate 100 times” → for.
- “Read until user enters 0” → while.
4.7 Nested Loops
- Definition: loop inside another loop (outer vs. inner).
- Bar-chart example
- Outer
whilereads next integer (terminates on negative). - Inner
forprints one*per unit of magnitude.
- Outer
- Counting inner executions = (#outer iterations) × (#inner iterations per outer pass).
4.8 Code Representation: while
- General syntax (C-style pseudocode)
while (expression) {
// body
}
- Converting flow-chart to code: move initialization above, update at bottom.
- Ancestors example revisited in pure code
curYear = 2020;
numAnc = 2;
while (curYear >= userYear) {
print(curYear, numAnc);
numAnc = numAnc * 2;
curYear = curYear - yearsPerGen; // 20
}
- Infinite-loop pitfalls
- Missing update statement.
- Using wrong operator (
==vs.!=). - Example that forgets to re-read
userNumresults in endless doubling ofnumKids.
4.9 Code Representation: do-while
- Syntax (executes body before expression check)
do {
// body
} while (expression);
- Use case: loop must run at least once (e.g., prompt user, then decide to repeat).
- Example variables:
curCount,userNum; counting runs untiluserNum <= 4.
4.10 Code Representation: for
- Syntax
for (init; expression; update) {
// body
}
Equivalent while:
init;
while (expression) {
// body
update;
}
- Iteration values
for i = 0; i < 6; i = i + 1→ takes .- Loop count = difference between bounds when using
++.
- Looping variable names should be descriptive (e.g.,
currYear,currC). - Savings-interest & average examples re-implemented with
for.
4.11 Loops Summary & Best Practices
- Always identify the three critical parts: init, expression, update.
- Select loop type for readability: for when countable, while otherwise, do-while when at least one iteration is mandatory.
- Guard against infinite loops by ensuring the expression can become false and updates occur.
- Nested loops multiply work; reason about total iterations.
- Use sentinel values to process unknown-length input cleanly.
4.12–4.15 Programming Labs Overview
- 4.12 Convert to Binary
- Loop while x > 0; output ; divide (reverse order of bits).
- 4.13 Varied Amount of Input Data
- Read non-negative integers until negative sentinel.
- Maintain running
sum,count,max; after loop output andmax.
- 4.14 Output Range with +10
- Inputs
low,high; iflow > highoutput error message, else loopvalue += 10.
- Inputs
- 4.15 Countdown Until Matching Digits
- Input between – inclusive.
- While the two digits differ, print number, decrement by .
- Reject input outside range.