Tom Kelliher, CS18
Feb. 5, 1996
Use:
sum = 0.0; // note style
count = 0;
cin >> data;
while (data != 0.0) {
sum += data;
count++;
cin >> data;
}
if (count != 0)
average = sum / count;
guess = x / 2.0; // good example of a sequence:
do { // x_0, x_1, ..., x_i
oldGuess = guess;
guess = oldGuess / 2.0 + x / (2.0 * oldGuess);
} while (fabs(guess - oldGuess) > EPSILON);
Pretest, posttest structures
Sentinel, counter, computation controlled repetition
Syntax:
while (<condition>) // note "style"
stmt;
while (<condition>) { // stmt replaced with compound block
stmt1; // while structure considered a single
... // "statement"
stmtn;
}
Fairly simple semantics
1, 0 conditions
Somewhat more complex syntax:
for (<initializer>; <condition>; <post-processing>) stmt;
Semantics, list items optional
Post-processing quite flexible:
for (i = 1; i <= 1024; i *= 2) cout << i << endl;
Watch out:
for (i = 1; i != 10; i += 2) <stmt>;
Efficiency issues
Equivalent in C, orthogonal in Pascal
continue: skip to next iteration
for (i = 0; i < 100; i++) {
if (i % 2 == 1) // other ways of doing the same thing?
continue;
cout << i << endl;
}
break: cease iterating
found = FALSE;
for i = 0; i < numElements; i++) {
if (data[i] == targetValue) {
found = TRUE;
break;
}
}
At least one iteration (compare while)
Arbitrary nesting possible
Example:
i = j = 0;
for (i = 0; i < 10; i++) {
cout << setw(10) << i << j << endl; // first 12 values printed?
for (j = 9; j >= 0; j--)
cout << setw(10) << i << j << endl;
}
How could we break out of both loops in last example?