Counter-controlled iteration (p. 160) requires a control variable, the initial value of the control variable, the increment by which the control variable is modified each time through the loop (also known as each iteration of the loop) and the loop-continuation condition that determines whether looping should continue.
In C++, a variable declaration that also reserves memory is a definition (p. 161).
for
Iteration StatementThe while
statement can be used to implement any counter-controlled loop.
The for
statement (p. 161) specifies all the details of counter-controlled iteration in its header
When the for
statement begins executing, its control variable is optionally declared and initialized. If the loop-continuation condition is initially true, the body executes. After executing the loop’s body, the increment expression executes. Then the loop-continuation test is performed again to determine whether the program should continue with the next iteration of the loop.
The general format of the for
statement is
for (initialization; loopContinuationCondition; increment) {
statement
}
where the initialization expression names the loop’s control variable and provides its initial value, loopContinuationCondition determines whether the loop should continue executing and increment modifies the control variable’s value, so that the loop-continuation condition eventually becomes false. The two semicolons in the for
header are required.
Most for
statements can be represented with equivalent while
statements as follows:
initialization;
while (loopContinuationCondition) {
statement
increment;
}
Typically, for
statements are used for counter-controlled iteration and while
statements for sentinel-controlled iteration.
If the initialization expression in the for
header declares the control variable, the control variable can be used only in that for
statement—it will not exist outside the for
statement.
The expressions in a for
header are optional. If the loopContinuationCondition is omitted, C++ assumes that it’s always true, thus creating an infinite loop. You might omit the initialization expression if the control variable is initialized before the loop. You might omit the increment expression if the increment is calculated with statements in the loop’s body or if no increment is needed.
The increment expression in a for
acts as if it’s a standalone statement at the end of the for
’s body.
A for
statement can count downward by using a negative increment—i.e., a decrement (p. 165).
If the loop-continuation condition is initially false, the for
statement’s body does not execute.
The initialization and increment expressions can be comma-separated lists that enable you to use multiple initialization expressions or multiple increment expressions.
The comma between the expressions is a comma operator, which guarantees that a list of expressions evaluates from left to right.
The comma operator has the lowest precedence of all C++ operators.
The value and type of a comma-separated list of expressions is the value and type of the rightmost expression.
C++ treats floating-point literals like 1000.0
and 0.05
as type double
. Similarly, C++ treats whole-number literals like 7
and -22
as type int
.
Standard library function pow(x, y)
(p. 169) calculates the value of x
raised to the y
th power. Function pow
takes two arguments of type double
and returns a double
value.
Parameterized stream manipulator setw
(p. 169) specifies the field width in which the next value output should appear, right justified by default. If the value is larger than the field width, the field width is extended to accommodate the entire value. Stream manipulator left
(p. 169) causes a value to be left justified and right
(p. 169) can be used to restore right justification.
Sticky output-formatting settings (p. 169) remain in effect until they’re changed.
Type double
suffers from what we call representational error (p. 170), because double
cannot precisely represent all decimal values.
DollarAmount
You cannot avoid rounding on interest calculations, because they result in fractional pennies when working with dollar amounts.
With integer arithmetic you can exercise precise control over rounding without suffering the representational errors associated with floating-point calculations.
DollarAmount
On most computers, an int
is a value from –2,147,483,647 to 2,147,483,647—way too small for many monetary applications.
C++11’s long long
(p. 176) type supports values in the range –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 as a minimum.
The range of long long
(and C++’s other integer types) can vary across platforms. For portability, C++11 introduced new integer-type names so you can choose the appropriate range of values for your program. An int64_t
(p. 177) supports the exact range –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
For a list of C++11’s integer-type names, see the header <cstdint>
(p. 177).
A member function can access both the private
data of the object on which that function is called and the private
data of other objects of the same class that are passed to the function.
In half-up rounding, values .5 and higher round up and everything else rounds down.
C++ Standard Library function to_string
(p. 178; from header <string>
) converts a numeric value to a string
object.
C++ Standard Library function abs
(p. 178; from header <cmath>
) returns the absolute value of its argument.
“Adding” string literals and string
objects using the + operator is known as string concatenation
(p. 178).
string
member function size
(p. 178) returns the number of characters in the string
.
Half-up rounding is a biased technique, because fewer values round down than up—fractional amounts of .1, .2, .3 and .4 round down, and .5, .6, .7, .8 and .9 round up. Banker’s rounding (p. 179) fixes this problem by rounding .5 to the nearest even integer.
do
…while
Iteration StatementThe do…
(p. 179) is similar to the while
statementwhile
statement. In the while
, the program tests the loop-continuation condition at the beginning of the loop, before executing its body; if the condition is false, the body never executes. The do
…while
statement tests the loop-continuation condition after executing the loop’s body; therefore, the body always executes at least once.
switch
Multiple-Selection StatementThe switch
multiple-selection statement (p. 180) performs different actions based on its controlling expression’s value.
The end-of-file indicator is a system-dependent keystroke combination that terminates user input. On UNIX/Linux/Mac OS X systems, end-of-file is entered by typing the sequence <Ctrl> d on a line by itself. This notation means to simultaneously press both the Ctrl key and the d key. On Windows systems, enter end-of-file by typing <Ctrl> z.
When you perform input with cin
in a condition, the condition evaluates to true if the input is successful or evaluates to false if the user enters the end-of-file indicator.
The switch
statement consists of a block that contains a sequence of case
labels (p. 184) and an optional default
case (p. 184).
In a switch
, the program evaluates the controlling expression and compares its value with each case
label. If a match occurs, the program executes the statements for that case
.
Listing cases consecutively with no statements between them enables the cases to perform the same set of statements.
Every value you wish to test in a switch
must be listed in a separate case
label.
Each case
can have multiple statements, and these need not be placed in braces.
A case
’s statements typically end with a break
statement (p. 184) that terminates the switch
’s execution.
Without break
statements, each time a match occurs in the switch
, the statements for that case and subsequent cases execute until a break
statement or the end of the switch
is encountered.
If no match occurs between the controlling expression’s value and a case
label, the optional default
case executes. If no match occurs and the switch
does not contain a default
case, program control simply continues with the first statement after the switch
.
break
and continue
StatementsThe break
statement, when executed in a while
, for
, do
…while
or switch
, causes immediate exit from that statement.
The continue
statement (p. 186), when executed in a while
, for
or do
…while
, skips the loop’s remaining body statements and proceeds with its next iteration. In while
and do
…while
statements, the program evaluates the loop-continuation test immediately. In a for
statement, the increment expression executes, then the program evaluates the loop-continuation test.
Simple conditions are expressed in terms of the relational operators >
, <
, >=
and <=
and the equality operators ==
and !=
, and each expression tests only one condition.
Logical operators (p. 188) enable you to form more complex conditions by combining simple conditions. The logical operators are &&
(logical AND), ||
(logical OR) and !
(logical negation).
To ensure that two conditions are both true, use the &&
(logical AND) operator. If either or both of the simple conditions are false, the entire expression is false.
To ensure that either or both of two conditions are true, use the ||
(logical OR) operator, which evaluates to true if either or both of its simple conditions are true.
A condition using &&
or ||
operators uses short-circuit evaluation (p. 190)—they’re evaluated only until it’s known whether the condition is true or false.
The unary !
(logical negation; p. 190) operator “reverses” the value of a condition.
By default, bool
values true
and false
are displayed by cout
as 1
and 0
, respectively. Stream manipulator boolalpha
(p. 191) specifies that the value of each bool
expression should be displayed as either the word “true” or the word “false.”
==
) and Assignment (=
) OperatorsAny expression that produces a value can be used in the decision portion of any control statement. If the value of the expression is zero, it’s treated as false
, and if the value is nonzero, it’s treated as true
.
An assignment produces a value—namely, the value assigned to the variable on the left side of the assignment operator.
Programmers normally write conditions such as x == 7
with the variable name (an lvalue) on the left and the literal (an rvalue) on the right. Placing the literal on the left, as in 7 == x
, enables the compiler to issue an error if you accidentally replace the ==
operator with =
. The compiler treats this as a compilation error, because you can’t change a literal’s value.