#include <stdio.h>
#include <ctype.h>
#define MAX 100
int stack[MAX];
int top = -1;
// Push
void push(int x) {
stack[++top] = x;
}
// Pop
int pop() {
return stack[top--];
}
// Evaluate postfix expression
int evaluate(char exp[]) {
int i = 0, a, b;
while (exp[i] != '\0') {
// If operand (digit)
if (isdigit(exp[i])) {
push(exp[i] - '0'); // convert char to int
}
else {
b = pop();
a = pop();
switch (exp[i]) {
case '+': push(a + b); break;
case '-': push(a - b); break;
case '*': push(a * b); break;
case '/': push(a / b); break;
}
}
i++;
}
return pop();
}
// Main
int main() {
char exp[100];
printf("Enter postfix expression: ");
scanf("%s", exp);
int result = evaluate(exp);
printf("Result = %d\n", result);
return 0;
}
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter