-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlab5.c
76 lines (68 loc) · 1.54 KB
/
lab5.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// Design,Develop and implement a program in C for the following stack applications a.
// Evaluation of suffix expression with single digit operands and operators:+,-,*,/,^,%
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include<ctype.h>
int s[20],top=-1;
int evaluate(char *);
void push(int);
int pop();
void main()
{
int res;
char post[30];
printf("enter a valid postfix expression\n");
scanf("%s",post);
res=evaluate(post);
printf("result of expression is %d",res);
//getch();
}
int evaluate(char *post)
{
int i,op1,op2,res,x;
char sym;
for(i=0;post[i]!='\0';i++)
{
sym=post[i];
if(isalpha(sym))
{
printf("enter value for %c",sym);
scanf("%d",&x);
push(x);
}
else if (isdigit(sym))
push(sym-'0');
else{
op2=pop();
op1=pop();
switch(sym)
{
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;
case '%':res=op1%op2;
break;
default:printf("Invalid operator in the expression is %c\n",sym);
exit(0);
}
push(res);
}
}
return(pop());
}
void push(int item)
{
s[++top]=item;
}
int pop()
{
return(s[top--]);
}