Westonci.ca is the premier destination for reliable answers to your questions, provided by a community of experts. Experience the ease of finding precise answers to your questions from a knowledgeable community of experts. Experience the ease of finding precise answers to your questions from a knowledgeable community of experts.

Matching parentheses. An math expression may have a number of parentheses like (, ), [, ], { and }. Each openning parenthesis (, or [, or { must be macthed by a corresponding closing parenthsis ), or ] or }. For example, 12 { 34 / [ 6 * ( 55 - 10 ) / ( 100 20 ) ] } has matched pairs of parentheses, while 12 { 34 / ( 6 * ) ] } does not. Write a function to check whether an input math expression has matched parentheses. The header of the function is given as follows:
bool match( const char exp [ ], const int s);
The input math express is store in the char array exp, and the size of exp is s. It returns true if all parentheses are matched or false otherwise.

Sagot :

C++ Code

#include
using namespace std;

bool match(const char exp[],const int s)
{
// declare a character array to perform stack operations
char stack[s];

// declare top and initialize to -1 and flag to 0
int top=-1,i,flag=0;

// visit all characters in the expression string
for(i=0;i {
// if the character is [ or ( or { then push it into stack
if(exp[i]=='[' || exp[i]=='(' || exp[i]=='{')
{
top++;
stack[top]=exp[i];
}
// if the character is ] or ) or } then check conditions
else if(exp[i]==']' || exp[i]==')' || exp[i]=='}')
{
// check stack is empty or not
if(top!=-1)
{
// check all possible failure conditions
if(exp[i]==')' && (stack[top] == '{' || stack[top]=='['))
{
flag = 1;
break;
}
else if(exp[i]==']' && (stack[top] == '{' || stack[top]=='('))
{
flag = 1;
break;
}
else if(exp[i]=='}' && (stack[top] == '(' || stack[top]=='['))
{
flag = 1;
break;
}
top--;
}
else
{
flag=1;
break;
}
}
}
// after visiting all characters of expression string check if stack is not empty and flag is 1. if any one of the condition is true return false. otherwise return true

if(top>=0 || flag==1)
return false;
else
return true;
}

int main()
{

// declare character array to store expression
char exp[10000];
cout<<"Enter an Expression"<
// read expression from user
cin.getline(exp, 10000);
int s=0;

// find the length of the expression string
for(int i=0;exp[i]!='\0';i++)
{
s++;
}

// call the match function
bool status = match(exp,s);

// print the result based on value returned by match() function
if(status == 1)
cout<<"true"< else
cout<<"false"<
}


Sample Input/Output is attached
View image Talanat
Thank you for visiting our platform. We hope you found the answers you were looking for. Come back anytime you need more information. Thank you for choosing our platform. We're dedicated to providing the best answers for all your questions. Visit us again. Westonci.ca is your go-to source for reliable answers. Return soon for more expert insights.