C program to evaluate the given postfix expression using Stack

Leave a Comment
//The following program in C is to convert infix expression to postfix expression
#include<stdio.h>                         //For standard input/output functions 
#include<stdlib.h>                       //For standard input/output functions 
#include<conio.h>                       //For Console related functions
 

char stack[40];                             //Stack is being defined
int top=-1;                                    //Setting the initial value of stack top element to '-1' 
char pop()                                    //Declaring a function to pop from the stack 
{
char a;
a=stack[top];
top--;
return a;                                     
//Function pop() will return the popped value 
}

void push(char item)                 
//Function for pushing the value in stack
 {
top++;
stack[top]=item;
}

int prcd(char symbol)              
//For finding the precedence value of the given arithmetic operation 
 {
switch(symbol)
{
case '+':
case '-':return 2;
break;
case '*':
case '/':return 4;
break;
case '^':
case '$':return 6;
break;
case '(':
case ')':
case '#':return 1;
break;
}
}

int isoperator(char symbol)                 
//function to check the item is a operator or not
 {
switch(symbol)
{
case '+':
case '-':
case '*':
case '/':
case '^':
case '$':
case '(':
case ')':return 1;
break;
default:return 0;
}
}

void convertip(char infix[],char postfix[])         
//Function to convert infix expression to postfix
 {
int i,symbol,j=0;
stack[++top]='#';
for(i=0;i{
symbol=infix[i];
if(isoperator(symbol)==0)
{
postfix[j]=symbol;
j++;
}
else{
if(symbol=='(')push(symbol);
else if(symbol==')')
{
while(stack[top]!='(')
{
postfix[j]=pop();
j++;
}
pop();
}
else{
if(prcd(symbol)>prcd(stack[top]))
push(symbol);
else{
while(prcd(symbol)<=prcd(stack[top]))
{
postfix[j]=pop();
j++;
}
push(symbol);
}
}
}
}
while(stack[top]!='#')
{
postfix[j]=pop();
j++;
}
postfix[j]='\0';
}
 

int main()                                         //Start of main() function
 {
char infix[20],postfix[20];
printf("Enter the valid infix string:");
gets(infix);                                     
//User enters the infix expression 
convertip(infix,postfix);
printf("The corresponding postfix string is:\n");
puts(postfix);                                
//Program prints the output postfix statement
getche();                                        //For stopping the execution of program after a keystroke 
}                                                      //End of main

0 comments: