Enum usage in C - Time & Space Complexity
Enums help us name groups of related values in code. When using enums, it's important to see how the program's steps grow as we use them.
We want to know how the program's work changes when enums are involved.
Analyze the time complexity of the following code snippet.
#include <stdio.h>
enum Color { RED, GREEN, BLUE };
void printColor(enum Color c) {
switch(c) {
case RED: printf("Red\n"); break;
case GREEN: printf("Green\n"); break;
case BLUE: printf("Blue\n"); break;
}
}
int main() {
enum Color colors[] = {RED, GREEN, BLUE, RED};
int n = sizeof(colors) / sizeof(colors[0]);
for(int i = 0; i < n; i++) {
printColor(colors[i]);
}
return 0;
}
This code defines an enum for colors and prints each color in an array using a loop and a switch-case.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the array of colors and calling printColor for each.
- How many times: The loop runs once for each color in the array (n times).
As the number of colors in the array grows, the program prints each one once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 print calls |
| 100 | About 100 print calls |
| 1000 | About 1000 print calls |
Pattern observation: The work grows directly with the number of colors; doubling colors doubles the work.
Time Complexity: O(n)
This means the program's work grows in a straight line with the number of colors to print.
[X] Wrong: "Using enums makes the program run faster or slower depending on the enum size."
[OK] Correct: Enums are just named numbers; they don't change how many times the program runs loops or prints. The time depends on how many items you process, not on enum details.
Understanding how enums fit into loops and switches helps you explain how your code handles groups of values efficiently. This skill shows you can think about how code grows with input, a key part of writing good programs.
"What if we replaced the array with a linked list of colors? How would the time complexity change?"