I tried to evaluate a postfix expression using only digits so after understanding the concept and implented the code, which I thought it was right, it didn't generate a correct answers but after I made a few changes it worked but here I want to know what is the mistake I did in the first so I cannot repeat it in the future !
These are the two codes (first one wrong and second one right )
#include <stdio.h>
#include <string.h>
int main()
{
char s[100];
int b[100]={0};
int x=0,j=0,i=0;
scanf("%s",s);
for (i=0; i<strlen(s); i++)
{
if(s[i]>=48 && s[i]<=57)
{
b[j]=s[i];
j++;
}
else
{
if (s[i]=='+')
{
x=(b[j-1]-48) + (b[j-2]-48);
b[j-2]=x;
j--;
}
else if (s[i]=='-')
{
x=(b[j-2]-48) - (b[j-1]-48);
b[j-2]=x;
j--;
}
else if (s[i]=='*')
{
x=(b[j-1]-48) * (b[j-2]-48);
b[j-2]=x;
j--;
}
else
{
x=(b[j-2]-48) / (b[j-1]-48);
b[j-2]=x;
j--;
}
}
}
printf("%d",b[0]);
return 0;
}
The correct code
#include <stdio.h>
#include <string.h>
int main()
{
char s[100];
int b[100]={0};
int x=0,j=0,i=0;
scanf("%s",s);
for (i=0; i<strlen(s); i++)
{
if(s[i]>=48 && s[i]<=57)
{
b[j]=s[i]-48; // modified
j++;
}
else
{
if (s[i]=='+')
{
x=(b[j-1]) + (b[j-2]); //modified
b[j-2]=x;
j--;
}
else if (s[i]=='-')
{
x=(b[j-2]) - (b[j-1]); // modofied
b[j-2]=x;
j--;
}
else if (s[i]=='*')
{
x=(b[j-1]) * (b[j-2]); //modified
b[j-2]=x;
j--;
}
else
{
x=(b[j-2]) / (b[j-1]); // modified
b[j-2]=x;
j--;
}
}
}
printf("%d",b[0]);
return 0;
}
in order to test the program we need to enter an expression in reverse polish notation like 32*1+
which is in infix notation is 3*2+1
so we will get a correct answer 7
Someone who doesn't know how the evaluation of Reverse Polish Notation works may not figure out the problem. Your code is correct but the algorithm is wrong.
I will take 32*1+
as an example :
For the first two numbers your code is correct but after calculating the result and pushing it to the stack, troubles begin. When it encounters an operator the next time it will subtract 48 from each of the two numbers extracted from the stack and your result is a product of that rule, which is wrong.