LED control patterns in Embedded C - Time & Space Complexity
When controlling LEDs in patterns, it is important to know how the time taken grows as the number of LEDs or steps increases.
We want to find out how the program's running time changes when we change the pattern size.
Analyze the time complexity of the following code snippet.
void led_pattern(int n) {
for (int i = 0; i < n; i++) {
turn_on_led(i);
delay(100);
turn_off_led(i);
}
}
This code turns on each LED one by one, waits a bit, then turns it off, repeating for n LEDs.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that turns on and off each LED.
- How many times: It runs exactly n times, once for each LED.
As the number of LEDs (n) increases, the total time grows directly with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 on-off cycles |
| 100 | About 100 on-off cycles |
| 1000 | About 1000 on-off cycles |
Pattern observation: Doubling the number of LEDs doubles the work done.
Time Complexity: O(n)
This means the time grows in a straight line with the number of LEDs controlled.
[X] Wrong: "The delay inside the loop makes the time complexity exponential."
[OK] Correct: The delay adds a fixed wait each loop, so total time still grows linearly with n, not exponentially.
Understanding how loops affect time helps you explain how embedded systems handle tasks efficiently.
"What if we nested another loop inside to blink each LED multiple times? How would the time complexity change?"