ProgrammingHardTCS NQT · Accenture
The procedure below counts the pairs (i, j) with i < j and a[i] + a[j] = 8, for the array a = [1, 5, 3, 3, 7, 4, 6, 2]. What is printed?
The procedure below counts the pairs (i, j) with i < j and a[i] + a[j] = 8, for the array a = [1, 5, 3, 3, 7, 4, 6, 2]. What is printed?
count = 0
for i = 0 to n - 2
for j = i + 1 to n - 1
if a[i] + a[j] == 8 then count = count + 1
end for
end for
Print count- A. 4
- B. 17
- C. 9
- D. 8
Correct answer: A. 4
The matching pairs are (1,7), (5,3) twice, and (6,2), so the answer is 4. Counting with a <= test adds more pairs, the ordered count including i = j gives 9, and counting ordered pairs with i not equal to j gives 8.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- Array a = [4, 4, 6, 1, 1] has a value appearing more than once. The procedure below counts the values that appear exactly twice. What is…
- Array a = [5, -3, 5] is treated as circular. The maximum circular subarray sum (a contiguous block that may wrap around the end) is found…
- Sorted array a = [1, 3, 6, 6, 6, 9]. The lower-bound binary search below finds the first index whose value is at least x = 6. What is…
- Array a = [2, 4, 6, 8, 10]. The loop below sums i a[i] over the 0-based indices i. What is printed? total = 0 for i = 0 to 4 total = total…
- The array [0, 1, 0, 3, 12] has its zeros moved to the end while keeping the order of the other values, by a two-pointer pass that writes…
- For the array a = [7, 2, 4, 9, 1, 5] the procedure below computes the sum of the minimum of every contiguous window of length 2 (windows…