0
0
Cprogramming~5 mins

Enum usage in C - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Enum usage
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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).
How Execution Grows With Input

As the number of colors in the array grows, the program prints each one once.

Input Size (n)Approx. Operations
10About 10 print calls
100About 100 print calls
1000About 1000 print calls

Pattern observation: The work grows directly with the number of colors; doubling colors doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the program's work grows in a straight line with the number of colors to print.

Common Mistake

[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.

Interview Connect

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.

Self-Check

"What if we replaced the array with a linked list of colors? How would the time complexity change?"