CT Week 4: While Loops (Iteration)
0. Prerequisites
NOTE
What you need to know:
- Conditionals:
Truekeeps the loop running,Falsestops it.- Variable Update:
i = i + 1.
Quick Refresher
- Loop: Repeating a block of code multiple times.
- While Loop: Keeps running as long as the condition is True.
- Infinite Loop: A loop that never stops (Bad!).
1. Core Concepts
1.1 Anatomy of a Loop
- Initialization: Setting up variables before the loop. (
i = 0). - Condition: The gatekeeper. (
while i < 5). - Body: The code to repeat. (
Print i). - Update: Changing the variable so the condition eventually becomes False. (
i = i + 1).
1.2 Flow of Execution
- Check Condition.
- If True Run Body Run Update Go back to Step 1.
- If False Exit Loop.
2. Pattern Analysis & Goated Solutions
Pattern 1: The “Counter” Loop (Standard)
Context: “How many times does this run?” Code:
i = 0
while i < 5:
Print i
i = i + 1
TIP
Mental Algorithm (Trace):
- Init: i=0.
- Check: ? Yes. Print 0. Update i=1.
- Check: ? Yes. Print 1. Update i=2. …
- Check: ? No. Stop.
- Result: Prints 0, 1, 2, 3, 4. (Runs 5 times).
Pattern 2: The “Accumulator” (Summing)
Context: “What is the final value of S?” Code:
i = 1, S = 0
while i <= 3:
S = S + i
i = i + 1
TIP
Mental Algorithm:
Step i Condition () S () Init 1 - 0 Loop 1 2 True Loop 2 3 True Loop 3 4 True Stop 4 False - Answer: S = 6.
Pattern 3: Infinite Loop Detection
Context: “Does this loop terminate?” Code:
i = 10
while i > 0:
Print i
i = i + 1 <-- Mistake!
TIP
Mental Algorithm:
- Check Direction: Condition is
i > 0. We start at 10.- Check Update:
iincreases (11, 12, 13…).- Logic: Will increasing numbers ever be less than 0? No.
- Result: Infinite Loop.
3. Practice Exercises
- Trace:
i=0.while i < 3: i = i + 2. Final i?- Hint: 0 2 4. Stops because . Final 4.
- Logic:
while False:…?- Hint: Never runs. Body skipped.
- Count:
i=10.while i > 0: i = i - 1. How many runs?- Hint: 10, 9, …, 1. Runs 10 times.
đź§ Level Up: Advanced Practice
Question 1: Loop Termination
Problem: while(A > B) { A = A - 1 }. When does it stop?
Logic:
- It stops as soon as
Abecomes equal toB(assuming integers and A starts > B). - Trap: If
Astarts <B, it never runs. - Trap: If
Ais float,A == Bmight be missed due to precision, leading to infinite loop? (In pseudocode usually exact).
Question 2: Infinite Loop Detection
Problem:
X = 0
While (X < 10) {
Print X
If (X == 5) { X = X - 1 }
X = X + 1
}Trace:
- 0, 1, 2, 3, 4, 5.
- At 5:
Xbecomes 4. ThenXbecomes 5. - Loop goes back to 5.
Xbecomes 4. Then 5. - Result: Infinite Loop oscillating between 4 and 5.
Question 3: Aggregation in Loop
Problem: Calculate average of positive numbers. Logic:
Sum = 0, Count = 0
While (Pile not empty) {
Read X
If (X > 0) {
Sum = Sum + X
Count = Count + 1
}
}
Avg = Sum / CountTrap: Division by zero if Count is 0 (no positive numbers). Always check If Count > 0 before dividing.