0% found this document useful (0 votes)
37 views2 pages

DS Practical 9 o - P

Uploaded by

okaybejs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views2 pages

DS Practical 9 o - P

Uploaded by

okaybejs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Experiment 9 - Evaluate Postfix Expression.

Program:

#include <ctype.h>
#include <stdio.h>
#define MAX 20

int stack[MAX];
int top = -1;

void push(int x) {
if (top < MAX - 1) {
stack[++top] = x;
} else {
printf("Stack overflow\n");
}
}
int pop() {
if (top >= 0) {
return stack[top--];
} else {
printf("Stack underflow\n");
return 0;
}
}
int main() {
char exp[20];
char *e;
int n1, n2, n3, num;
printf("Enter the expression (postfix): ");
scanf("%s", exp);
e = exp;
while (*e != '\0') {
if (isdigit(*e)) {
num = *e - '0';
push(num);
} else {
n1 = pop();
n2 = pop();
switch (*e) {
case '+':
n3 = n2 + n1;
break;
case '-':
n3 = n2 - n1;
break;
case '*':
n3 = n2 * n1;
break;
case '/':
n3 = n2 / n1;
break;
default:
printf("Invalid operator: %c\n", *e);
return 1;
}
push(n3);
}
e++;
}
printf("\nThe result of expression %s = %d\n\n", exp, pop());

return 0;
}

Output:

You might also like