Next: Summary
Up: The do-while statement
Previous: Example Program: Valid Input
The program in section 16.5 could have equally well
have been written using a do-while
loop. The do-while
loop would be:
cin >> candno; do { // enter marks cout << "Input candidate marks: "; cin >> s1 >> cw1 >> s2 >> cw2; // process marks count = count+1; 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; // enter candidate number cout << "Input candidate number (negative to finish): "; cin >> candno; } while (candno >= 0);
Download program.
This is not completely equivalent to the while
statement version.
Consider what happens if the user initially enters a negative
candidate number--they would be surprised to then be asked for
further data and another candidate number! If there is at least one
candidate then the two versions are equivalent.