A complete code block example on Postfix Evaluation in C Data Structures.
The following code snippet is complete working C-code on evaluating postfix. I have commented the code for easy understanding.
- Size of Stack
- Global declarations
- Read the postfix expressions
- Push the operand
- Operator/pop two operands
- Invalid Operator
- Printing the given postfix operations
- The result after evaluation.
/* Evaluating postfix */
#include <stdio.h>
#include <math.h>
#define SIZE 50 /* Size of Stack */
#include <ctype.h>
int s[SIZE]; int top=-1; /* Global declarations */
push(int elem) { s[++top]=elem; }
int pop() { return(s[top--]); }
main()
{
char pofx[50],ch;
int i=0,op1,op2;
printf("\n\nRead the Postfix Expression ? ");
scanf("%s",pofx);
while( (ch=pofx[i++]) != '\0')
{
if(isdigit(ch)) push(ch-'0'); /* Push the operand */
else
{ /* Operator,pop two operands */
op2=pop(); op1=pop();
switch(ch)
{
case '+':push(op1+op2);break;
case '-':push(op1-op2);break;
case '*':push(op1*op2);break;
case '/':push(op1/op2);break;
case '%':push(op1%op2);break;
case '^':push(pow(op1,op2));break;
default : printf("Invalid operator\n");
}
}
}
printf("\n Given Postfix Expn: %s\n",pofx);
printf("\n Result after Evaluation: %d\n",s[top]);
}
Conclusion
The Data Structure code will help to print the user-provided expression and gives the result after Postfix Evaluation in C programming language.

Leave a Reply