ProgrammingHardTCS NQT · Accenture
A nested loop counts the pairs (i, j) with 1 <= j <= i <= 6 that also satisfy i + j even. The procedure prints the count. What is printed?
A nested loop counts the pairs (i, j) with 1 <= j <= i <= 6 that also satisfy i + j even. The procedure prints the count. What is printed?
count = 0
for i = 1 to 6
for j = 1 to i
if (i + j) mod 2 == 0 then count = count + 1
end for
end for
Print count- A. 6
- B. 12
- C. 18
- D. 9
Correct answer: B. 12
Listing the pairs with j at most i and i + j even gives 12 pairs. Requiring j < i gives 6, using all j up to 6 gives 18, and counting odd sums gives 9.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- The procedure below counts the numbers i from 1 to 100 whose binary form has exactly three 1 bits (bits are counted by repeatedly taking n…
- A string of parentheses "(()())((" is scanned by the procedure below. The variable open counts unmatched '(' at the end, and the procedure…
- The procedure below scans the string "abracadabra" from left to right and counts how many letters are repeats of an earlier letter (a…
- A string is a rotation of another when it can be obtained by moving some prefix to the end. The procedure below checks whether…
- The array [1, 2, 3, 4, 5, 6, 7] is shifted left by 2 positions by the procedure below: the element at index k is placed at index (k - 2)…
- The procedure below uses bitmasks over the set {1, 2, 3} (bit i set means element i+1 is included), so it visits the 8 subsets including…