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