There are many situations that we need iteration, but we don't know
know before hand, nor can be ascertained by the program before the loop
is entered. This is when we use the indeterminant loop.
| The syntax | An example |
|---|---|
while(condition){
loop body
}
|
// powers of two up to 1000
int power = 1;
while(power<1000){
cout << power << endl;
power *= 2;
}
|
void moveTillStopped(grid & g)
{ // post; The mover is facing a block or edge in front
while(g.frontIsClear()){
g.move();
}
}
int main()
{
grid tarpit(5,10);
cout << "A grid initialized only with rows and columns"<<endl
<< "has its mover randomly set." << endl;
moveTillStopped(tarpit);
tarpit.display() << endl;
return 0;
}
The input statement returns true if the input successfull retrieved a value to put into the variable. It will be false otherwise.
while((cin >> x) && (x >= 0)){
// do something with x
}
// Use a sentinel of -1 to terminate a loop
#include <iostream>
using namespace std;
int main()
{
const double sentinel = -1.0; // User enters this to terminate
double accumulator = 0.0; // Maintain running sum of inputs
int n = 0; // Maintain total number of inputs
double testScore, average;
// Prompt
cout << "Enter test scores [0.0 through 100.0] or " << sentinel
<< " to quit" << endl;
// Input and process at the same time
while( (cin >> testScore) && (testScore != sentinel) ){
accumulator += testScore; // Update accumulator
n++; // Update total inputs
}
if(n > 0){
average = accumulator / n;
cout << "Average of " << n << " tests = " << average << endl;
} else {
cout << "Can't average 0 numbers" << endl;
}
return 0;
}