Tom Kelliher, CS17
A common situation:
i = 0; // Initialization.
while (i < n) // Predicate.
{
// Do something based on i's value.
++i; // Post-loop processing.
}
Initialization, predicate and post-loop processing are combined in the for statement:
for (i = 0; i < n; ++i) ; // Do something based on i's value
General form of a for statement:
for (Initialization; Predicate; PostLoopProcessing) LoopBody
Semantics of a for statement:
long fact(int n)
{
long prod = 1;
int i;
for (i = 2; i <= n; ++i)
prod *= i;
return prod;
}
Simulate for fact(5).
int sum(int n); // Prototype.
Write the function yourself.
See previous examples
Entering a list of ages and using a negative age to indicate ``end of input'':
cout << "Enter an age: "
cin >> inputAge;
while (inputAge >= 0)
{
// Do something with the age.
cout << "Enter an age: "
cin >> inputAge;
}
Note the redundancy. Better expressed through a posttest structure:
do
{
cout << "Enter an age: "
cin >> inputAge;
// Do something with the age.
} while (inputAge >= 0);
Suppose the first age is itself negative? (Unlikely in this case.) The ``best'' solution:
while (1)
{
cout << "Enter an age: "
cin >> inputAge;
if (inputAge < 0)
break;
// Do something with the age.
}
Midtest repetition?
Not used very often.
Example: rejecting invalid inputs.
#include <iostream.h>
#include <iomanip.h>
double computeAverage(int number);
int main()
{
int n;
do
{
cout << "Enter the number of scores: ";
cin >> n;
} while (n < 1);
cout << "\nThe average score is " << setprecision(1)
<< setiosflags(ios::fixed) << computeAverage(n) << ".\n";
cout << "\nThe bill is in the mail.\n";
return 0;
}
double computeAverage(int number) // Why return double?
{
int sum = 0;
int score;
int i;
// Note comma operator in loop initializer.
// The form of this differs from a similar example in the text.
for (sum = 0, i = 0; i < number; ++i)
{
cout << "Enter score " << i << ": ";
cin >> score;
if (score < 0)
{
cout << "Score must be non-negative! Score discarded.\n";
// Why is this decrement necessary?
--i;
continue; // Skip to next iteration.
}
sum += score;
}
return sum / number; // Will this return a double?
}
What is printed by:
int i, j;
for (i = 0; i < 3; ++i)
for (j = 0; j < 4; ++j)
cout << j << endl;
What is printed by:
int i, j;
for (i = 0; i < 3; ++i)
for (j = 0; j < 4; ++j)
cout << setw(8) << i << setw(8) << j << endl;