Skip to content

Instantly share code, notes, and snippets.

@heytulsiprasad
Last active October 20, 2020 20:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heytulsiprasad/acefdbb1e6a2c2b87340875a89e3745c to your computer and use it in GitHub Desktop.
Save heytulsiprasad/acefdbb1e6a2c2b87340875a89e3745c to your computer and use it in GitHub Desktop.
Write a program for postfix evaluation
#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;
}
@heytulsiprasad
Copy link
Author

Output

output

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment