Learning outcomes
By the end of this lecture, you should be able to:- solve pattern problems using
while - use sentinel-controlled loops
- apply
breakandcontinuecorrectly - trace digit-based loops
Pattern 1: sum of first n numbers
Pattern 2: sum of digits
Pattern 3: reverse a number
Pattern 4: sentinel input loop
Read numbers until user enters-1.
break and continue
Trap: continue without update
- when
i == 2, it keeps repeating (infinite loop)
Exam hints and traps
- in digit loops, use
n //= 10to shrink number - place update before
continueif needed - sentinel value should be excluded from computation
Practice
- Count digits of a number using
while. - Print odd numbers from 1 to 19.
- Write loop to find smallest positive
nsuch that sum1+...+n >= target.
