Arithmetic Notations
Arithmetic notations are different ways of writing arithmetic expressions using symbols and rules. There are three common arithmetic notations:
Infix notation: Infix notation is a way of writing mathematical expressions where the operator is placed between the two operands.. For example, the expression "3 + 4" is in infix notation.
Prefix notation: Prefix notation is also known as Polish notation. It eliminates the need for parentheses and can be evaluated without the use of precedence rules. For example, the expression "+ 3 4" is in prefix notation.
Postfix notation: Postfix notation is also known as Reverse Polish notation. It eliminates the need for parentheses and can be evaluated without the use of precedence rules. In postfix notation, the operator appears after the operands. For example, the expression "3 4 +" is in postfix notation.
Infix to Prefix Algorithm
- Create an empty stack and an empty output string.
- Reverse the infix expression: Reverse the order of all elements in the infix expression, including operands and operators.
- Iterate through the reversed infix expression from left to right.
- If the current character is an operand (number or variable), append it to the output string.
- If the current character is a closing bracket ‘)’, push it onto the stack.
- If the current character is an operator or an opening bracket ‘(‘, compare its precedence with the precedence of the operator at the top of the stack.
- If the current operator has higher precedence than the operator at the top of the stack or the stack is empty, push the current operator onto the stack.
- If the current operator has lower or equal precedence than the operator at the top of the stack, pop the operators from the stack and append them to the output string until an operator with lower precedence is encountered or the stack becomes empty. Then push the current operator onto the stack.
- If the current character is an opening bracket ‘(‘, pop the operators from the stack and append them to the output string until the corresponding closing bracket ‘)’ is encountered. Discard the closing bracket.
- Repeat steps 4 to 9 until all characters in the reversed infix expression have been processed.
- Pop the remaining operators from the stack and append them to the output string.
- Reverse the output string to obtain the prefix expression.
No comments:
Post a Comment