0
0
Cprogramming~20 mins

Why enumerations are used in C - See It in Action

Choose your learning style9 modes available
Why enumerations are used
📖 Scenario: Imagine you are creating a simple program to manage traffic light colors. Each color has a specific meaning and you want to use clear names instead of numbers to represent them.
🎯 Goal: You will create an enumeration to represent traffic light colors and use it in a program to print the meaning of each color.
📋 What You'll Learn
Create an enumeration called TrafficLight with values RED, YELLOW, and GREEN
Create a variable of type TrafficLight and assign it the value RED
Use a switch statement to print the meaning of the current traffic light color
Print the output to the console
💡 Why This Matters
🌍 Real World
Enums are used in many programs to represent fixed sets of options like states, modes, or categories, making code clearer and less error-prone.
💼 Career
Understanding enums is important for writing maintainable and readable code in C programming jobs, especially in embedded systems, game development, and system software.
Progress0 / 4 steps
1
Create the enumeration for traffic light colors
Write an enumeration called TrafficLight with the values RED, YELLOW, and GREEN.
C
Need a hint?

Use the enum keyword followed by the name TrafficLight and list the colors inside curly braces.

2
Create a variable of type TrafficLight and assign RED
Create a variable called currentLight of type TrafficLight and assign it the value RED.
C
Need a hint?

Declare the variable with the enum type and assign RED using the equals sign.

3
Use a switch statement to print the meaning of the traffic light
Write a switch statement using the variable currentLight to print "Stop" for RED, "Ready" for YELLOW, and "Go" for GREEN.
C
Need a hint?

Use switch with case labels for each color and printf to print the messages.

4
Print the output
Add the necessary #include directive and write a main function that runs the code and prints the output.
C
Need a hint?

Remember to include stdio.h and write a main function that returns 0.