ProgrammingModerate

A matrix of n x n values is read and the program needs the sum of all cells above the main diagonal. What is the cost, and is it correct to loop with j from i + 1?

  1. A. O(n^2) time, and looping with j from i + 1 visits each cell above the diagonal exactly once
  2. B. O(n) time, since only the diagonal matters
  3. C. O(n^3) time, since the loop is nested twice
  4. D. O(n^2) time, but cells on the diagonal are counted twice

Correct answer: A. O(n^2) time, and looping with j from i + 1 visits each cell above the diagonal exactly once

There are about n^2 / 2 cells above the diagonal, all visited once with j starting at i + 1. Cells on the diagonal are never included.

More C Programming questions

Exams that ask this topic