CS101
CS101
• Repetition structure
– Programmer specifies an action to be repeated while some condition
remains true
– Psuedocode
while there are more items on my shopping list
Purchase next item and cross it off my list
– while loop repeated until condition becomes false.
• Example
int product = 2;
while ( product <= 1000 )
product = 2 * product;
The while Repetition Structure
• Flowchart of while loop
true
product <= 1000 product = 2 * product
false
Formulating Algorithms (Counter-Controlled
Repetition)
• Counter-controlled repetition
– Loop repeated until counter reaches a certain value.
• Definite repetition
– Number of repetitions is known
• Example
A class of ten students took a quiz. The grades (integers in the range 0
to 100) for this quiz are available to you. Determine the class average on
the quiz.
Formulating Algorithms (Counter-Controlled
Repetition)
• Pseudocode for example:
Set total to zero
Set grade counter to one
While grade counter is less than or equal to ten
Input the next grade
Add the grade into the total
Add one to the grade counter
Set the class average to the total divided by ten
Print the class average
3#include <iostream>
5using std::cout;
6using std::cin;
7using std::endl;
9int main()
10 {
15
16 // initialization phase
26 }
27
28 // termination phase
31
33 }
Enter grade: 98
Enter grade: 76
Enter grade: 71
Enter grade: 87
Enter grade: 83
Enter grade: 90
Enter grade: 57
Enter grade: 79
Enter grade: 82
Enter grade: 94
Class average is 81
Formulating Algorithms with Top-Down, Stepwise
Refinement (Sentinel-Controlled Repetition)
3#include <iostream>
5using std::cout;
6using std::cin;
7using std::endl;
8using std::ios;
10 #include <iomanip>
11
12 using std::setprecision;
13 using std::setiosflags;
14
15 int main()
16 {
21
22 // initialization phase
23 total = 0;
24 gradeCounter = 0;
25
26 // processing phase
29
30 while ( grade != -1 ) {
31 total = total + grade;
32 gradeCounter = gradeCounter + 1;
35 }
36
37 // termination phase
38 if ( gradeCounter != 0 ) {
43 }
44 else
46
48 }