LearnFrenzy
Sign in Take a free test

Structures, Unions, Enums · Structure Programs · Question 7

Traffic light state machine using an enum in C Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

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.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links