ProgrammingHardAccenture · Cognizant
A string of parentheses "(()())((" is scanned by the procedure below. The variable open counts unmatched '(' at the end, and the procedure prints it. What is printed?
A string of parentheses "(()())((" is scanned by the procedure below. The variable open counts unmatched '(' at the end, and the procedure prints it. What is printed?
open = 0
for each character ch
if ch == '(' then open = open + 1
else if open > 0 then open = open - 1
end for
Print open- A. 6
- B. 3
- C. 8
- D. 2
Correct answer: D. 2
Each ')' matches the most recent open '(', and the string leaves two unmatched opening brackets at the end. Printing the length minus the counter gives 6, counting closing brackets gives 3, and the length of the string is 8.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- 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…
- The number of trailing zeros in the decimal form of 2^20 5^3 is found by the procedure below, which divides out factors of 10 one at a…
- The procedure below computes the integer square root of 200 by testing r = 0, 1, 2, ... and stopping at the largest r with (r + 1) (r + 1)…