forked from Abhishekaggarwal1998/DS-Lab-Codes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram6.cpp
135 lines (134 loc) · 1.97 KB
/
Program6.cpp
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
/* Q: Write a program to demonstrate the use of stack in converting arithmetic expression from infix notation to postfix
notation and in evaluating arithmetic postfix expression.*/
#include<iostream>
#include<stack>
#include<math.h>
#include<string.h>
#include<stdlib.h>
using namespace std;
int top=-1;
char post[100];
int prec(char ch)
{
switch(ch)
{
case '+':
return 1;
case '-':
return 1;
case '*':
return 2;
case '/':
return 2;
case '^':
return 3;
}
return -1;
}
void push(int num)
{
post[++top]=num;
}
int pop()
{
return post[top--];
}
void evaluate_postfix(char post[20],int l)
{
int n1,n2,n3,num;
for(int i=0;i<l;)
{
if(isdigit(post[i]))
{
num=post[i]-'0';
push(num);
}
else if(post[i]==' ')
{
}
else
{
n1=pop();
n2=pop();
switch(post[i])
{
case '+':
{
n3=n1+n2;
break;
}
case '-':
{
n3=n2-n1;
break;
}
case '*':
{
n3=n1*n2;
break;
}
case '/':
{
n3=n2/n1;
break;
}
case '^':
{
n3=pow(n2,n1);
break;
}
}
push(n3);
}
i++;
}
cout<<"The result of expression is "<<pop();
}
int main()
{
char a[100];
char post[100];
int k=0;
cout<<"enter the infix expression"<<endl;
cin>>a;
stack<char>s;
for(int i=0;a[i]!='\0';i++)
{
if(a[i]>='0' && a[i]<='9')
{
post[k]=a[i];
k++;
}
else if(a[i]=='(')
s.push(a[i]);
else if(a[i]==')')
{
while(s.top()!='(')
{
post[k]=s.top();
k++;
s.pop();
}
s.pop();
}
else if(a[i]=='*'|| a[i]=='/'|| a[i]=='+'|| a[i]=='-'|| a[i]=='^')
{
while(prec(a[i]) < prec(s.top()))
{
post[k]=s.top();
k++;
s.pop();
}
s.push(a[i]);
}
}
cout<<"Postfix Expression : ";
int l=strlen(post);
for(int i=0;i<k;i++)
{
cout<<post[i];
}
cout<<endl;
evaluate_postfix(post,l);
return 0;
}