#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAX 20
typedef struct Stack {
int top;
int item[MAX];
} Stack;
Stack stack = {-1, {}};
int isEmpty();
int isFull();
int peek();
void push(int value);
int pop();
int precedence(char symbol);
void convertToPostfix(char expression[], char postfix[]);
int evaluate(char postfix[]);
void main() {
char expression[MAX];
char postfix[MAX];
printf("\nMasukkan ekspresi: ");
gets(expression);
fflush(stdin);
convertToPostfix(expression, postfix);
printf("--------------------------\n");
printf("\033[34mekspresi\033[m: %s\n", expression);
printf("\033[33mpostfix\033[m\t: %s\n", postfix);
printf("\033[32mhasil\t\033[m: %d\n", evaluate(postfix));
printf("--------------------------\n");
}
// stack operation
int isFull() {
return stack.top == MAX;
};
int isEmpty() {
return stack.top == -1;
};
int peek() {
if (!isEmpty())
return stack.item[stack.top];
}
void push(int value) {
if (!isFull()) {
stack.top += 1;
stack.item[stack.top] = value;
}
}
int pop() {
if (!isEmpty()) {
int item = peek();
stack.top -= 1;
return item;
}
}
// * etc operation
int precedence(char symbol) {
switch (symbol) {
case '+':
case '-':
return 1;
case '/':
case '*':
return 2;
default:
return 0;
}
}
void convertToPostfix(char expression[], char postfix[]) {
int i, ii = 0;
for (i = 0; i < strlen(expression); i++) {
char symbol = expression[i];
if (isdigit(symbol)) {
postfix[ii++] = symbol;
} else if (symbol == '(') {
push(symbol);
} else if (symbol == ')') {
while (peek() != '(')
postfix[ii++] = pop();
pop();
} else {
if (precedence(symbol) > precedence(peek())) {
push(symbol);
} else {
while (precedence(symbol) <= precedence(peek()))
postfix[ii++] = pop();
push(symbol);
}
}
}
while (!isEmpty())
postfix[ii++] = pop();
postfix[ii] = '\0';
}
int evaluate(char postfix[]) {
for (int i = 0; postfix[i] != '\0'; i++) {
char symbol = postfix[i];
if (isdigit(symbol)) {
push(symbol - '0');
} else {
int number1 = pop();
int number2 = pop();
int result = 0;
switch (symbol) {
case '+':
result = number2 + number1;
break;
case '-':
result = number2 - number1;
break;
case '*':
result = number2 * number1;
break;
case '/':
result = number2 / number1;
break;
}
push(result);
}
}
return pop();
}
To embed this project on your website, copy the following code and paste it into your website's HTML: