Presentation is loading. Please wait.

Presentation is loading. Please wait.

Loop Strategies Repetition Playbook.

Similar presentations


Presentation on theme: "Loop Strategies Repetition Playbook."— Presentation transcript:

1 Loop Strategies Repetition Playbook

2 Case 1: Counter-Controlled Loops
Counter variable increases/decreases by set amount each iteration "I know I want this loop to run _____ times"

3 Counter Controlled Add 5 numbers:

4 Counter Recipees 2 loops that run 5 times Different counter values
Programmers usually start from 0

5 Off By One Error Loop that goes 1 too many or too few times

6 For Loop Every counting loop looks similar:
int i = 1; //initialize while(i < 20) { //condition //do stuff i++; //update }

7 For loop For loop – shortened counting loop
for(initialize; test; update) { //statements } initialize done before loop starts test done before each iteration update is done at the end of the loop

8 For Sample Count 0 to 19: WHILE FOR
int i = 0; while(i < 20) { //do stuff i++; } for(int i = 0; i < 20; i++) { //do stuff }

9 For Advantages Puts loop logic up front

10 For Advantages Counting variable only scoped inside loop:

11 For Tricks Any of the three statements can be anything:
Count 10 to 1: for(int i = 10; i >= 1; i--) Count 0 to 100 by 2's: for(int i = 0; i <= 100; i = i +2) Count using already defined variable: int i; for(i = 0; i <= 100; i = i + 2)

12 Stupid For Tricks Statements can be empty
Count using already defined variable: int i = 0; for( ; i <= 100; i++)… Manual update for(int i = 0; i <= 100; ){ i = i + 2; } No test????? for(int i = 0; ; i++)…

13 Case 2: Sentinel-Controlled Loops
Sentinel : value that indicates ending Money <= 0 User inputs 'q' "I know _____ means it is time to stop"

14 Sum until user enters 0

15 Other ways… To guarantee something happens at least once:
Do first time before loop Start with known "bad value" Or…

16 Do While Do While loop Do statement Check expression True, repeat
False, continue

17 Guessing Game Turn this into guessing game:

18 Do While Do while version: LCV must be scoped outside of loop

19 While While version: Duplicative code No guarantee body will execute…

20 Case 3: Flag-Controlled Loops
Flag : Boolean variable used to indicate state Starts true or false, change when ready to stop

21 Read until find multiple of 2,3 or 5

22 Case Studies GCD of two numbers
Find the largest number that divides in evenly to two inputs

23 Case Studies Future Tuition :
Suppose that the tuition for a university is $10,000 this year and tuition increases 7% every year. In how many years will the tuition be doubled?

24 Case Studies Monte Carlo PI Monte Carlo simulation : probability based
circleArea / squareArea =  / 4  can be approximated as: 4 * numberOfHits /


Download ppt "Loop Strategies Repetition Playbook."

Similar presentations


Ads by Google