Data Structures & AlgorithmsHardTCS NQT · Infosys pattern

What value of count does this code print for n = 16?

What value of count does this code print for n = 16?
int count = 0;
for (int i = n; i > 0; i /= 2)
    for (int j = 0; j < i; j++)
        count++;
printf("%d", count);
  1. A. 80
  2. B. 16
  3. C. 31
  4. D. 64

Correct answer: C. 31

The inner loop runs i times for i = 16, 8, 4, 2, 1 (integer division ends at 0), giving 31, which is O(n). 80 = 16 × 5 assumes the inner loop always runs n times.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic