DSA_Assignment[1]
DSA_Assignment[1]
Theory
1. Infix Expression
● Example: (A + B) * (C - D)
● Example: * + A B - C D
● Example: A B + C D - *
Given:
Infix: (A + B) * (C - D)
Conversions:
● Prefix: * + A B - C D
● Postfix: A B + C D - *
#include <iostream>
#include <stack>
#include <cctype>
using namespace std;
int main() {
string postfix = "52+83-*"; // (5+2)*(8-3)
cout << "Result: " << evaluatePostfix(postfix) << endl;
return 0;
}
Output:
Result: 35
#include <iostream>
#include <stack>
#include <string>
#include <algorithm>
#include <cmath>
using namespace std;
switch(c) {
case '+': st.push(val1 + val2); break;
case '-': st.push(val1 - val2); break;
case '*': st.push(val1 * val2); break;
case '/': st.push(val1 / val2); break;
case '^': st.push(pow(val1, val2)); break;
}
}
}
return st.top();
}
int main() {
string prefix = "-*+52 83"; // equivalent to (5+2)*(8-3)
cout << "Result: " << evaluatePrefix(prefix) << endl;
return 0;
}
Output:
Result: 35
#include <iostream>
#include <stack>
#include <string>
#include <cctype>
#include <cmath>
using namespace std;
if (isdigit(c)) {
int value = 0;
while (i < expression.length() && isdigit(expression[i])) {
value = (value * 10) + (expression[i] - '0');
i++;
}
i--;
values.push(value);
}
else if (c == '(') {
ops.push(c);
}
else if (c == ')') {
while (!ops.empty() && ops.top() != '(') {
int val2 = values.top(); values.pop();
int val1 = values.top(); values.pop();
char op = ops.top(); ops.pop();
values.push(applyOperator(val1, val2, op));
}
ops.pop();
}
else if (c == '+' || c == '-' || c == '*' || c == '/' || c == '^') {
while (!ops.empty() && precedence(ops.top()) >= precedence(c)) {
int val2 = values.top(); values.pop();
int val1 = values.top(); values.pop();
char op = ops.top(); ops.pop();
values.push(applyOperator(val1, val2, op));
}
ops.push(c);
}
}
while (!ops.empty()) {
int val2 = values.top(); values.pop();
int val1 = values.top(); values.pop();
char op = ops.top(); ops.pop();
values.push(applyOperator(val1, val2, op));
}
return values.top();
}
int main() {
string infix = "(3+5)*2-(8/4)^2";
cout << "Result: " << evaluateInfix(infix) << endl;
return 0;
}
Output:
Result: 12