ProgrammingHardCAT · MBA placement
The procedure below counts the pairs i < j in the array [3, 1, 4, 1, 5] whose sum is even. What is printed?
The procedure below counts the pairs i < j in the array [3, 1, 4, 1, 5] whose sum is even. What is printed?
count = 0
for i = 0 to n - 2
for j = i + 1 to n - 1
if (a[i] + a[j]) mod 2 == 0 then count = count + 1
end for
end for
Print count- A. 4
- B. 20
- C. 6
- D. 12
Correct answer: C. 6
The odd values are 3, 1, 1 and 5, and the even value is 4, so an even pair sum needs two odd values or two even values. There are 6 such pairs among the 10 pairs. Counting odd sums gives 4, the total of pairs is 10, and counting ordered pairs gives 20.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- The procedure below collects x mod 5 for every x from 1 to 20 into a set and prints the size of the set. What is printed? seen = empty set…
- Array a = [1, 1, 1, 1] (0-based). From index i you may jump forward by at most a[i] positions. The greedy below counts the minimum number…
- The procedure below sums the decimal digits of 2^10 = 1024 once and prints the result. What is printed? x = 2^10; total = 0 while x > 0…
- The procedure below counts the inversions of the array [2, 4, 1, 3] (pairs i < j with a[i] > a[j]) by checking all pairs. What is printed?…
- The procedure below counts the integers from 1 to 29 that are divisible by 3 or by 5. What is printed? count = 0 for n = 1 to 29 if n mod…
- Read the pseudocode. a = 1, b = 1, s = 0 for i = 1 to 6 t = a + b a = b b = t if (t mod 3 == 0) s = s + t else s = s - 1 end for print s…