ProgrammingVery hardProduct company OA · code-tracing level
What will be the output of the following pseudocode? (Arrays are indexed from 0.)
What will be the output of the following pseudocode? (Arrays are indexed from 0.)
Integer a[8] = {1, 2, 3, 4, 6, 7, 8, 9}
Integer i = 0, j = 7, c = 0
while (i < j)
if (a[i] + a[j] <= 10)
c = c + (j - i)
i = i + 1
else
j = j - 1
end if
end while
Print c- A. 12
- B. 28
- C. 15
- D. 16
Correct answer: D. 16
Since the array is sorted, when a[i] + a[j] ≤ 10 every partner between i + 1 and j also works, so the code adds j − i pairs at once. It counts pairs with sum ≤ 10: partners of 1 — 7 (all, since 1 + 9 = 10); of 2 — 3, 4, 6, 7, 8 (5); of 3 — 4, 6, 7 (3); of 4 — 6 (1). Total 16. 28 = C(8, 2) counts all pairs; 15 misses the boundary pair 1 + 9 = 10.
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? (Arrays are indexed from 0; a 'from a down to b' loop does nothing when a < b.)…
- What will be the output of the following pseudocode? // 32-bit signed integers; overflow wraps around (two's complement) Integer f = 1 for…
- What will be the output of the following pseudocode? Integer a = 100, b = 7, steps = 0 while (a != b) if (a > b) a = a - b else b = b - a…
- What will be the output of the following pseudocode? (/ is integer division; calls counts every call, including the first.) Integer calls…
- What will be the output of the following pseudocode? (^ is bitwise XOR and >> is a right shift.) Integer g = 59, n = 0 while (g > 0) n = n…
- How many times does the body of this loop run? // c is an 8-bit unsigned integer: it holds 0 to 255 and arithmetic wraps modulo 256…