ProgrammingHardAccenture · Cognizant pattern

How many times is count incremented?

How many times is count incremented?
Integer n = 4, count = 0
for (each i from 1 to n)
    for (each j from 1 to i * i)
        if (j mod i == 0)
            for (each k from 1 to j)
                count = count + 1
            end for
        end if
    end for
end for
Print count
  1. A. 30
  2. B. 65
  3. C. 40
  4. D. 100

Correct answer: B. 65

For each i the innermost loop runs only when j = i, 2i, ..., i·i, adding j each time: i × (1 + 2 + ... + i) = i²(i + 1)/2. That gives 1 + 6 + 18 + 40 = 65.

More Pseudocode and Code Tracing questions

Exams that ask this topic