|
Recall that a for-loop is intended to simplify the thought process by separating a loop into two parts, the sequence that you want to look at, and what you want to do for each member of that sequence.
For example, a for-loop is convenient for computing powers. Here is a sensible definition of a power function.
// power(x,n) returns x to the n-th power. // // Requirement: n > 0. double power(const double x, const int n) { double p = x; for(int k = 2; k <= n; k++) { p = p * x; } return p; }There are two loop-control variables, k and p. The for loop logically breaks into two parts, one concerned with k and the other with p. The k part is:
for(int k = 2; k <= n; k++)
{
…
}
which makes k take on each member of sequence
[2, 3, 4, …, n].
The p part is:
double p = x;
for(k = …)
{
p = p * x;
}
return p;
What about the following version of power?
double power(const double x, const int n) { double p = x; for(int k = 2; k <= n; p = p * x) { k++; } return p; }That works, but management of k and p are not separable. That makes it much more difficult to understand than the previous version. To make your code easier to understand, concentrate on one control variable in a for-loop heading. The standards require you to do that.
|