Seven-segment display control in Arduino - Time & Space Complexity
When controlling a seven-segment display, we want to know how the time to update the display changes as we handle more digits.
We ask: How does the work grow when we show more numbers?
Analyze the time complexity of the following code snippet.
const int segmentPins[7] = {2, 3, 4, 5, 6, 7, 8};
const byte digits[10][7] = {
{1,1,1,1,1,1,0}, // 0
{0,1,1,0,0,0,0}, // 1
// ... other digits
};
void displayDigit(int digit) {
for (int i = 0; i < 7; i++) {
digitalWrite(segmentPins[i], digits[digit][i]);
}
}
This code lights up the correct segments to show one digit on a seven-segment display.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that runs 7 times to set each segment.
- How many times: Always 7 times per digit displayed, no matter which digit.
Each digit requires turning on or off 7 segments, so the work per digit is fixed.
| Input Size (n) | Approx. Operations |
|---|---|
| 1 digit | 7 operations |
| 10 digits | 70 operations |
| 100 digits | 700 operations |
Pattern observation: The work grows directly with the number of digits; more digits mean more segments to update.
Time Complexity: O(n)
This means the time to update the display grows in a straight line as you show more digits.
[X] Wrong: "Updating one digit takes longer if the digit is bigger or more complex."
[OK] Correct: The code always updates all 7 segments regardless of the digit, so time stays the same for any digit.
Understanding how loops affect performance helps you explain how your code scales when controlling hardware like displays.
"What if we changed the code to update only the segments that need to change from the previous digit? How would the time complexity change?"
