Write a program which uses a stack to match left and right parentheses. The user
ID: 3601265 • Letter: W
Question
Write a program which uses a stack to match left and right parentheses. The user can enter parentheses, operands and operators. If an operand or operator is encountered, ignore it. Whenever a left parenthesis is found, push it. Whenever a right parenthesis is found, pop the stack and see if the input string value is paired with the popped value. Parentheses may be of the form 0, 0, OR0 Generate the appropriate error message or specify that the parentheses are properly matched, according to the notes we previously reviewed as "Parentheses Matching Algorithm" in Notes 6.Explanation / Answer
#include<iostream>
#include<string>
using namespace std;
void push(char stack[], int &count, char a){
stack[count] = a;
count++;
}
char pop(char stack[], int &count){
int temp;
temp = count-1;
count--;
return stack[temp];
}
int main(){
string inp;
char stack[50];
cout << "Enter the expression in parenthesis :";
cin >> inp;
int count = 0;
for (int i = 0; i<inp.size();i++){
if (inp[i] == '(' || inp[i] == '{' || inp[i] == '['){
push(stack,count,inp[i]);
}
if (inp[i] == ')' || inp[i] == '}' || inp[i] == ']') {
int found = 0;
while (count > 0 && found != 1){
if (inp[i] == ')'){
if (pop(stack,count) == '('){
found = 1;
break;
}
}
if (inp[i] == '}'){
if (pop(stack,count) == '{'){
found = 1;
break;
}
}
if (inp[i] == ']'){
if (pop(stack,count) == '['){
found = 1;
break;
}
}
}
if (found == 0){
cout << "Parenthesis not matching ";
return 0;
}
}
}
cout << "Parenthesis are matching ";
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.