Use a safe enum for a traffic light.
What to build
An enum class and a function that moves between its values.
Requirements
- Define
enum class Light { Red, Green, Yellow }. - Write
Light next(Light l): red goes to green, green to yellow, yellow to red. - Starting from red, apply
nextthe given number of times, and print the state in lower case.
Input
One whole number.
Output
One word.
Constraints
The number is from 0 to 1000.
Example
Input:
1
Output:
green
Why it works
enum class makes every value name its type, and the compiler refuses to mix it up with plain numbers.
Examples
Example 1 · Input
1
Expected output
green
Example 2 · Input
0
Expected output
red
Hints
Hint 1
Write enum class Light { Red, Green, Yellow };.
Hint 2
A switch can return the next state.
Solution
Show one correct solution (try it yourself first)
#include <iostream>
using namespace std;
enum class Light { Red, Green, Yellow };
Light next(Light l) {
switch (l) {
case Light::Red:
return Light::Green;
case Light::Green:
return Light::Yellow;
default:
return Light::Red;
}
}
int main() {
int steps;
cin >> steps;
Light now = Light::Red;
for (int i = 0; i < steps; i++) {
now = next(now);
}
if (now == Light::Red) cout << "red" << endl;
else if (now == Light::Green) cout << "green" << endl;
else cout << "yellow" << endl;
return 0;
}