Answer to Question #233836 in C for Asjad

Question #233836

3. Write a program for evaluating the value for a given postfix expression using stack data structure. 

a) Infix to Postfix

b)Prefix to Infix


1
Expert's answer
2021-09-06T23:58:55-0400


#include<iostream>
#include <string>
#include <stack>
using namespace std;


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


void InToPos(string s) {


	stack<char> st; //For stack operations, we are using C++ built in stack
	string result;


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


		// If the scanned character is
		// an operand, add it to output string.
		if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'))
			result += c;


		// If the scanned character is an
		// ‘(‘, push it to the stack.
		else if (c == '(')
			st.push('(');
		else if (c == ')') {
			while (st.top() != '(')
			{
				result += st.top();
				st.pop();
			}
			st.pop();
		}


		else {
			while (!st.empty() && prototype(s[i]) <= prototype(st.top())) {
				result += st.top();
				st.pop();
			}
			st.push(c);
		}
	}
	while (!st.empty()) {
		result += st.top();
		st.pop();
	}


	cout << result << endl;
}
bool isOp(char ch)
{
	return (ch >= 'a' && ch <= 'z') ||
		(ch >= 'A' && ch <= 'Z');
}
string PosToIn(string exp)
{
	stack<string> s;


	for (int i = 0; exp[i] != '\0'; i++)
	{
		if (isOp(exp[i]))
		{
			string op(1, exp[i]);
			s.push(op);
		}
		else
		{
			string op1 = s.top();
			s.pop();
			string op2 = s.top();
			s.pop();
			s.push("(" + op2 + exp[i] +
				op1 + ")");
		}
	}


	return s.top();
}
int main() {
	bool quit = false;
	while (!quit)
	{
		cout << "\nMENU\n";
		cout << "1 -Postfix to Infix\n";
		cout << "2 -Infix to Postfix\n";
		cout << "3 -Exit\n";
		int cmd;
		cin >> cmd;
		switch (cmd)
		{
		case 1:
		{
			cout << "Please enter expression: ";
			string exp;
			cin >> exp;
			InToPos(exp);
			break;
		}
		case 2:
		{
			cout << "Please enter expression: ";
			string exp;
			cin >> exp;
			cout<<PosToIn(exp);
			break;
		}
		case 3:
		{
			quit = true;
			break;
		}
		default:
			break;
		}
	}
	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