From ebfab4e9b05529b66420b348ee25c3e862224de6 Mon Sep 17 00:00:00 2001 From: Ashish Rana <98229499+arrobotics@users.noreply.github.com> Date: Thu, 27 Oct 2022 21:51:07 +0530 Subject: [PATCH] postficcpp --- Assignment 4/postfix.cpp | 58 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 Assignment 4/postfix.cpp diff --git a/Assignment 4/postfix.cpp b/Assignment 4/postfix.cpp new file mode 100644 index 0000000..4631e15 --- /dev/null +++ b/Assignment 4/postfix.cpp @@ -0,0 +1,58 @@ +#include +#include +#include +using namespace std; +// The function calculate_Postfix returns the final answer of the expression after calculation +int calculate_Postfix(string post_exp) +{ + stack stack; + int lenth = post_exp.length(); + // loop to iterate through the expression + for (int i = 0; i < lenth; i++) + { + + if ( post_exp[i] >= '0' && post_exp[i] <= '9') + { + stack.push( post_exp[i] - '0'); + } + // if the character is an operator we enter else block + else + { + // pop the top two elements from the stack and save them in two integers + int a = stack.top(); + stack.pop(); + int b = stack.top(); + stack.pop(); + //performing the operation on the operands + switch (post_exp[i]) + { + case '+': // add + stack.push(b + a); + break; + case '-': // sub + stack.push(b - a); + break; + case '*': // mul + stack.push(b * a); + break; + case '/': // div + stack.push(b / a); + break; + case '^': // exp + stack.push(pow(b,a)); + break; + } + } + } + //the calculated result + return stack.top(); +} +// driver function +int main() +{ + //we save the postfix expression to calculate in postfix_expression string + string postfix_expression = "70+65^2*5/-"; + cout<<"The answer after calculating the postfix expression is : "; + cout<