Page last updated 04/21/99
The for loop is used when you know exactly how many iterations there should be.
The while loop is used when there are an indeterminant number of iterations. The number of iterations vary from zero and upward.
There are times that you want the loop body to be executed at least once. That is, the condition need not be tested until after the loop body is executed one time through.
| The while loop | The do while |
|---|---|
while(condition){
loop body
}
|
do {
loop body
} while(condition);
|
Typical use of the do while:
char nextOption()
{ // post: Return an uppercase W, D, or Q
char option = '?';
do {
cout<<"W)ithdraw, D)eposit,or Q)uit: ";
cin >> option;
option = toupper(option);
} while((option != 'W') &&
(option != 'D') &&
(option != 'Q'));
return option;
}
int main()
{
char choice = 'Q';
do {
choice = nextOption();
// assert: choice is either 'Q', 'W', or 'D'
if('W' == choice)
cout << "\nValid entry--process W\n" << endl;
if('D' == choice)
cout << "\nValid entry--process D\n" << endl;
if('Q' == choice)
cout << "\nHave a nice whatever :)" << endl;
} while ( choice != 'Q' );
return 0;
}
// Determine the range of temperatures in a set of known size
#include <iostream>
using namespace std;
int main()
{
int aTemp;
int highest = -9999; // No temperature will be less than -9999
int lowest = 9999; // No temperature will be greater than 9999
int j, n, range;
cout << "Enter number of temperature readings: ";
cin >> n;
// Input first temperature to record it as highest and lowest
cout << "Enter readings 1 per line" << endl;
for(j = 1; j <= n; j++)
cin >> aTemp;
do {
// Update the highest so far, if necessary
if(aTemp > highest)
highest = aTemp;
// Update the lowest so far, if necessary
if(aTemp < lowest)
lowest = aTemp;
// Get the next input
} while(cin >> aTemp);
range = highest - lowest;
cout << "Range: " << range << endl;
return 0;
}
Page 329. Project 8F.
Generate a random number between 1 and 100.
Enter a guess.
While the guess is not the random number
if the guess is less than the number then print "too low" else "too high"
enter the next guess