What is Prefix notation?
A prefix notation is another form of expression but it does not require other information such as precedence and associativity, whereas an infix notation requires information of precedence and associativity. It is also known as polish notation. In prefix notation, an operator comes before the operands.
Prefix form: <operator> <operand> <operand>.
Example:
A+B -> This is Infix notation.
+AB -> This is Prefix notation.
source code:
#include<iostream>
#include<stack>
using namespace std;
int EvaluatePrefix(string exp);
bool IsNumber(char ch);
bool IsOperator(char ch);
int PerformOperation(char ch, int op1, int op2);
int main()
{
cout << "Prefix form: <operator> <operand> <operand>." << endl;
string exp;
cout << "\nEnter Prefix Expression: ";
cin >> exp;
int result = EvaluatePrefix(exp);
cout << "\nResult = " << result << endl;
return 0;
}
//
int EvaluatePrefix(string exp)
{
stack<char> s;
for (int i = exp.length(); i >= 0; i--)
{
if (IsNumber(exp[i]))
{
s.push(exp[i]-'0');
}
else if (IsOperator(exp[i]))
{
int op1 = s.top(); s.pop();
int op2 = s.top(); s.pop();
int result = PerformOperation(exp[i],op1,op2);
s.push(result);
}
}
return s.top();
}
//
bool IsNumber(char ch)
{
if (ch >= '0' && ch <= '9')
return true;
return false;
}
//
bool IsOperator(char ch)
{
if (ch == '+' || ch == '-' || ch == '*' || ch == '/')
return true;
return false;
}
//
int PerformOperation(char ch, int op1, int op2)
{
if (ch == '+') return op1 + op2;
else if (ch == '-') return op1 - op2;
else if (ch == '*') return op1 * op2;
else if (ch == '/') return op1 / op2;
else return -1;
}
For support me: https://www.patreon.com/code12hub
No comments:
Post a Comment