What is embedded C - Complexity Analysis
When working with embedded C, it is important to understand how the time your program takes grows as you give it more data or tasks.
We want to know how the program's running time changes when the input size changes.
Analyze the time complexity of the following code snippet.
void toggle_leds(int n) {
for (int i = 0; i < n; i++) {
// Toggle LED connected to pin i
toggle_pin(i);
}
}
This code toggles LEDs connected to pins from 0 up to n-1, one by one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that toggles each LED pin.
- How many times: It runs exactly n times, once for each LED.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 toggles |
| 100 | 100 toggles |
| 1000 | 1000 toggles |
Pattern observation: The number of operations grows directly with the number of LEDs to toggle.
Time Complexity: O(n)
This means the time to run grows in a straight line as you add more LEDs to toggle.
[X] Wrong: "The loop runs a fixed time no matter how many LEDs there are."
[OK] Correct: The loop runs once for each LED, so more LEDs mean more time.
Understanding how loops affect time helps you write efficient embedded programs that respond quickly and save power.
"What if we nested another loop inside to toggle each LED multiple times? How would the time complexity change?"