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- A. 10
- B. 3
- C. 11
- 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.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- What will be the output of the following pseudocode? Integer stars = 0 Procedure p(Integer n) stars = stars + 1 for (each i from 1 to n)…
- What will be the output of the following pseudocode? (& is bitwise AND on two's-complement integers) Integer n = 360 while (n > 0) Print n…
- What will be the output of the following pseudocode? (substring(s, i, k) is the k characters starting at index i; indices start at 0)…
- What will be the output of the following pseudocode? Function F(Integer n) if (n == 0) return 1 end if return n - M(F(n - 1)) End Function…
- What will be the output of the following pseudocode? (Arrays are indexed from 0) Integer a[6] = {1, 2, 3, -2, 2, 1}, c = 0, s for (each i…
- What will be the output of the following pseudocode? Integer m[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} for (each i from 0 to 2) for…