POSTFIX EVALUATION WITH SINGLE OR MULTI DIGIT:
Students find difficulties in finding the correct code for Postfix evaluation using Stack which works for Single as well for multidigit also;
So here is the Question Format Given::-
Question_2; Data_Structure:
Write a C program to evaluate the following POSTFIX expression. Use STACK to solve this
problem.
Here is the Correct code:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <ctype.h> | |
#define SIZE 50 | |
int s[SIZE]; | |
int top=-1; | |
int flag=0; | |
int pop() | |
{ | |
return(s[top--]); | |
} | |
int push(int elem) | |
{ | |
if(flag==1){ | |
int num; | |
num=pop(); | |
s[++top]=elem+10*num; | |
} | |
else if(flag==0){ | |
s[++top]=elem; | |
flag=1; | |
} | |
} | |
int main() | |
{ | |
char pofx[50],ch; | |
int i=0,op1,op2; | |
printf("Enter the Postfix Expression:"); | |
fgets(pofx,100,stdin); | |
while( (ch=pofx[i++]) != '\n') | |
{ | |
if(isdigit(ch)) push(ch-'0'); | |
else if(ch==' ') | |
flag=0; | |
else | |
{ | |
flag=0; | |
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; | |
default: | |
printf("Input invalid ... give proper input\n"); | |
return 0; | |
} | |
} | |
} | |
printf("Result: %d\n",s[top]); | |
} |
THANK YOU
ReplyDelete