Showing posts with label evaluation of postfix. Show all posts
Showing posts with label evaluation of postfix. Show all posts

Oct 11, 2011

C Program for Evaluation of Postfix Expression

C Program for Evaluation of Postfix Expression In this program we evaluate the Postfix Expression, using the stack. For example, 456*+7- is the postfix expression, from left one by one it is inserted into the stack, and after evaluation the answer is 27. Read more about C Programming Language .

/***********************************************************
* You can use all the programs on  www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact info@c-program-example.com
* To find more C programs, do visit www.c-program-example.com
* and browse!
* 
*                                  Happy Coding
***********************************************************/


#define SIZE 50            /* Size of Stack */
#include <ctype.h>
int s[SIZE];
int top=-1;       /* Global declarations */

push(int elem)
{                       /* Function for PUSH operation */
 s[++top]=elem;
}

int pop()
{                      /* Function for POP operation */
 return(s[top--]);
}

main()
{                         /* Main Program */
 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;
   }
  }
 }
 printf("\n Given Postfix Expn: %s\n",pofx);
 printf("\n Result after Evaluation: %d\n",s[top]);
}
 
Read more Similar C Programs
Data Structures

Learn C Programming
You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it


(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!