Write the code to check for balanced parenthesis in a C++ program. Please be spe
ID: 3755217 • Letter: W
Question
Write the code to check for balanced parenthesis in a C++ program. Please be specific on the skipping of characters as well as the error reporting
C++ is empty. Here is the algorithm: program ends successfully after the end of the program is reached and the stack delimiterMatching (file) read character ch from file: while not end of file if ch is C T, or f push (ch) i else if ch is), 1 or ' ch and popped off delimiter do not match failure if else if ch is / read the next character if this character is skip all characters until «+/"is found and report an e if the end offile is reached before " " is encountered: else ch the character read in; continue // go to the beginning of the loop; // else ignore other characters; read next character ch from file if stack is empty successi else failureExplanation / Answer
//C++ program
#include<iostream>
#include<stack>
using namespace std;
bool matchParenthesis(string exp)
{
stack<char> st;
char x;
for (int i=0; i<exp.length(); i++)
{
if (exp[i]=='('||exp[i]=='['||exp[i]=='{')
{
st.push(exp[i]);
continue;
}
if (st.empty())
return false;
switch (exp[i])
{
case ')':
x = st.top();
st.pop();
if (x=='{' || x=='[')
return false;
break;
case '}':
x = st.top();
st.pop();
if (x=='(' || x=='[')
return false;
break;
case ']':
x = st.top();
st.pop();
if (x =='(' || x == '{')
return false;
break;
}
}
return (st.empty());
}
int main()
{
string expression;
cout<<"Enter expression : ";
cin>>expression;
if (matchParenthesis(expression))
cout << expression<<" is Balanced";
else
cout << expression<<" is not Balanced";
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.