Determining Well Parenthesis

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

IT SERVICES PRIVATE LIMITED

Determining Well-Formed Expressions with Parenthesis


The following section outlines an algorithm for determining whether or not an
expression is well formed.
A classic use of a stack is for determining whether a set of parenthesis is "well formed".
What exactly do we mean by well formed? In the case of parenthesis pairs, for an
expression to be well formed, a closing parenthesis symbol must match the last
unmatched opening parenthesis symbol and all parenthesis symbols must be matched
when the input is finished.
Consider the following table demonstrating Well-Formed Versus Ill-Formed
Expressions:

Well-Formed Expressions
(xxx[])
()[]{}
{(xxxxx)()}

Ill-Formed Expressions
(xxx[)
((
{xxxxx)()}

Why do we care about balancing parenthesis?


Because the compiler looks for balanced parenthesis in such situations as:

nested components (such as for loops, if-then statements, and while loops). The
compiler checks for matching {} pairs to denote blocks of code. If the pairs do not
match, a compiler error will occur.
mathmatical expressions. For example a = b - {(x + y) * z + 3};
array notation [ ].
function calls and function definitions. Specifically, the parameters must be
surrounded by balanced "(" ")".

Impetus xzxIT Services Pvt.Ltd.


B-16, First floor, Sant Tukaram Vyapar Sankul, Sector - 24, Nigdi, Pune, Maharashtra. India. Pin 411044.
Mobile 9970600774, 9730012775|Board 91-20-27640406|Fax 91-20-27641703
Email : admin@impetusitservices.com | Website : www.impetusits.in

IT SERVICES PRIVATE LIMITED


The Algorithm
Given an expression with characters and parenthesis, ( ), [ ], and { }, determine if an
expression is well-formed by using the following algorithm in conjunction with a stack.
Read in the expression character by character. As each character is read in:

If the character is an opening symbol (characters "(", "{", or "["), then push it
onto the stack
Else if the character is a closing symbol (characters ")", "}", or "]"), then:
o Check if the stack is empty. If it is, then there is no matching opening
symbol. The expression is not well formed.
o Else,
get the character at the top of the stack
pop the stack
compare the current closing symbol to the top symbol. If they
balance each other, then the expression is still balanced and
continue looping (reading the next character)
If the end of the expression is reached, and it is still balanced, then print
"expression is well formed"
Otherwise, print "expression is not well formed"

Impetus xzxIT Services Pvt.Ltd.


B-16, First floor, Sant Tukaram Vyapar Sankul, Sector - 24, Nigdi, Pune, Maharashtra. India. Pin 411044.
Mobile 9970600774, 9730012775|Board 91-20-27640406|Fax 91-20-27641703
Email : admin@impetusitservices.com | Website : www.impetusits.in

You might also like