Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I dont know where I went wrong this program showing no error during compilatin but printing the wrong value.. please help me out

#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);
}

>Solution :

You might want to change push(ch = '0'); to

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    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, in the range0to9`.

Your code ch = '0' stores the digit '0' into ch and pushes this value, which is the character code or 0 (48 in ASCII).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading