Postfix Evaluation in C

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--]); }

  char pofx[50],ch;
  int i=0,op1,op2;
  printf("\n\nRead the Postfix Expression ? ");
  while( (ch=pofx[i++]) != '\0')
    if(isdigit(ch)) push(ch-'0'); /* Push the operand */
      {        /* Operator,pop two  operands */
	op2=pop();    op1=pop();
            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]); 


The Data Structure code will help to print the user-provided expression and gives the result after Postfix Evaluation in C programming language.

Rabins Sharma Lamichhane

Rabins Sharma Lamichhane is senior ICT professional who talks about #it, #cloud, #servers, #software, and #innovation. Rabins is also the first initiator of Digital Nepal. Facebook: rabinsxp Instagram: rabinsxp

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *