#include<stdio.h> void prefix(); char stack[50]; int s[50]; char pre[50]; int p = -1; int top = -1; int rtop = -1; int xtop=-1; xpush(int elem) { s[++xtop]=elem; } int xpop() { return(s[xtop--]); } void push(char x) { stack[++top] = x; } char pop() { if(top == -1) return -1; else return stack[top--]; } int priority(char x) { if(x == '(') return 0; if(x == '+' || x == '-') return 1; if(x == '*' || x == '/') return 2; } main() { int choice; do { printf("\n\n----MENU----\n1.INFIX - PREFIX\n2.EXIT\n"); printf("Enter your choice\n"); scanf("%d",&choice); switch(choice) { case 1 : prefix();break; case 2 : printf("~~~~~ Thank You ~~~~~\n");break; default: printf("INVALID INPUT !!!!\n"); } }while(choice!=2); } void prefix() { xtop=-1;rtop=-1;p=-1; int i=0,j=0; char exp[50],rexp[50]; char *e,*r, x; printf("Enter the expression :: "); scanf("%s",exp); while(exp[i]!='\0') i++; i--; while(i>=0) { if(exp[i]==')') { rexp[j++]='('; i--; } else if(exp[i]=='(') { rexp[j++]=')'; i--; } else rexp[j++]=exp[i--]; } rexp[j]='\0'; r=rexp; while(*r != '\0') { if(isalnum(*r)) { pre[++p]=*r; } else if(*r=='(') { push(*r); } else if(*r==')') { while((x=pop())!='(') pre[++p]=x; } else { while(priority(stack[top])>=priority(*r)) pre[++p]=pop(); push(*r); } r++; } while(top != -1) { pre[++p]=pop(); } int print=p; printf("\nPrefix expression :: "); while(print!=-1) printf("%c",pre[print--]); ///////////evaluation////////////// i=0; j=0; int op1,op2; char ch; while(i!=(p+1)) { i++; ch=pre[j++]; if(isdigit(ch)) xpush(ch-'0'); else { op1=xpop(); op2=xpop(); switch(ch) { case '+':xpush(op1+op2);break; case '-':xpush(op1-op2);break; case '*':xpush(op1*op2);break; case '/':xpush(op1/op2);break; } } } printf("\n\nResult after Evaluation: %d\n",s[xtop]); }
Labels: Data Structure in C