Bird
0
0
Arduinoprogramming~5 mins

Playing melodies with tone() in Arduino - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Playing melodies with tone()
O(n)
Understanding Time Complexity

When playing melodies with the tone() function, the time it takes depends on how many notes you play.

We want to know how the total time grows as the number of notes increases.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


const int buzzer = 8;
int melody[] = {262, 294, 330, 349};
int noteDurations[] = {4, 4, 4, 4};

void playMelody() {
  for (int i = 0; i < 4; i++) {
    int duration = 1000 / noteDurations[i];
    tone(buzzer, melody[i], duration);
    delay(duration * 1.3);
  }
}

This code plays a melody of 4 notes on a buzzer, each with a specific duration.

Identify Repeating Operations
  • Primary operation: The for loop that plays each note one by one.
  • How many times: It runs once for each note in the melody array.
How Execution Grows With Input

As you add more notes, the total time to play the melody grows in direct proportion.

Input Size (n)Approx. Operations
1010 notes played, so 10 loop runs
100100 notes played, so 100 loop runs
10001000 notes played, so 1000 loop runs

Pattern observation: The time grows evenly as you add more notes.

Final Time Complexity

Time Complexity: O(n)

This means the time to play the melody grows directly with the number of notes.

Common Mistake

[X] Wrong: "Playing more notes doesn't take more time because the buzzer plays fast."

[OK] Correct: Each note takes a certain time to play, so more notes mean more total time.

Interview Connect

Understanding how loops affect time helps you explain how programs handle repeated tasks, like playing sounds or processing data.

Self-Check

"What if we added a nested loop to play each note multiple times? How would the time complexity change?"