CSC 107 – Programming For Science
Today’s Goal Know how to use and write for loops Explain why to use for, while, & do-while loops Convert between the 3 loops with same end result Explain why we would never convert between loops
Loop Structure
while Loop while (expression) { statement;... } L OOP TERMINATION CONDITION expression is L OOP TERMINATION CONDITION Boolean expression checked at start of each pass Executes entire loop body if expression is true Once expression checked & found false, loop is over L OOP BODY L OOP BODY inside braces executed during pass
do-while Loop
Loop Structure
Loop Control Variant Variable used to control when loop ends Counting passes of loop often performed with this Count not literal; could be constant form of update Very common when used in strictly bounded loops
Loop Control Variant Examples of loops using loop control variant Launching a rocket ( Blast off!)
Loop Control Variant Examples of loops using loop control variant Launching a rocket ( Blast off!) Going through even numbers ( …)
Loop Control Variant Examples of loops using loop control variant Launching a rocket ( Blast off!) Going through even numbers ( …) Alarm clocks (5:57… 5:58… 5:59… it!)
Loop Control Variant Examples of loops using loop control variant Launching a rocket ( Blast off!) Going through even numbers ( …) Alarm clocks (5:57… 5:58… 5:59… it!) Love (She loves me, she love me not, she loves me)
for Loop
Initialization Expression
Loop Control Variant Update
Comparing for & while Loops for Loop while Loop
Tracing for Loop
Counting in for Loops for 's control variant often counts up or down Check against limit in loop termination expression Limit against which we will check is often constant Use constants to hold value of these limits Makes code much easier to read Simplifies changing code when limit needs to change for (i = 0; i < 42; i++) or for (i = 0; i < THE_ANSWER; i++)
Your Turn Get in groups & work on following activity
For Next Lecture