C Program to implement Postfix expression evaluation for multiple digits number - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

C Program to implement Postfix expression evaluation for multiple digits number

Share This
C Program to implement Postfix expression evaluation for multiple digits number
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
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#define SIZE 50
int top=-1;
push(int *stack,int item)
{
stack[++top]=item;
}
int pop(int *stack)
{
return(stack[top--]);
}
int main()
{
char *pofx,ch;
int i=0,op1,op2,*stack;
pofx=(char *)malloc(sizeof(char)*SIZE);
stack=(int *)malloc(sizeof(int)*SIZE);
printf("\n....Please!! enter ; after every operand and operator.......\n");
/*here ; is used for delimeter*/
printf("enter the postfix expression:");
scanf("%s",pofx);
//scan the symbols from left to right one after another
while(i<strlen(pofx))
{
if(isdigit(pofx[i])) //If operand push to stack
{
int opr=0;
while(pofx[i]!=';')
{
opr=(opr*10)+(pofx[i]-'0');/*pofx[i]-'0' is used for converting character to integer*/
i++;
}
/* if the symbol is operand then push into stack*/
push(stack,opr);
}
else if(pofx[i]==';')
{
i++;
}
else //If symbol is operator then pop top two elements from stack and push back the result into stack
{
ch=pofx[i];
op2=pop(stack);
op1=pop(stack);
switch(ch)
{
case '+': push(stack,(op1+op2));
break;
case '-': push(stack,(op1-op2));
break;
case '*': push(stack,(op1*op2));
break;
case '/': push(stack,(op1/op2));
break;
case '^': push(stack,(pow(op1,op2)));
break;
}
i++;
}
}
printf("\nresult after evaluation:%d\n",stack[top]);
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX



Happy Exploring!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.