C Program to Implement The Conversion of Infix Expression to Postfix Expression - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

C Program to Implement The Conversion of Infix Expression to Postfix Expression

Share This

#include<stdio.h> #include<stdlib.h> #include<string.h> #define SIZE 50 int top=-1; push(char *stack,char elem) { stack[++top]=elem; } char pop(char *stack) { return(stack[top--]); } int priority(char ch) //priority for different operators { if(ch=='^') { return(5); } else if(ch=='*' || ch=='/') { return(4); } else if(ch=='+' || ch=='-') { return(3); } else { return(2); } } void infix_pofix(char *infix) { int length; char *stack; static int index=0,pos=0; char symbol,temp; char *postfix; //dynamic array allocation for stack and postfix expression stack=(char *)malloc(sizeof(char)*SIZE); postfix=(char *)malloc(sizeof(char)*100); length=strlen(infix); while(index<length) { //take one by one symbol from infix expression symbol=infix[index]; //cases for different operators switch(symbol) { case '(': push(stack,symbol); break; case ')': temp=pop(stack); while(temp!='(') { /*if the symbol is closing parentheses then repeatedly pop from the stack until correspondin opening parentheses is encountered*/ postfix[pos]=temp; pos++; temp=pop(stack); } break; case '^': case '+': case '-': case '*': case '/':while(priority(stack[top])>=priority(symbol)) { /*if the precedence of the stack operator is greater or equal to precedence of incoming operator then pop and add to postfix expression, otherwise push the operator into stack*/ temp=pop(stack); postfix[pos]=temp; pos++; } push(stack,symbol); break; default:postfix[pos++]=symbol; break; } index++; } while(top>=0) { /*pop one by one symbol from the stack*/ temp=pop(stack); postfix[pos++]=temp; } //make postfix character array to string postfix[pos++]='\0'; printf("\nequivalent postfix expression\n"); printf("%s",postfix); } int main() { char *infix; infix=(char *)malloc(sizeof(char)*100); printf("\n enter the infix expression:"); scanf("%s",infix); infix_pofix(infix); return 0; }

Happy Exploring!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.