0
0
Arduinoprogramming~5 mins

Code organization with functions in Arduino - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Code organization with functions
O(n)
Understanding Time Complexity

When we organize Arduino code using functions, it helps keep things neat and clear.

We want to see how the time to run the program changes as we call these functions more or less.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


void blinkLED(int times) {
  for (int i = 0; i < times; i++) {
    digitalWrite(LED_BUILTIN, HIGH);
    delay(100);
    digitalWrite(LED_BUILTIN, LOW);
    delay(100);
  }
}

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  blinkLED(5);
  delay(1000);
}
    

This code defines a function to blink an LED a number of times, then calls it repeatedly.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop inside the blinkLED function that runs 'times' times.
  • How many times: The loop runs exactly as many times as the 'times' argument given (5 in this example).
How Execution Grows With Input

Explain the growth pattern intuitively.

Input Size (times)Approx. Operations
10About 10 LED blinks
100About 100 LED blinks
1000About 1000 LED blinks

Pattern observation: The time to run grows directly with the number of blinks requested.

Final Time Complexity

Time Complexity: O(n)

This means the time grows in a straight line as you increase the number of times the LED blinks.

Common Mistake

[X] Wrong: "Using functions always makes the program run faster."

[OK] Correct: Functions help organize code but do not change how many times loops run or how long delays last.

Interview Connect

Understanding how functions affect time helps you write clear code and explain your choices confidently.

Self-Check

"What if we changed the blinkLED function to call itself recursively instead of using a loop? How would the time complexity change?"