Loops – Comprehensive Study Notes
Loop Concept
A loop is a program construct that repeatedly executes a list of statements (the loop body) while a Boolean expression (the loop condition) is .
When the expression becomes , control proceeds to the first statement after the loop.
Each execution of the body is called an iteration.
Real-life analogy: Parents driving a baby “around the block” until the baby falls asleep.
Decision point: each time the car reaches a landmark (top or bottom of the street) parents check Awake?
If baby is awake drive another loop; if asleep exit.
Key vocabulary
Loop body – statements inside the loop.
Loop condition / expression – Boolean test that controls repetition.
Iteration – one pass through the body.
Sentinel – special value that signals loop termination when processing lists.
Loop Basics
Structure (generic):
initialization
while (expression) { // decision statement
statements // loop body
update // prepares next test
}
continuation
Three canonical components for a counter-controlled (N-times) loop:
Initialization of loop variable (before loop).
Condition using relational operator (top of loop).
Update of loop variable (end of body).
Once control enters the body, execution continues to the body’s end even if the expression would become false mid-body (one-entry, one-exit discipline).
Flow-chart example (powers of 2 until user enters 0):
Variables: , .
Condition: print get next input.
Loop Examples
Summation & Average with Sentinel
Task: read non-negative integers terminated by , output average.
Initialize: , , .
Condition: \text{val} > -1.
Body:
.
.
(get next).
After loop: .
Critical points from participation Q&A:
First input fetched before loop; if negative, body never runs.
initialized to ; each iteration adds the current input value.
counts how many actual values processed (not sentinel).
Counting Negatives
Goal: count how many negative numbers appear in a list ending with .
Condition (A) should be \text{val} < 0.
Counting statement (B): when negative detected.
Finding Maximum in a Positive List (ending with 0)
Initialize so that every positive input is >\text{max} first time.
Condition: \text{val} > 0 (loop until 0).
Update rule (B): if \text{val} > \text{max} then .
Order of inputs does not affect final max.
Looping Until Done (User-Controlled)
Pattern: get initial input before loop, repeat body, get new input at end.
Celsius to Fahrenheit example
Menu choice controls continuation; loop exits when choice .
Each iteration: output current and computed , then increment Celsius by .
Loop iterates at least once because initial value forces true.
Loop Expressions & Relational Operators
Common relational forms: <, \le, >, \ge, ==, \neq.
Design rule: expression describes when to iterate, not when to stop.
Practice prompts:
Iterate while expression .
Iterate while x < 100, , , etc.
Horizontal bar chart program: subtract per loop to print one “-”.
Common Loop Errors
Reversed condition (using instead of ).
Forgetting to update loop variable infinite loop.
Missing new input in body also causes infinite loop (example with doubling ).
Detecting infinite loops: Coral simulator stalls or floods output; user must Pause/Exit.
Looping Times
Typical for counter variable starting at .
Condition for 10 iterations: i<10 (values ).
For 99 iterations starting at : init ; condition i<=99.
Savings account example
For loop executes 10 times, printing balance each year.
Each pass: output , then update .
More Complex Examples
Euclid’s GCD (while version)
If \text{numA}<\text{numB} swap.
Loop while \text{numA} \bmod \text{numB} > 0:
.
; .
When remainder , (or ) is .
Generational Ancestor Counter
Start , .
Loop while .
Output .
(each ancestor has 2 parents).
(one generation back).
Temperature Table (-10 to 40 by 5)
For \text{currC}=-10; \; \text{currC}<=40; \; \text{currC}+!+=5:
.
Print table row.
Nested Loops
Inner loop executes fully for each outer-loop iteration.
Bar-chart example: outer while reads value; inner for prints that many asterisks.
Counting inner executions: .
Programming Constructs for Loops
while Loop
Syntax (C-style):
while (condition) {
// body
}
Use when number of iterations cannot be determined a priori (e.g., sentinel, user quits with 'q').
do-while Loop
Guarantees at least one execution.
do {
// body
} while (condition);
Example variable increments before first test.
for Loop
Compact counter-controlled form:
for (i = start; i < end; i = i + step) {
// body
}
Preferred when iterations pre-computable (loop 100 times, loop times).
Every for can be rewritten as equivalent while; choose for readability.
Example transformations shown side-by-side in transcript.
Choosing Loop Type (Guidelines)
Pre-known count for.
Unknown until runtime / sentinel / convergence while.
Need at least one run regardless do-while.
Code Patterns & Conversions
Converting for while:
for (i=0; i<N; i++) {...}
// equivalent
i = 0;
while (i < N) {
...
i = i + 1;
}
Loop to iterate times after reading input use for.
Loop to keep halving until result < 10 use while (condition unknown in advance).
Lab Overviews (Tasks to Practice)
Convert integer to binary by repeatedly outputting , updating .
Read arbitrary non-negative integers, output average (integer division) and max, sentinel <0.
Output range [first, second] in steps of , with error if second < first.
Countdown from 20–98 until both digits equal (e.g., ); validate input range.
Loops Summary (Key Points)
Loops let programs process data repetitively: averages, counts, maxima.
Infinite loops arise from incorrect conditions or missing updates.
Counter-controlled loop requires init, condition, update.
while, do-while, and for offer specialized syntax but equivalent power.
Nested loops enable multi-dimensional tasks (tables, charts).
Choosing the correct loop type improves readability and maintainability.