Datasheet
The keyword break can be used within a loop to immediately get out of the loop and continue execu-
tion of the program. The keyword
continue can be used to return to the top of the loop and reevaluate
the
while expression. Both are often considered poor style because they cause the execution of a pro-
gram to jump around somewhat haphazardly.
The Do/While Loop
C++ also has a variation on the while loop called do/while. It works similarly to the while loop,
except that the code to be executed comes first, and the conditional check for whether or not to continue
happens at the end. In this way, you can use a loop when you want a block of code to always be exe-
cuted at least once and possibly additional times based on some condition. The example that follows
will output “This is silly.” once even though the condition will end up being false.
int i = 100;
do {
std::cout << “This is silly.” << std::endl;
i++;
} while (i < 5);
The For Loop
The for loop provides another syntax for looping. Any for loop can be converted to a while loop and
vice versa. However, the
for loop syntax is often more convenient because it looks at a loop in terms of
a starting expression, an ending condition, and a statement to execute at the end of every iteration. In the
following code,
i is initialized to 0, the loop will continue as long as i is less than 5, and at the end of
every iteration,
i is incremented by 1. This code does the same thing as the while loop example, but to
some programmers, it is easier to read because the starting value, ending condition, and per-iteration
statement are all visible on one line.
for (int i = 0; i < 5; i++) {
std::cout << “This is silly.” << std::endl;
}
Arrays
Arrays hold a series of values, all of the same type, each of which can be accessed by its position in the
array. In C++, you must provide the size of the array when the array is declared. You cannot give a vari-
able as the size — it must be a constant value. The code that follows shows the declaration of an array of
10 integers followed by a
for loop that initializes each integer to zero.
int myArray[10];
for (int i = 0; i < 10; i++) {
myArray[i] = 0;
}
15
A Crash Course in C++
04_574841 ch01.qxd 12/15/04 3:39 PM Page 15










