Answer to Question #242042 in C++ for Alan

Question #242042

Convert the expression into postfix notation and then verify if it is correct or not,direct answers for both 5conversion are not allowed for verification take dummy values for eachvariable.

a+b*(c/d-e)%(f+g*h)-i


1
Expert's answer
2021-09-25T05:57:26-0400
#include<bits/stdc++.h>
using namespace std;


int prec(char a) {
	if(a == '^')
		return 3;
	else if(a == '/' || a=='*')
		return 2;
	else if(a == '+' || a == '-')
		return 1;
	else
		return -1;
}


void infix_to_postfix(string s) {


	stack<char> stk; 
	string res;


	for(int i = 0; i < s.length(); i++) {
		char c = s[i];


		if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'))
			res += c;


		else if(c == '(')
			stk.push('(');


		else if(c == ')') {
			while(stk.top() != '(')
			{
				res += stk.top();
				stk.pop();
			}
			stk.pop();
		}


		else {
			while(!stk.empty() && prec(s[i]) <= prec(stk.top())) {
				res += stk.top();
				stk.pop();
			}
			stk.push(c);
		}
	}
	while(!stk.empty()) {
		res += stk.top();
		stk.pop();
	}
	cout << res << endl;
}


int main() {
	string expression = "a+b*(c/d-e)%(f+g*h)-i";
	infix_to_postfix(expression);
	return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS