Ask coding questions

← Back to all posts
Checking and evaluating expressions
sharkquik (0)


Anyone knows how to check for unclosed parentheses in an expression? Basically I'm writing a program to check the expressions and provide helpful error message.

mwilki7 (786)

You could try implementing a symbol stack.
Every time you see an opening symbol ( [ {
put it on the stack

Every time you see a closing symbol } ] )
remove the top element of the stack

If the closing symbol does not match with what's on top of the stack, then there is an error.
For instance, ( on top of the stack and you see a ] there is a problem because ] should have been a )

eankeen (997)


as a simple solution, you can have a variable counter the starts at 0. For every open parenthesis it finds, it increases counter by 1. For every closed parenthesis it finds, it decreases counter by 1. If counter is positive, then there are more open parenthesis than closed parenthesis. If counter is negative, then there are more closed parenthesis than open parenthesis.

if you are looking for a more complete solution, i'd recommend looking into abstract syntax trees (AST). they might seem complicated, but you can definitely find some very simple example and implementations online that you can model.

hope i helped :)