How a Computer Does Math

How a Computer Does Math

How a Computer Does Math

Ever wondered how a computer understands complex mathematical expressions like (3 + 5) * 7? It’s not magic — it’s logic. This blog explores how computers convert and evaluate mathematical expressions using Infix, Postfix, and Prefix notations. These conversions are essential in compilers and interpreters — the backbone of how we write and run code.

What Is Infix, Postfix, and Prefix?

  • Infix: Operators are between operands. E.g. A + B
  • Postfix (Reverse Polish Notation): Operators come after operands. E.g. AB+
  • Prefix (Polish Notation): Operators come before operands. E.g. +AB

Why Convert Infix to Postfix or Prefix?

Computers need a way to evaluate expressions without ambiguity. Infix expressions rely on parentheses and operator precedence, which can be hard to parse. Postfix and Prefix eliminate these issues and make evaluation straightforward using stacks.

Infix to Postfix Conversion

Let’s implement the Shunting Yard algorithm using a stack in C. It respects operator precedence and associativity.

#include <stdio.h>
#include <ctype.h>
#include <string.h>

#define MAX 100

char stack[MAX];
int top = -1;

int precedence(char op) {
  if(op == '^') return 3;
  if(op == '*' || op == '/') return 2;
  if(op == '+' || op == '-') return 1;
  return 0;
}

void push(char c) {
  stack[++top] = c;
}

char pop() {
  return stack[top--];
}

char peek() {
  return stack[top];
}

int isOperator(char c) {
  return (c == '+' || c == '-' || c == '*' || c == '/' || c == '^');
}

void infixToPostfix(char *infix) {
  char postfix[MAX];
  int j = 0;

  for(int i = 0; i < strlen(infix); i++) {
    char c = infix[i];

    if(isalnum(c)) {
      postfix[j++] = c;
    } else if(c == '(') {
      push(c);
    } else if(c == ')') {
      while(top != -1 && peek() != '(')
        postfix[j++] = pop();
      pop(); // remove '('
    } else if(isOperator(c)) {
      while(top != -1 && precedence(peek()) >= precedence(c))
        postfix[j++] = pop();
      push(c);
    }
  }

  while(top != -1)
    postfix[j++] = pop();

  postfix[j] = '\0';
  printf("Postfix: %s\n", postfix);
}

int main() {
  char expr[MAX];
  printf("Enter infix expression: ");
  scanf("%s", expr);
  infixToPostfix(expr);
  return 0;
}

Sample Output:

Enter infix expression: (A+B)*C
Postfix: AB+C*

Infix to Prefix Conversion

To convert to Prefix, we reverse the infix string, swap ( and ), perform postfix conversion, then reverse the result.

Steps:

  1. Reverse the infix string
  2. Swap '(' with ')' and vice versa
  3. Convert to postfix
  4. Reverse postfix to get prefix

This shows how postfix and prefix remove ambiguity, helping the computer compute expressions without any need for parentheses.

How the Computer Evaluates Postfix

Once the expression is in postfix, the computer uses a simple stack-based evaluation:

  1. Scan the expression left to right
  2. If operand → push
  3. If operator → pop 2 operands, apply operator, push result

This makes parsing and execution deterministic — no confusion about which operator to evaluate first.

Here’s a C program that evaluates a postfix expression. For simplicity, we’ll assume operands are single-digit integers and the expression is space-separated:

#include <stdio.h>

#include <stdlib.h>

#include <ctype.h>

#define MAX 100

int stack[MAX];

int top = -1;

void push(int val) {

    stack[++top] = val;

}

int pop() {

    return stack[top--];

}

int evaluatePostfix(char* expr) {

    int i = 0;

    while (expr[i] != '\0') {

        char c = expr[i];

        if (isdigit(c)) {

            push(c - '0'); // Convert char to int

        } else if (c == '+' || c == '-' || c == '*' || c == '/') {

            int b = pop();

            int a = pop();

            switch (c) {

                case '+': push(a + b); break;

                case '-': push(a - b); break;

                case '*': push(a * b); break;

                case '/': push(a / b); break;

            }

        }

        i++;

    }

    return pop();

}

int main() {

    char expr[MAX];

    printf("Enter postfix expression (no spaces, single-digit numbers): ");

    scanf("%s", expr);

    int result = evaluatePostfix(expr);

    printf("Evaluated Result: %d\n", result);

    return 0;

}

Sample Output:

Enter postfix expression: 53+2*

Evaluated Result: 16

Conclusion

Understanding how a computer does math gives you insight into how compilers, interpreters, and calculators work behind the scenes. It’s not just about code — it’s about logic and structure. If you're diving deeper into C, stacks, or building your own language someday — expression conversion is your foundation.

Comments