int n; cout << "Enter a number less than 10: "; cin >> n; |
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;
} |
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;
as long as (n >= 10) keep doing the following
{
cout << "Enter a number less than 10: ";
cin >> n;
} |
as long
as (n >= 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 impelement 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? I accidently wrote x = 0
rather than x == 0. The result is that because
the ||-expression is evaluated left-to-right, x gets set to 0 in
the first part of the OR, and that makes the second part true
regardless of what the y value is.