Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- char stack[100];
- int top = -1;
- char ch;
- void push(char elem){
- stack[++top] = elem;
- }
- char pop(){
- return (stack[top--]);
- }
- void evalutation(char postfix[50]){
- int j=0, operand1, operand2;
- while((ch=postfix[j++]) != '\0'){//jth character of postfix string will be stored in ch
- if(ch >= '0' && ch <= '9') push(ch - '0');//if ch is a number, number will be pushed on top of stack
- else{//if ch is an operator
- operand2=pop();//2 operands will be popped
- operand1=pop();
- switch(ch){//the operation will be done and pushed on top of the stack
- case '+': push(operand1 + operand2); break;
- case '-': push(operand1 - operand2); break;
- case '*': push(operand1 * operand2); break;
- case '/': push(operand1 / operand2); break;
- }
- }
- }
- }
- int precidence(char elem){
- switch (elem){ // | ( | < | +,- | < | *,/ |
- case '(': return 1;
- case '+':
- case '-': return 2;
- case '*':
- case '/': return 3;
- default: return 0;
- }
- }
- void convert(char infix[50], char postfix[50]){
- int i = 0, j = 0; //i and j will be indexes for the infix & postfix strings
- while ((ch = infix[i++]) != '\0'){//ith character will be stored in ch
- if (ch == '(') push(ch);//if ch is (, it will be on top of the stack
- else if (ch >= '0' && ch <= '9') postfix[j++] = ch;//if ch is 0-9, add to postfix string
- else if (ch == ')'){//if ch is ),
- while (stack[top] != '(')//Until stack's top is not (,
- postfix[j++] = pop();//pop elements from stack, add to postfix string
- pop();//pop the (
- } else{// if ch is an operator
- while (precidence(stack[top]) >= precidence(ch))//if top's character's precidence is >= ch's,
- postfix[j++] = pop();//pop the character on top of the stack and add it to the postfix string
- push(ch);//push operator on top of the stack
- }
- }
- while (top != -1) postfix[j++] = pop();//Until the stack doesn't become emty, pop the top element and add to postfix string
- postfix[j] = '\0';//add null character at the end of postfix string to indicate end of string
- }
- int main(){
- char infix[50], postfix[50];//infix and postfix strings created
- printf("\nInfix Expression:\t");
- gets(infix);//infix string is inputted
- convert(infix, postfix);//call for converting infix string to postfix
- printf("\nPostfix Expression:\t%s\n", postfix);//print the postfix string
- evalutation(postfix);//call for evaluating postfix string
- printf("\nPostfix Evaluation:\t%d\n",stack[top]);//the value on top will be the answer
- return 0;
- }
- //Output:-
- //>C:\programs\"in2post"
- //Infix Expression: 7-(2*3+5)*(8-4/2)
- //Postfix Expression: 723*5+842/-*-
- //Postfix Evaluation: -59
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement