Traffic Light Controller using Switch Dry Run in C

Traffic Light Controller using Switch is an interactive C dry run visualizer from the Switch programs section. Study the source code, then use the execution controls to follow each step, variable update, highlighted line, and console output.

This page provides a browser-based dry run with source-code highlighting, auto-scroll, voice narration controls, and execution output for learning the program step by step.

Traffic Light Controller using Switch Program Code

#include <stdio.h>
#include <unistd.h> // for sleep()

// Traffic light states
enum LightState {RED, RED_YELLOW, GREEN, YELLOW};

void display_state(enum LightState state) {
    switch(state) {
        case RED:
            printf(" RED - Stop\n");
            break;
        case RED_YELLOW:
            printf(" RED-YELLOW - Prepare to go\n");
            break;
        case GREEN:
            printf(" GREEN - Go\n");
            break;
        case YELLOW:
            printf(" YELLOW - Slow down\n");
            break;
    }
}

int main() {
    enum LightState current = GREEN;
    int cycle_count = 0;
    
    printf("Traffic Light Simulation\n");
    printf("=======================\n");
    
    while(cycle_count < 3) { // Simulate 3 cycles
        printf("\nCycle %d:\n", cycle_count + 1);
        
        switch(current) {
            case RED:
                display_state(RED);
                sleep(5); // Red for 5 seconds
                current = RED_YELLOW;
                break;
                
            case RED_YELLOW:
                display_state(RED_YELLOW);
                sleep(2); // Red-Yellow for 2 seconds
                current = GREEN;
                break;
                
            case GREEN:
                display_state(GREEN);
                sleep(5); // Green for 5 seconds
                current = YELLOW;
                break;
                
            case YELLOW:
                display_state(YELLOW);
                sleep(3); // Yellow for 3 seconds
                current = RED;
                cycle_count++;
                break;
        }
    }
    
    printf("\nSimulation complete!\n");
    return 0;
}

View the complete Switch programs page.

Program Console Traffic Light Controller using Switch Topic: C Vignaankosh.com
Execution Panel
Step 0/0
Console is empty.