Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- https://onlinegdb.com/2lTyzz6y5
- #include <stdio.h>
- #include <stdlib.h>
- #include <ctype.h>
- #define MAX_SIZE 100
- char stack[MAX_SIZE];
- int top=-1;
- void push(char item){
- if(top >= MAX_SIZE-1){
- printf("Stack Overflow\n");
- return;
- }
- stack[++top]=item;
- }
- char pop(){
- if (top<0){
- printf("Stack Underflow\n");
- return -1;
- }
- return stack[top--];
- }
- int precedence(char symbol){
- switch(symbol){
- case '+':
- case '-': return 1;
- case '*':
- case '/':
- case '%': return 2;
- case '^': return 3;
- default: return 0;
- }
- }
- int isOperator(char symbol){
- return (symbol == '+' || symbol == '-' || symbol == '*' || symbol == '/' || symbol == '%' || symbol == '^');
- }
- void infixToPostfix(char infix[],char postfix[]) {
- int i=0;
- int j=0;
- char item, temp;
- while(infix[i]!='\0' && infix[i]!='\n') {
- item = infix[i];
- if(isalnum(item))
- postfix[j++] = item;
- else if (item == '(')
- push(item);
- else if(item==')')
- while (top!= -1 && (temp = pop())!='(')
- postfix[j++] = temp;
- else if (isOperator(item)) {
- while (top != -1 && precedence(stack[top]) >= precedence(item))
- postfix[j++] = pop();
- push(item);
- }
- i++;
- }
- while(top!=-1)
- postfix[j++]=pop();
- postfix[j]='\0';
- }
- int evaluatePostfixExpression(char postfix[]) {
- int top=-1;
- int i=0;
- char item;
- int operand1, operand2,result;
- while(postfix[i]!='\0'){
- item=postfix[i];
- if (isalnum(item))
- stack[++top]=item-'0';
- else if (isOperator(item)) {
- operand2 = stack[top--];
- operand1 = stack[top--];
- switch(item){
- case '+':
- result = operand1 + operand2;
- break;
- case '-':
- result = operand1 - operand2;
- break;
- case '*':
- result = operand1 * operand2;
- break;
- case '/':
- result = operand1 / operand2;
- break;
- case '%':
- result = operand1 % operand2;
- break;
- case '^':
- result = 1;
- for (int j=0;j<operand2;j++)
- result *= operand1;
- break;
- }
- stack[++top]=result;
- }
- i++;
- }
- return stack[top];
- }
- int main() {
- char infixExpression[MAX_SIZE];
- char postfixExpression[MAX_SIZE];
- printf("Infix expression: ");
- scanf("%s", infixExpression);
- infixToPostfix(infixExpression, postfixExpression);
- printf("Postfix expression: %s\n", postfixExpression);
- int result = evaluatePostfixExpression(postfixExpression);
- printf("Result: %d\n", result);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement