/*
Subject: DSL Practical
Pr. No: 09
Title: In any language program mostly syntax error occurs due to unbalancing delimiter
such as (),{},[]. Write C++ program using stack to check whether given expression
is well parenthesized or not.
*/
//.........Header Files
#include<iostream>
using namespace std;
//.......Char Stack to store Expression
char stack[10];
//.....top Pointer of Stack
int top = -1;
//---------------------------Function: To check Balanced Parantheses.
void checkBalPara()
{
char ch, expr[20];
int i, flag;
cout<<"\n\n Enter the Expression([]): ";
cin>>expr;
for(i=0; expr[i] != '\0'; i++)
{
flag = 0;
if(expr[i] == '(' || expr[i] == '[' || expr[i] == '{')
{
top++;
stack[top] = expr[i];
}
else if(expr[i] == ')' || expr[i] == ']' || expr[i] == '}')
{
ch = stack[top];
top--;
switch(expr[i])
{
case ')': if(ch != '(')
flag = 1;
break;
case ']': if(ch != '[')
flag = 1;
break;
case '}': if(ch != '{')
flag = 1;
break;
default: cout<<"\n Invalid Bracket...!!!";
}
if(flag == 1)
{
cout<<"\n\t The Expression is Not Well-Paranthesized...!!!";
break;
}
}
else
{
//.....Ignore Operators and operands
}
}
if(top != -1 || flag == 1)
cout<<"\n\t The Expression is Not Well-Paranthesized...!!!";
else
cout<<"\n\t The Expression is Well-Paranthesized...!!!";
}
//------------------------------------------------------------------------
//........Main Function
int main()
{
cout<<"\n Program to check Whether Expression has Balanced Paratheses..???";
checkBalPara();
cout<<"\n\n";
return 0;
}
/*--------------------------------OUTPUT-----------------------------------
student@ioe-melab01-134:~$ g++ DSLab_Pr-09_chkPara.cpp -o a
student@ioe-melab01-134:~$ ./a
Program to check Whether Expression has Balanced Paratheses..???
Enter the Expression([]): (a+b)
The Expression is Well-Paranthesized...!!!
student@ioe-melab01-134:~$ ./a
Program to check Whether Expression has Balanced Paratheses..???
Enter the Expression([]): [(a+b)*(c-d)]
The Expression is Well-Paranthesized...!!!
student@ioe-melab01-134:~$ ./a
Program to check Whether Expression has Balanced Paratheses..???
Enter the Expression([]): {[a*(b+c)]
The Expression is Not Well-Paranthesized...!!!
student@ioe-melab01-134:~$ ./a
Program to check Whether Expression has Balanced Paratheses..???
Enter the Expression([]): [()]}
The Expression is Not Well-Paranthesized...!!!
The Expression is Not Well-Paranthesized...!!!
student@ioe-melab01-134:~$
*/