Delimeters
// FDS Group D
// Q.26) 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.
#include <iostream>
using namespace std;
#define MAX 50
class Stack
{
char stk[MAX];
char expr[MAX];
int top = -1;
public:
Stack();
bool isEmpty();
bool isFull();
void pushData(char);
char popData();
bool checkExpression();
};
Stack::Stack()
{
cout << "Enter The Expression\n";
cin >> expr;
cout << "Entered Expression is : " << expr << " ";
}
bool Stack::isEmpty()
{
if (top == -1)
{
return 1;
}
else
{
return 0;
}
}
bool Stack::isFull()
{
if (top == MAX - 1)
{
return 1;
}
else
{
return 0;
}
}
void Stack::pushData(char ch)
{
if (!isFull())
{
top++;
stk[top] = ch;
}
else
{
cout << "\nStack OverFlow\n";
}
}
char Stack::popData()
{
if (!isEmpty())
{
char ch = stk[top];
top--;
return ch;
}
else
{
cout << "\nStack UnderFlow\n";
}
}
bool Stack::checkExpression()
{
for (int i = 0; expr[i] != '\0'; i++)
{
if (expr[i] == '(' || expr[i] == '{' || expr[i] == '[')
{
pushData(expr[i]);
continue;
}
if (isEmpty())
{
return 0;
}
switch (expr[i])
{
case '}':
{
bool pop = popData();
if (pop == '[' || pop == '(')
{
return 0;
}
}
break;
case ']':
{
bool pop = popData();
if (pop == '{' || pop == '(')
{
return 0;
}
}
break;
case ')':
{
bool pop = popData();
if (pop == '[' || pop == '{')
{
return 0;
}
}
break;
}
}
return (isEmpty());
}
int main()
{
string userInput;
while (true)
{
Stack st;
if (st.checkExpression())
{
cout << "'Balanced Expression'\n";
}
else
{
cout << "'UnBalanced Expression'\n";
}
while (true)
{
cout << "\nDo You Want To Try For Next Expression (y/n)\n";
cin.clear();
cin.ignore(100, '\n');
getline(cin, userInput);
if (userInput == "y" || userInput == "Y")
{
break;
}
else if (userInput == "n" || userInput == "N")
{
exit(0);
}
else
{
cout << "Please Enter Correct Input\n";
continue;
}
}
}
return 0;
}
// Output
// Enter The Expression
// {}[](){{(}
// Entered Expression is : {}[](){{(} Which is 'UnBalanced Expression'
// Do You Want To Try For Next Expression (y/n)
// y
// Enter The Expression
// {[({}[]())]}
// Entered Expression is : {[({}[]())]} Which is 'Balanced Expression'
// Do You Want To Try For Next Expression (y/n)
// n
// Process exited after 33.79 seconds with return value 0
Comments
Post a Comment