EECS 2030 E, Fall 2015

Stacking Precedence

 

Your Task

Write a program that reads from the user a mathematical expression that may contain nested precedence characters, which are the following: parentheses (), brackets [], and braces {}. For example, the input string can be:

{a-b*[c/(d+e)]+f*[g-h*{i+j*k}]-m/(n+1)+((p/[r/t]-u)-v)/w}

The program should ignore operators and operands and focus only on the above precedence characters. Specifically, it should determine whether these characters are “Balanced”, “Imbalanced”, or “Overlapping”. And accordingly output one of the three messages. See the sample runs below as examples. If there are multiple problems, output the message corresponding to the first one encountered.

Approach: Read the input string from left to right.  Ignore non-precedence characters.  Push open precedence characters onto the stack.  When a close precedence character is encountered, pop the stack and see if the two characters match. Start with the code provided here. The precedence characters are stored in two separate strings. They “match” if the two characters are at the same index in their respective strings.

 

Sample Runs

Run:

	Enter expression:
	[a+b*(c-d])
	Overlapping
    
	Enter expression:
	(a+(b-[c/d])
	Imbalanced
    
	Enter expression:
	(a+b)]-c
	Imbalanced
    
	Enter expression:
	{a-[b/(c+d)]}
	Balanced

 

 

 

Based on an exercise by H. Roumani
--- End of Exercise ---