POSTFIX Eval

mail@pastecode.io avatar
unknown
plain_text
2 years ago
1.6 kB
1
Indexable
Never
#include<stdio.h>
char s[100];
int top=-1;

int isEmpty(){
    if(top==-1){
        return 1;
    }
    return 0;
}

void push(char i){
    s[++top]=i;
}

void pop(){
    s[top--]=0;
}

void display(){
    for(int i=top;i>-1;i--){
        printf("%d \n",s[i]);
    }
}
int isOperator(char ch){
    if(ch=='/'||ch=='*'||ch=='+'||ch=='-'||ch=='^'){
        return 1;
    }
    return 0;
}

int toInt(char ch){
    return ch-'0';
}

int evaluation(int a, int b, char ch){
    int value;
    switch(ch){
        case '/': value =a/b;
        break;
        case '*': value=a*b;
        break;
        case '+': value=a+b;
        break;
        case '-': value=a-b;
        break;
        case '^': value=a^b;
        break;
    }
    return value;
}

int main (){
    char str[100];
    printf("Enter the Postfix Expression:");
    scanf("%s",&str);
    printf("\n");
    for (int i=0;i<strlen(str);i++){
        if(str[i]=' '){
            continue;
        }
        else if(!isOperator(str[i])){
            int num=0;
            while(!isOperator(str[i])){
                num=num*10+toInt(str[i]);
                printf("%d",toInt(str[i]));
                i++;
            }
            i--;
            push(num);
        }
        else if(isOperator(str[i])){
            int b=s[top];
            pop();
            int a=s[top];
            pop();
            push(evaluation(a,b,str[i]));
        }
    }
    printf("Value of the expression: %d",s[top]);
    return 0;
}