Learning outcomes
By the end of this lecture, you should be able to:- explain why loops are needed
- distinguish repetition from selection (
if) - trace iterative logic using state tables
- recognize loop-control variables
Why this week matters
In Week 2, you learned conditions and expressions.In Week 3, you use them repeatedly with loops. Without loops:
- same statement must be written many times
- code becomes long and error-prone
- concise code
- easier updates
- cleaner logic for counting and processing lists/strings
Repetition in daily coding
Common tasks requiring loops:- print 1 to 100
- sum first
nnumbers - generate multiplication table
- scan each character in a string
- run input validation until correct input is entered
Iteration mindset
Every loop has 4 parts:- initialization
- condition check
- body execution
- update (move toward stop condition)
Manual dry-run framework
For each iteration, track:- current values (
i,sum, etc.) - condition result (
True/False) - action taken in body
- updated values
Example without loop (problem)
Example with loop (idea preview)
Exam hints and traps
- Loop question may hide a missing update line.
- If condition never becomes
False, loop is infinite. ifdecides once; loop decides repeatedly.
Quick practice
- Write two tasks where loops are necessary.
- Identify loop-control variable in:
- What happens if update line is removed?
Quick answers
- Sample: print first 100 numbers, compute factorial.
count.- Can become infinite loop (depends on condition).
