Next: Example Program: Generation of
Up: The for statement
Previous: Example for statement: Print
The program from section 16.5 could also be modified
to use the for statement to control the loop. This cannot be
done without changing the specification of the input data. If the
specification was changed so that the number of students was entered
before the examination marks then a for statement could be used
as follows:
void main()
{
int candno; // candidate number
int s1, cw1, s2, cw2; // candidate marks
int final1, final2; // final subject marks
int count; // number of students
int sum1, sum2; // sum accumulators
int subav1, subav2; // subject averages
int i; // for loop control variable
const float EXAMPC = 0.7,
CWPC = 0.3;
// initialise
sum1 = 0;
sum2 = 0;
// enter number of students
cout << "Enter number of students: ";
cin >> count;
for (i=0; i<count; i=i+1)
{
// enter candidate number and marks
cout << "Input candidate number and marks: ";
cin >> candno >> s1 >> cw1 >> s2 >> cw2;
// process marks
final1 = int(EXAMPC*s1+CWPC*cw1);
final2 = int(EXAMPC*s2+CWPC*cw2);
sum1 = sum1+final1;
sum2 = sum2+final2;
// output marks
cout << candno << " "
<< s1 << " " << cw1 << " "
<< s2 << " " << cw2 << " "
<< final1 << " " << final2
<< endl;
}
// evaluate averages
subav1 = sum1/count;
subav2 = sum2/count;
// output averages
cout << endl << "Subject1 average is " << subav1
<< endl << "Subject2 average is " << subav2
<< endl;
}
Download program.
Note that if zero or a negative number is entered for the number of students then this program will fail, an attempted division by zero will be encountered (why?). This could be fixed by putting in a validation check on the number of students when this is entered by the user.