ProgrammingVery hardProduct company OA · code-tracing level
What will be the output of the following pseudocode? (Array positions run from 1 to 10.)
What will be the output of the following pseudocode? (Array positions run from 1 to 10.)
Integer alive[1..10] = all 1, left = 10, pos = 0, count = 0
while (left > 1)
pos = pos mod 10 + 1
if (alive[pos] == 1)
count = count + 1
if (count == 3)
alive[pos] = 0
left = left - 1
count = 0
end if
end if
end while
for (each i from 1 to 10)
if (alive[i] == 1)
Print i
end if
end for- A. 5
- B. 7
- C. 4
- D. 10
Correct answer: C. 4
This is the Josephus elimination: walking round a circle of 10 and removing every third person still present. Removal order: 3, 6, 9, 2, 7, 1, 8, 5, 10, leaving 4. (Formula check: J(1) = 0 and J(n) = (J(n − 1) + 3) mod n gives 0, 1, 1, 0, 3, 0, 3, 6, 0, 3 for n = 1…10, i.e. position 3 + 1 = 4.) 10 is the last one removed, a common confusion with the survivor.
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? (& is bitwise AND, | is bitwise OR, << and >> are shifts.) Integer x = 22, r = 0 for…
- What will be the output of the following pseudocode? (Arrays are indexed from 0; / is integer division.) Integer a[7] = {1, 3, 5, 5, 5, 7…
- What will be the output of the following pseudocode? Integer s = 0 Procedure p(Integer n) if (n == 0) return end if p(n - 1) s = s + n p(n…
- What will be the output of the following pseudocode? (/ is integer division.) Function A(Integer n) if (n <= 0) return 1 end if return B(n…
- What will be the output of the following pseudocode? (g is a global variable.) Integer g = 0 Function f(Integer n) if (n == 0) return 0…
- What will be the output of the following pseudocode? (Integers are passed by value. An array parameter receives a reference to the…