School Prizes
National Olympiad — Municipal round (2009 season)
Submission name: prize.cpp
Problem summary
A pupil has seven grades. A grade of 2 cancels the prize. Otherwise print one star for every grade of 6.
Input
Seven integer grades.
Output
No if at least one grade is 2; otherwise a line containing one * per grade of 6.
Constraints
Each grade is between 2 and 6.
Worked example
An independently prepared example for this explanation.
Input
6 3 4 5 6 6 2
Output
No
Solution analysis
- Read all seven grades while maintaining a count of sixes and a flag recording whether a failing grade has appeared.
- The failing flag takes priority over the star count. A pupil with a failing grade receives No even when several grades are excellent.
- For 6, 3, 4, 5, 6, 6, 2, the count of sixes is three, but the final 2 cancels the prize. Replacing that 2 by 6 would produce four stars.
Why it works
After each grade, the counter equals the number of sixes seen and the flag is true exactly when a 2 has appeared. After seven grades these describe the whole pupil record, so the required branch and number of stars are correct.
Watch out. Print No with exactly this capitalization. With no 2 and no 6, the output is an empty line.
Commented C++17 solution
An independently written complete program with standard headers.
#include <iostream>
#include <string>
using namespace std;
int main() {
int stars = 0;
bool failed = false;
for (int i = 0; i < 7; i++) {
int grade;
cin >> grade;
if (grade == 2) {
failed = true;
}
if (grade == 6) {
stars++;
}
}
// A failing grade cancels every excellent-grade star.
if (failed) {
cout << "No";
} else {
cout << string(stars, '*');
}
cout << '\n';
}