Professional Documents
Culture Documents
1
Loops
2
while statement
SYNTAX
while ( Expression ) {
.
. // loop body
.
}
FALSE
expression
TRUE
body
statement
4
Two types of loops
event-controlled loops
some condition within the loop body
changes and this causes the
repeating to stop
5
Count controlled loops
6
Example
int count ;
7
Trace and output
count
4
OUTPUT: 4
3 3
2 2
1 1
0 Done
so loop terminates
8
Count controlled loop example
9
The program
ifstream myInfile ;
int ThisBP ;
int Total ;
int count ;
count = 0 ; // initialize
14
Example
// Sentinel controlled loop
Total = 0;
16
End of file Example
Total = 0;
19
flag controlled example
CountGoodReadings = 0;
Safe = 1; // initialize flag to 1
while (Safe) {
cin >> ThisBP;
if ( ThisBP >= 200 )
Safe = 0; // change flag to 0
else
CountGoodReadings++;
} // while
cout << CountGoodReadings << endl; 20