Model a traffic light with an enum and a function that returns the next state, and print the sequence for 5 steps starting from red.
Solution
main.c
#include <stdio.h>
enum light { RED, GREEN, YELLOW, LIGHT_COUNT };
static const char *light_name[LIGHT_COUNT] = {"RED", "GREEN", "YELLOW"};
static const int seconds[LIGHT_COUNT] = {30, 25, 5};
enum light next(enum light l) {
switch (l) {
case RED: return GREEN;
case GREEN: return YELLOW;
case YELLOW: return RED;
default: return RED; /* never reached: keeps the compiler happy */
}
}
int main(void) {
enum light l = RED;
for (int step = 0; step < 5; step++) {
printf("%-6s %2ds\n", light_name[l], seconds[l]);
l = next(l);
}
return 0;
}
Output Verified by compiling and running
RED 30s
GREEN 25s
YELLOW 5s
RED 30s
GREEN 25s
The enum names the states, and arrays indexed by the enum hold each state's data. A switch without a default would let the compiler warn when a new state is added but not handled – a useful trade-off to know.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!