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
  1. A. 6
  2. B. 3
  3. C. 8
  4. 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.

More Pseudocode and Code Tracing questions

Exams that ask this topic