Evaluate an infix expression (with parentheses)?
public int EvaluateInfix(string expression) {
Stack<int> operands = new Stack<int>();
Stack<char> operators = new Stack<char>();
int i = 0;
while (i < expression.Length) {
if (char.IsWhiteSpace(expression[i])) {
i++;
continue;
if (char.IsDigit(expression[i])) {
int val = 0;
while (i < expression.Length &&
char.IsDigit(expression[i])) {
val = val * 10 + (expression[i] - '0');
i++;
operands.Push(val);
continue;
if (expression[i] == '(') {
operators.Push(expression[i]);
else if (expression[i] == ')') {
while (operators.Peek() != '(') {
ApplyOp(operands, operators);
operators.Pop(); // remove '('
Follow on:
else if (IsOperator(expression[i])) {
while (operators.Count > 0 &&
Precedence(operators.Peek()) >= Precedence(expression[i])) {
ApplyOp(operands, operators);
operators.Push(expression[i]);
i++;
while (operators.Count > 0) {
ApplyOp(operands, operators);
return operands.Pop();
bool IsOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
int Precedence(char op) {
if (op == '+' || op == '-') return 1;
if (op == '*' || op == '/') return 2;
return 0;
void ApplyOp(Stack<int> operands, Stack<char> operators) {
int b = operands.Pop();
int a = operands.Pop();
char op = operators.Pop();
int result = 0;
switch (op) {
case '+': result = a + b; break;
case '-': result = a - b; break;
case '*': result = a * b; break;
Follow on:
case '/': result = a / b; break;
operands.Push(result);
Explanation:
Standard two-stack algorithm for evaluating infix expressions considering operator
precedence and parentheses.