ProgrammingHard

A loop walks a string with for (i = 0; i < strlen(s); i++) on a string of length 10^6. What is the total cost?

  1. A. About 5 x 10^11 character reads, which is too slow for a one-second limit
  2. B. About 10^6 reads, which is fast enough
  3. C. About 10^9 reads, which is borderline
  4. D. Constant time, since strlen is cached

Correct answer: A. About 5 x 10^11 character reads, which is too slow for a one-second limit

strlen scans the string each time, so the loop costs about n^2 / 2 = 5 x 10^11 reads. Calling strlen once fixes it.

More C Programming questions

Exams that ask this topic