while
StatementA while
statement repeatedly executes a target statement as long as a condition is true. Its syntactic form is
while (condition)
statement
In a while
, statement (which is often a block) is executed as long as condition evaluates as true
. condition may not be empty. If the first evaluation of condition yields false
, statement is not executed.
The condition can be an expression or an initialized variable declaration (§ 5.2, p. 174). Ordinarily, the condition itself or the loop body must do something to change the value of the expression. Otherwise, the loop might never terminate.
Variables defined in a while
condition or while
body are created and destroyed on each iteration.
while
LoopA while
loop is generally used when we want to iterate indefinitely, such as when we read input. A while
is also useful when we want access to the value of the loop control variable after the loop finishes. For example:
(a) unsigned aCnt = 0, eCnt = 0, iouCnt = 0;
char ch = next_text();
switch (ch) {
case 'a': aCnt++;
case 'e': eCnt++;
default: iouCnt++;
}
(b) unsigned index = some_value();
switch (index) {
case 1:
int ix = get_value();
ivec[ ix ] = index;
break;
default:
ix = ivec.size()-1;
ivec[ ix ] = index;
}
(c) unsigned evenCnt = 0, oddCnt = 0;
int digit = get_num() % 10;
switch (digit) {
case 1, 3, 5, 7, 9:
oddcnt++;
break;
case 2, 4, 6, 8, 10:
evencnt++;
break;
}
(d) unsigned ival=512, jval=1024, kval=4096;
unsigned bufsize;
unsigned swt = get_bufCnt();
switch(swt) {
case ival:
bufsize = ival * sizeof(int);
break;
case jval:
bufsize = jval * sizeof(int);
break;
case kval:
bufsize = kval * sizeof(int);
break;
}
vector<int> v;
int i;
// read until end-of-file or other input failure
while (cin >> i)
v.push_back(i);
// find the first negative element
auto beg = v.begin();
while (beg != v.end() && *beg >= 0)
++beg;
if (beg == v.end())
// we know that all elements in v are greater than or equal to zero
The first loop reads data from the standard input. We have no idea how many times this loop will execute. The condition fails when cin
reads invalid data, encounters some other input failure, or hits end-of-file. The second loop continues until we find a negative value. When the loop terminates, beg
is either equal to v.end()
, or it denotes an element in v
whose value is less than zero. We can use the state of beg
outside the while
to determine further processing.
Exercise 5.14: Write a program to read string
s from standard input looking for duplicated words. The program should find places in the input where one word is followed immediately by itself. Keep track of the largest number of times a single repetition occurs and which word is repeated. Print the maximum number of duplicates, or else print a message saying that no word was repeated. For example, if the input is
how now now now brown cow cow
the output should indicate that the word now
occurred three times.