int n;
cout << "Enter a number less than 10: ";
cin >> n;
However, if the user is dumb or inattentive or malicious,
they might enter a number that is greater than or equal to 10.
We might want to ensure that doesn't happen (imagine our next
step was to compute sqrt(10 - n)
, for example), so
we might extend our code to something like this:
int n;
cout << "Enter a number less than 10: ";
cin >> n;
if (n >= 10)
{
cout << "Enter a number less than 10: ";
cin >> n;
}
This looks good, however, a very dumb,
inattentive, or malicious user might enter two numbers in a row
that were greater than or equal to 10, thus requiring another
"if
" statement (like this).
In fact, no matter how many of these "if
"
statements we put in, a sufficiently dumb, inattentive, or
malicious user can get by with n
having an invalid
value. What we really want to say is something like
int n;
cout << "Enter a number less than 10: ";
cin >> n;
while n is at least 10, keep doing the following
{
cout << "Enter a number less than 10: ";
cin >> n;
}
while
n is at least 10, keep doing the following
is
while (n >= 10)
Putting that in our code fragment, we end up with:
int n;
cout << "Enter a number less than 10: ";
cin >> n;
while (n >= 10)
{
cout << "Enter a number less than 10: ";
cin >> n;
}
while
loop
The syntax of a while
-loop is much like the syntax
of an if
-statement without an else block: We have
while
followed by a test condition and a block of
code. As long as the test condition is true ("while" the test
condition is true), we keep executing the block of code
(referred to as the body of the loop).
A typical task that we'll implement with a loop is finding the sum of bunch of integers input by the user. We'll assume that the user will enter a negative number to indicate that he's done inputting data. (The negative number is just an end marker - it should not be included in the sum.) The typical way of doing this is:
int sum, k;
sum = 0;
cin >> k;
while (k >= 0)
{
sum = sum + k;
cin >> k;
}
cout << sum << endl;
The section of code that sets sum = 0
and reads the
first value for k
performs initialization,
i.e. work before the loop that prepares you for the loop. The
variable sum
must have the value zero before the
loop begins, otherwise the whole concept is blown. The first
value for k
needs to be read in from the user
before we begin the loop, since that value will be checked in
the loop's test condition. Here's the
whole program.
while ( (x = 0) || (x*y < 10) )
{
cout << "Enter x and y: ";
cin >> x >> y;
}
Can you spot the problem?
x = 0
rather than
x == 0
.