ProgrammingHardTCS NQT · Infosys

What will be the output of the following pseudocode? (a loop whose start is greater than its end runs zero times)

What will be the output of the following pseudocode? (a loop whose start is greater than its end runs zero times)
Integer count = 0
Boolean isPrime
for (each i from 1 to 30)
    isPrime = true
    for (each d from 2 to i - 1)
        if (i mod d == 0)
            isPrime = false
        end if
    end for
    if (isPrime)
        count = count + 1
    end if
end for
Print count
  1. A. 10
  2. B. 3
  3. C. 11
  4. D. 1

Correct answer: C. 11

There are 10 primes up to 30, but for i = 1 the inner loop (2 to 0) never runs, so 1 is also counted: 11. 10 forgets that i = 1 slips through, 3 ignores the reset isPrime = true (once 4 fails, nothing else counts), and 1 runs the inner loop up to d = i, so every i > 1 divides itself and only i = 1 survives.

More Pseudocode and Code Tracing questions

Exams that ask this topic