Assignment 2

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 4

C++ implementation of an expression evaluator using a stack to convert a given valid infix

expression to a postfix expression and then evaluate the postfix expression to print the result:

#include <iostream>

#include <stack>

#include <string>

using namespace std;

int precedence(char op) {

if (op == '+' || op == '-')

return 1;

if (op == '*' || op == '/')

return 2;

return 0;

string infixToPostfix(const string& expression) {

string postfix;

stack<char> stack;

for (char ch : expression) {

if (isalnum(ch))

postfix += ch;

else if (ch == '(')

stack.push(ch);

else if (ch == ')') {


while (!stack.empty() && stack.top() != '(') {

postfix += stack.top();

stack.pop();

stack.pop(); // Discard '('

} else {

while (!stack.empty() && precedence(stack.top()) >= precedence(ch)) {

postfix += stack.top();

stack.pop();

stack.push(ch);

while (!stack.empty()) {

postfix += stack.top();

stack.pop();

return postfix;

int evaluatePostfix(const string& expression) {

stack<int> stack;

for (char ch : expression) {

if (isdigit(ch))
stack.push(ch - '0');

else {

int operand2 = stack.top(); stack.pop();

int operand1 = stack.top(); stack.pop();

if (ch == '+')

stack.push(operand1 + operand2);

else if (ch == '-')

stack.push(operand1 - operand2);

else if (ch == '*')

stack.push(operand1 * operand2);

else if (ch == '/')

stack.push(operand1 / operand2); // Integer division

return stack.top();

void evaluateExpression(const string& infixExpression) {

string postfixExpression = infixToPostfix(infixExpression);

cout << "Postfix expression: " << postfixExpression << endl;

int result = evaluatePostfix(postfixExpression);

cout << "Result: " << result << endl;

}
int main() {

string infixExpression = "3 + 4 * 2 / (1 - 5) ^ 2";

evaluateExpression(infixExpression);

return 0;

This C++ code converts a given infix expression to a postfix expression using the shunting-
yard algorithm and then evaluates the postfix expression using a stack-based approach.
Finally, it prints the postfix expression and the result of the evaluation. You can replace the
infixExpression variable with any valid infix expression to test the code.

You might also like