Vous êtes sur la page 1sur 2

# include<stdio.h> # include<conio.

h> /*program to evaluate the given postfix expression*/ typedef struct { int a[100]; int top; }STACK; void push(STACK *s,int x) { if(s->top==99) printf("STACK OVERFLOW\n"); else s->a[++s->top]=x; } int pop(STACK *s) { int x; if(s->top<0) printf("STACK UNDERFLOW\n"); else { x=s->a[s->top--]; return x; } } int operation(int p1,int p2,char op) { switch(op) { case '+':return p1+p2; case '*':return p1*p2; case '-':return p1-p2; case '/':return p1/p2; } } int evaluate(char pos[]) { STACK s1; int p1,p2,result,i; s1.top=-1; for(i=0;pos[i]!='\0';i++) if(isdigit(pos[i])) push(&s1,pos[i]-'0');/*use to find the integer value of it*/ else { p2=pop(&s1); p1=pop(&s1); result=operation(p1,p2,pos[i]); push(&s1,result);

}/*end of for loop*/ return pop(&s1); } void main() { char postfix[100]; clrscr(); printf("Please Enter the VALID POSTFIX string\n\n Operands are SINGLE DIGIT\n\n"); gets(postfix); printf("The Result is==>%d",evaluate(postfix)); getch(); }/*end of main*/

Algorithm: Postfix Expression :Algorithm STEP 1 : Read the given postfix expression into a string called postfix. STEP 2 : Read one character at a time & perform the following operations : 1. If the read character is an operand, then convert it to float and push it onto the stack. 2. If the character is not an operand, then pop the operator from stack and assign to OP2. Similarly, pop one more operator from stack and assign to OP1. 3. Evaluate the result based on operator x. 4. Push the result (based on operator x) onto the stack. STEP 3 : Repeat STEP 2 till all characters are processed from the input string. STEP 4 : Return the result from this procedure or algorithm and display the result in main program. Read more: http://wiki.answers.com/Q/Write_a_program_in_C_language_to_evaluate_a_Postfix_expressio n_by_using_a_STACK_Illustrate_the_algorithm_with_the_help_of_an_example#ixzz1VfrWPhFv

Vous aimerez peut-être aussi