Experiment-6 dsa
Experiment-6 dsa
AIM:
Supported operators: +, -, *, /, %, ^.
PSEUDO CODE:
BEGIN
FUNCTION precedence(op)
o RETURN 1
o RETURN 2
4. ELSE
o RETURN 0
FUNCTION is Operand(c)
o ELSE IF c is ')' THEN WHILE the top of the stack is not '(':
WHILE the stack is not empty AND precedence of top of stack >= precedence
of c:
THEORY:
The process of converting an infix expression (where operators are placed between operands) into a
postfix expression (where operators follow the operands) is essential for evaluating arithmetic
expressions without the need for parentheses or operator precedence during evaluation.
Infix Expression:
Infix notation is the common way of writing expressions where operators are placed between
operands. Example: A + B, 3 * (A + B), etc. It requires parentheses to explicitly define the order of
operations.
Postfix Expression:
In postfix notation, operators come after operands. Example: A B + (instead of A + B). Postfix
expressions do not require parentheses because the order of operations is clearly defined by the
position of the operators.
Operator Precedence:
In infix expressions, different operators have different levels of precedence (e.g., * and / have higher
precedence than + and -). In postfix expressions, the position of operators ensures that the correct
precedence is automatically followed, eliminating the need for parentheses.
CODE:
#include <iostream>
#include <stack>
#include <string>
#include <cctype>
#include <cmath>
return 0;}
stack<char> s;
string postfix = "";
if (isOperand(current)) {
postfix += current;
} else if (current == '(') {
s.push(current);
} else if (current == ')') {
postfix += s.top();
s.pop();
} else {
while (!s.empty() && precedence(s.top()) >= precedence(current)) {
postfix += s.top();
s.pop();
s.push(current);
while (!s.empty()) {
postfix += s.top();
s.pop();
}
return postfix;
int main() {
string infix;
return 0;
CONCLUSION:
Converting an infix expression (where operators like +, -, *, / are placed between operands) into a
postfix expression (where operators come after the operands) makes it easier for computers to
evaluate math expressions. This is because, in postfix notation, we don’t need parentheses or worry
about operator precedence. The order of operations is already clear.
Using a stack (a simple data structure that works like a pile), we can easily manage the operators and
make sure they are used in the correct order. This makes the conversion process straightforward and
quick.
REFERENCE:
1. TUF (Take U Forward)