The While-Loop
-
The syntax of the while-loop is:
while (Boolean_Expression)
Yes_Statement
The execution sequence of the while-loop is as follows:
-
First the Boolean-Expression is test, if it is true, the loop statement
is executed
-
The Boolean_expression is then retested
-
The loop statement
is executed as long as (while) the Boolean_Expression is true.
-
When the Boolean_expression is tested and found to be false, the while-loop is exited and the next program statement after the while-loop is executed.
-
Note that if the Boolean_expression evaluates to false when the
while-loop begins, then the loop body is not executed, not even once.
-
However if the Boolean_expression always evaluates to true despite the statements inside the loop body,
then the loop keeps on looping for ever. (You will need to type "control-C" to stop the program from running forever.)
This is called an infinite loop.
-
// Illustration of the use of the while-loop
// The user first enters two integers
// and then types in the answer for the sum of the integers.
// If the answer is correct, then the program responds
// with an encouraging statement.
// The program should not end until the correct answer is entered.
#include <iostream>
using namespace std;
int main ( )
{
int Num1, Num2, CorrectAnswer, Input;
cout << "Type 2 integers separated by a space and press enter: ";
cin >> Num1 >> Num2;
CorrectAnswer = Num1 + Num2;
cout << "Add up " << Num1 << " and " << Num2
<< " and enter your answer: ";
cin >> Input;
while (Input != CorrectAnswer)
{
cout << "Your answer is incorrect!\n";
cout << "Please re-calculate the sum of " << Num1
<< " and " << Num2 << " and re-enter the result: ";
cin >> Input;
}
cout << "Grrreat! Your answer is corrrect!" << endl;
return 0;
} //end main
The following shows an example of the dialogue:
Type 2 integers separated by a space and press enter: 11 6
Add up 11 and 6 and enter your answer: 2
Your answer is incorrect!
Please re-calculate the sum of 11 and 6 and reenter the result: -23
Your answer is incorrect!
Please re-calculate the sum of 11 and 6 and reenter the result: 17
Grrreat! Your answer is corrrect!
-
The following example is from the textbook:
#include <iostream>
using namespace std;
int main( )
{
double balance = 50.00;
int count = 0;
cout << "This program tells you how long it takes\n"
<< "to accumulate a debt of $100, starting with\n"
<< "an initial balance of $50 owed.\n"
<< "The interest rate is 2% per month.\n";
while (balance < 100.00)
{
balance = balance + 0.02 * balance;
count++;
}
cout << "After " << count << " months,\n";
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
cout << "your balance due will be $" << balance << endl;
return 0;
}
-
// An example of a sentinel-controlled while-loop
// The program asks the user to enter the final exam score
// for each of the student in a class,
// and then computes the average score for the class.
// As usual, there are always some students who did not take the exam
// (bad students), and the professor is lazy and does not want to count
// the number of exam scores before entering them (bad professor).
//
// To compute the class average, we can declare a variable, say sum,
// to represent the sum of the scores, and initialize it to 0.
// After reading each score from the keyboard, it is added to sum.
// After we are done reading all the scores, we need to divide the sum
// by the total number of scores. We can obtain that number if we use a
// counter which is initialized to 0 and is incremented by 1
// after a score is read.
// The remaining challenge is to come up with a way to know when
// to stop the loop.
// One way to get around the problem is to use a unique data value,
// called the sentinel value, as the last data item.
// Here we use a score of -1 as the sentinel value,
// since we believe exam scores cannot be negative
// no matter how crazy the professor may be.
#include <iostream>
using namespace std;
int main ( )
{
const int SENTINEL = -1;
int count = 0, sum = 0, score;
float average;
cout << "Enter scores one at a time as requested.\n";
cout << "When done, enter " << SENTINEL
<< " to stop.\n";
cout << "Enter the first score: ";
cin >> score;
while (score != SENTINEL)
{
count++;
sum += score;
cout << "Enter the next score: ";
cout << "When done, enter " << SENTINEL
<< " to stop.\n";
cin >> score;
} // end while
if (count==0)
{
cout << "You didn't enter a meaningful number.\n"
<< "No average is computed.\n";
}
else
{
// compute the class average
average = float(sum)/float(count);
// output the results
cout << count <<
" exam scores were processed.\n";
cout << "Average score is: " << average
<< endl;
}
return 0;
} //end main