1
Flow of Control: Loops (Savitch, Chapter 4)
TOPICS
- while Loops
- do while Loops
- for Loops
- break Statement
- continue Statement
Loops! ¡
2
CS 160, Fall Semester 2012
An ¡Example ¡While ¡Loop ¡
int count = 1; int sum = 0; while (count < 5) { sum += count; count++; }
3
What exactly does this code do?
CS 160, Fall Semester 2012
Step-‑by-‑step ¡
int ¡count ¡= ¡1; ¡ int ¡sum ¡= ¡0; ¡ while ¡(count ¡< ¡5) ¡ { ¡ ¡ ¡sum ¡+= ¡count; ¡ ¡ ¡count++; ¡ } ¡
¡
4
Code begins count = 1, sum = 0 true, enter loop Bottom of loop: count = 2, sum = 1 True again, re-enter loop Bottom of loop: count = 3, sum = 3 True again, re-enter loop Bottom of loop: count = 4, sum = 6 True again, re-enter loop Bottom of loop: count = 5, sum = 10 False, exit loop (count 5, sum 10)
CS 160, Fall Semester 2012