Download presentation
Presentation is loading. Please wait.
Published byConrad McDonald Modified over 9 years ago
1
CSC 107 – Programming For Science
2
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
3
Loop Structure
4
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
5
do-while Loop
6
Loop Structure
7
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
8
Loop Control Variant Examples of loops using loop control variant Launching a rocket (10-9-8-7-6-5-4-3-2-1-Blast off!)
9
Loop Control Variant Examples of loops using loop control variant Launching a rocket (10-9-8-7-6-5-4-3-2-1-Blast off!) Going through even numbers (2-4-6-8…)
10
Loop Control Variant Examples of loops using loop control variant Launching a rocket (10-9-8-7-6-5-4-3-2-1-Blast off!) Going through even numbers (2-4-6-8-10-12-14…) Alarm clocks (5:57… 5:58… 5:59… $@#$@ it!)
11
Loop Control Variant Examples of loops using loop control variant Launching a rocket (10-9-8-7-6-5-4-3-2-1-Blast off!) Going through even numbers (2-4-6-8-10-12-14…) Alarm clocks (5:57… 5:58… 5:59… $@#$@ it!) Love (She loves me, she love me not, she loves me)
12
for Loop
13
Initialization Expression
14
Loop Control Variant Update
15
Comparing for & while Loops for Loop while Loop
16
Tracing for Loop
19
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++)
20
Your Turn Get in groups & work on following activity
21
For Next Lecture
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.