Download presentation
Presentation is loading. Please wait.
1
Iteration with While You can say that again
2
Problem You want to add 100 numbers
3
Problem 100 variables? int a,b,c,d…. cin >> a; cin >> b; … int answer = a + b + c…
4
Problem Use one variable 100 times?
int num, answer = 0; cin >> num; answer += num; cin >> num; answer += num; …
5
Golden Rule of Programming
If you write the same code more than once you are probably doing it wrong.
6
Problem Repeat to eliminate duplication: int num, answer = 0;
Repeat 100 times cin >> num; answer += num;
7
While While statement expression Boolean expression
statement is the body of the loop Usually compound using { } After executing, test expression again
8
While Sample Sample loop Counts 1 to 100 Happens once Happens 0+ times
9
While Sample Sample loop Expression : boolean expression
True – execute body, then check again False – done; skip to end of loop
10
Infinite Loop Condition is always true : infinite loop
Ctrl-C breaks a program
11
While Sample Sample loop Expression : boolean expression
Usually tests a variable (loop control variable)
12
Loop Control Variables
i, j, k : accepted identifiers for loop control variables
13
While Sample Sample loop Update: change loop control variable
"Go to next step" Do as first or last thing in loop body
14
Infinite Loop No update to LCV = infinite loop
int i = 0; while(i < 20) { cout << i << " "; //i never changes!!! }
15
Counting Example Start at 10, count by 5's, count until 50
16
Making a list Formatting numbers as a list: version 1
17
Making a list Formatting numbers as a list: version 2
18
Few Problems are Unique
Pattern solving is pattern recognition
19
Patterns of Loop Use Typical use patterns Total some values
Average some values
20
Total Total something up: Declare variable before
Add current value in loop Use total after
21
Average Find average Get total Get count
Use counting variable After loop, divide total by count
22
Average Find average - correct
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.