Last active
October 20, 2020 20:03
-
-
Save heytulsiprasad/acefdbb1e6a2c2b87340875a89e3745c to your computer and use it in GitHub Desktop.
Write a program for postfix evaluation
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<conio.h> | |
#include<string.h> | |
#define MAX 50 | |
int stack[MAX]; | |
char post[MAX]; | |
int top = -1; | |
void pushstack(int tmp); | |
void evaluate(char c); | |
void main() { | |
int i, l; | |
printf("Insert a postfix notation :: "); | |
gets(post); | |
l = strlen(post); | |
for (i = 0; i < l; i++) { | |
if (post[i] >= '0' && post[i] <= '9') { | |
pushstack(i); | |
} | |
if (post[i] == '+' || post[i] == '-' || post[i] == '*' || | |
post[i] == '/' || post[i] == '^') { | |
evaluate(post[i]); | |
} | |
} | |
printf("\n\nResult :: %d", stack[top]); | |
getch(); | |
} | |
void pushstack(int tmp) { | |
top++; | |
stack[top] = (int)(post[tmp] - 48); | |
} | |
void evaluate(char c) { | |
int a, b, ans; | |
a = stack[top]; | |
stack[top] = '\0'; | |
top--; | |
b = stack[top]; | |
stack[top] = '\0'; | |
top--; | |
switch (c) { | |
case '+': | |
ans = b + a; | |
break; | |
case '-': | |
ans = b - a; | |
break; | |
case '*': | |
ans = b * a; | |
break; | |
case '/': | |
ans = b / a; | |
break; | |
case '^': | |
ans = b ^ a; | |
break; | |
default: | |
ans = 0; | |
} | |
top++; | |
stack[top] = ans; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output