6.7. The while Statement
A while statement repeatedly executes a target statement as long as a condition is true. Its syntactic form is
while (condition)
statement
Exercises Section 6.6.5
Exercise 6.7:There is one problem with our vowel-counting program as we've implemented it: It doesn't count capital letters as vowels. Write a program that counts both lower- and uppercase letters as the appropriate vowelthat is, your program should count both 'a' and 'A' as part of aCnt, and so forth.Exercise 6.8:Modify our vowel-count program so that it also counts the number of blank spaces, tabs, and newlines read.Exercise 6.9:Modify our vowel-count program so that it counts the number of occurrences of the following two-character sequences: ff, fl, and fi.Exercise 6.10:Each of the programs in the highlighted text on page 206 contains a common programming error. Identify and correct each error.The statement (which is often a block) is executed as long as the condition evaluates as true. The 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 definition:
Any variable defined in the condition is visible only within the block associated with the while. On each trip through the loop, the initialized value is converted to bool (Section 5.12.3, p. 182). If the value evaluates as TRue, the while body is executed. Ordinarily, the condition itself or the loop body must do something to change the value of the expression. Otherwise, the loop might never terminate.
bool quit = false;
while (!quit) { // expression as condition
quit = do_something();
}
while (int loc = search(name)) { // initialized variable as condition
// do something
}

Using a while Loop
We have already seen a number of while loops, but for completeness, here is an example that copies the contents of one array into another:
// arr1 is an array of ints
int *source = arr1;
size_t sz = sizeof(arr1)/sizeof(*arr1); // number of elements
int *dest = new int[sz]; // uninitialized elements
while (source != arr1 + sz)
*dest++ = *source++; // copy element and increment pointers
Code for Exercises in Section 6.6.5
164, C++ programmers tend to write terse expressions. The statement in the body of the while
(a) switch (ival) {
case 'a': aCnt++;
case 'e': eCnt++;
default: iouCnt++;
}
(b) switch (ival) {
case 1:
int ix = get_value();
ivec[ ix ] = ival;
break;
default:
ix = ivec.size()-1;
ivec[ ix ] = ival;
}
(c) switch (ival) {
case 1, 3, 5, 7, 9:
oddcnt++;
break;
case 2, 4, 6, 8, 10:
evencnt++;
break;
}
(d) int ival=512 jval=1024, kval=4096;
int bufsize;
// ...
switch(swt) {
case ival:
bufsize = ival * sizeof(int);
break;
case jval:
bufsize = jval * sizeof(int);
break;
case kval:
bufsize = kval * sizeof(int);
break;
}
is a classic example. This expression is equivalent to
*dest++ = *source++;
{
*dest = *source; // copy element
++dest; // increment the pointers
++source;
}
