Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

NEED HELP WITH THIS Consider an expression that contains grouping symbols. The g

ID: 3579451 • Letter: N

Question

NEED HELP WITH THIS

Consider an expression that contains grouping symbols. The grouping symbols are parentheses, { }, [ ]. Expressions are considered to be balanced if their grouping symbols follow the following rules:

each left symbol must be followed by a right symbol with some data in between (ie. you can't have an empty pair like [ ] )

if pairs are nested , one pair must be completely nested within another.

Here is an example of a balanced expression: abc{de(fg){ijk}{l{m[n]}}o[p]}qr

Here is an example where the grouping symbols are not balanced: abc{(def}}{ghij{kl}m]

Write a method with signature boolean isBalanced(String s) that returns true if the grouping symbols within the string are properly balanced. Use a stack in your solution. You may assume that each symbol is just one character and that there are no spaces, as in the examples above.

Explanation / Answer

#include #include #define max 50 void main() { char stk[max],exp[100]; int top,i; clrscr(); top = -1; printf(" Enter an infix expression "); gets(exp); for(i=0; exp[i] != ''; i++) { if( exp[i]=='(' || exp[i] =='[' || exp[i] == '{' ) { top++; stk[top]= exp[i]; } else if ( exp[i] == ')' ) { if( stk[top] == '(' ) top--; } else { printf("Unbalanced exp"); exit(0); } } else if ( exp[i] == ']' ) { if( stk[top] == '[' ) top--; else { printf("Unbalanced exp"); exit(0); } } else if ( exp[i] == '}' ) { if( stk[top] == '{' ) top--; else { printf("Unbalanced exp"); exit(0); } } } // for if( top == -1 ) printf("Exp is balanced"); else printf("Exp is not balanced"); } // main