Last active
September 1, 2025 05:22
-
-
Save lakshyaraj2006/3b1d0a106edc57344bf3a78c248d7f24 to your computer and use it in GitHub Desktop.
A C program to convert infix to evaluate the postfix expression.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include<stdio.h> | |
| #include<stdlib.h> | |
| #include<string.h> | |
| #include<stdbool.h> | |
| #include<ctype.h> | |
| struct Stack { | |
| int size; | |
| int top; | |
| char *arr; | |
| }; | |
| int isFull(struct Stack * sp) { | |
| if (sp->top == sp->size-1) { | |
| return 1; | |
| } | |
| return 0; | |
| } | |
| int isEmpty(struct Stack * sp) { | |
| if (sp->top == -1) { | |
| return 1; | |
| } | |
| return 0; | |
| } | |
| int precedence(char c) { | |
| if (c == '^') { | |
| return 3; | |
| } else if (c == '*' || c == '/' || c == '%') { | |
| return 2; | |
| } else if (c == '+' || c == '-') { | |
| return 1; | |
| } else if (c == '&') { | |
| return 0; | |
| } else if (c == '|') { | |
| return -1; | |
| } | |
| return -2; | |
| } | |
| bool isOperator(char c) { | |
| if ( | |
| c == '^' || c == '&' || c == '|' || c == '/' || c == '*' || c == '+' || c == '-' | |
| ) { | |
| return true; | |
| } else { | |
| return false; | |
| } | |
| } | |
| char pop(struct Stack * sp) { | |
| if (isEmpty(sp)) { | |
| printf("Stack Undeflow! Cannot pop from the stack\n"); | |
| return -1; | |
| } | |
| else { | |
| int val = sp->arr[sp->top]; | |
| sp->top--; | |
| return val; | |
| } | |
| } | |
| void push(struct Stack * sp, char val) { | |
| if (isFull(sp)) { | |
| printf("Stack Overflow! Cannot push %d to the stack\n", val); | |
| } | |
| else { | |
| sp->top++; | |
| sp->arr[sp->top] = val; | |
| } | |
| } | |
| char stackTop(struct Stack * sp) { | |
| return sp->arr[sp->top]; | |
| } | |
| int calculate(char op, int a, int b) { | |
| switch (op) | |
| { | |
| case '/': | |
| return a/b; | |
| break; | |
| case '*': | |
| return a*b; | |
| break; | |
| case '+': | |
| return a+b; | |
| break; | |
| case '-': | |
| return a-b; | |
| break; | |
| } | |
| } | |
| int main(){ | |
| struct Stack * sp = (struct Stack *)malloc(sizeof(struct Stack)); | |
| char * exp = "1273-/215+*+"; | |
| sp->size = strlen(exp); | |
| sp->top = -1; | |
| sp->arr = (char *)malloc(sp->size * sizeof(char)); | |
| for (int i = 0; exp[i] != '\0'; i++) | |
| { | |
| if (isdigit(exp[i])) { | |
| push(sp, exp[i]); | |
| } else if(isOperator(exp[i])) { | |
| char op = exp[i]; | |
| int b = pop(sp) - '0'; | |
| int a = pop(sp) - '0'; | |
| push(sp, (calculate(op, a, b) + '0')); | |
| } | |
| } | |
| printf("%d", pop(sp) - '0'); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment