Challenge: Traffic Light
Completed
Use enum class Light { Red, Yellow, Green };. Read a word (red, yellow or green), turn it into a Light, and print what the next light will be and what to do. The order is Green → Yellow → Red → Green.
Input
One word.
Output
For green: Next: yellow (slow down). For yellow: Next: red (stop). For red: Next: green (go).
Example
Input
green
Output
Next: yellow (slow down)
Editor
C++
Hints
Turn the word into a Light with if statements.
Write a function Light next(Light l) using switch.
Solution explanation
Once the text is turned into an enum class value, the rest of the program works with clear, safe names.
Show solution
#include <iostream>
#include <string>
using namespace std;
enum class Light { Red, Yellow, Green };
Light next(Light l) {
switch (l) {
case Light::Green: return Light::Yellow;
case Light::Yellow: return Light::Red;
case Light::Red: return Light::Green;
}
return Light::Red;
}
int main() {
string word;
cin >> word;
Light now = Light::Red;
if (word == "yellow") now = Light::Yellow;
if (word == "green") now = Light::Green;
switch (next(now)) {
case Light::Green: cout << "Next: green (go)\n"; break;
case Light::Yellow: cout << "Next: yellow (slow down)\n"; break;
case Light::Red: cout << "Next: red (stop)\n"; break;
}
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module