ProgrammingModerate

Which change makes the loop for (int i = 0; i < strlen(s); i++) run in linear time?

  1. A. Replace i++ with i += 2
  2. B. Replace the loop with a while that never ends
  3. C. Store n = strlen(s) before the loop and test i < n
  4. D. Move the strlen call inside the loop body

Correct answer: C. Store n = strlen(s) before the loop and test i < n

Computing strlen once removes the repeated scan. Changing the step does not change the complexity, and moving the call inside makes it worse.

More C Programming questions

Exams that ask this topic