I wrote a program which is used to evaluate postfix expression, I am not getting any compiler error/warnings but I am not getting the correct output, which probably means the issue is with the calculation but I don't know where.
My Code:
#include <ctype.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAX 20
char s[MAX], top = 0;
void main() {
char postfix[MAX], ch;
int i, op1, op2, res;
clrscr();
printf("\n\t\t program to evaluate postfix expression");
printf("\n\t\t.......");
printf("\n enter the postfix expression:\n");
scanf("%s", &postfix);
for (i = 0; i < strlen(postfix); i ) {
ch = postfix[i];
if (isdigit(ch))
push(ch = '0');
else {
op2 = pop();
op1 = pop();
switch (ch) {
case ' ':
res = op1 op2;
break;
case '-':
res = op1 - op2;
break;
case '*':
res = op1 * op2;
break;
case '/':
res = op1 / op2;
break;
case '^':
res = pow(op1, op2);
break;
default:
printf("invalid choice");
}
push(res);
}
}
printf("result of above expression is:%d\n", pop());
getch();
}
push(int element) {
top;
s[top] = element;
}
int pop() {
int element;
element = s[top];
--top;
return (element);
}
CodePudding user response:
You should fix the typo and change push(ch = '0');
to
push(ch - '0');
ch
is a character, isdigit(ch)
, or better isdigit((unsigned char)ch)
tells you it is a digit, ch
- '0'is the digit value, a number in the range
0to
9`.
Your code ch = '0'
stores the digit '0'
into ch
and pushes this value, which is the character code or 0
on your system, 48 in ASCII.