ProgrammingHard

For a char buffer of length 10^6 that is processed once, which loop is correct and fast enough?

  1. A. for (size_t i = 0, len = strlen(buf); i < len; i++) process(buf[i]);
  2. B. for (size_t i = 0; i < strlen(buf); i++) process(buf[i]);
  3. C. for (size_t i = 0; buf[i] != '\0'; i++) for (size_t j = 0; j < strlen(buf); j++) process(buf[i]);
  4. D. for (size_t i = 0; i < sizeof buf; i++) process(buf[i]);

Correct answer: A. for (size_t i = 0, len = strlen(buf); i < len; i++) process(buf[i]);

Computing the length once gives one O(n) pass. The in-loop strlen version is O(n^2). The sizeof version reads past the string, and the nested version is O(n^2) or worse.

More C Programming questions

Exams that ask this topic