POSTFIX AND PREFIX EXPRESSIONS LECTUER 6 NOTES.. Operator stack: This stack will be used to keep operations (+, -, *, /, ^) Order of precedence of operations– 1. Parentheses [], (),{} 2. ^ (Exponential) (R –L) 3. / *( L-R) 4. + – (L –R) ALGORITHM: • Initialize result as a blank string, Iterate through given expression, one character at a time 1. If the character is an operand, add it to the result. 2. If the character is an operator. 1. If the operator stack is empty, then push it to the operator stack. 2. Else If the operator stack is not empty, 1. If the operator’s precedence is greater than or equal to the precedence of the stack top of the operator stack, then push the character to the operator stack. 2. If the operator’s precedence is less than the precedence of the stack top of operator stack then “pop out an operator from the stack and add it to the result until the stack is empty or operator’s precedence is greater than or equal to the precedence of the stack top of operator stack“. then push the operator to stack. 3. If the character is “(“, then push it onto the operator stack. 4. If the character is “)”, then “pop out an operator from the stack and add it to the result until the corresponding “(“ is encountered in operator stack. Now just pop out the “(“. EXERCISE 1: Develop and execute a Java program to convert a valid infix expression to postfix expression using stack. Assume that the infix expression is read as a single line consisting of non-negative single digit operands and binary arithmetic operators. The operators are +(add), -(subtract), *(multiply), /(divide) and %(Remainder). Infix to Postfix /* Java implementation to convert infix expression to postfix*/ // Note that here we use Stack class for Stack operations import java.util.Stack; class Test { // A utility function to return precedence of a given operator // Higher returned value means higher precedence static int Prec(char ch) { switch (ch) { case '+': case '-': return 1; case '*': case '/': return 2; case '^': return 3; }return -1; } static String infixToPostFix(String expression){ String result = ""; Stack<Character> stack = new Stack<>(); for (int i = 0; i <expression.length() ; i++) { char c = expression.charAt(i);//method returns a char value at the given index number //check if char is operator if(precedence(c)>0){ // if stack not empty we check precedence of operator at the top of the stack is greater than or equal to the precedence of the operator outside the stack //then pop operator from the stack to result then push the lower precedence in line 34 while(!stack.isEmpty() && precedence(stack.peek()) >=precedence(c)){ result += stack.pop(); } stack.push(c); }else if(c=='('){// if you reach open ( then push it in the stack stack.push(c);} else if(c==')'){ // close ) then pop all operator until reach open ( char x = stack.pop(); while(x!='('){// if i do not reach open brackets pop and add it into expression , if reach ( discarding it result += x; x = stack.pop(); } }else{ //character is neither operator nor ( result += c; } } for (int i = 0; i <=stack.size() ; i++) {//check the size of the stack if not empty then pop all the stack to the result result += stack.pop(); } return result; } public static void main(String[] args) { String exp = "A+B*(C % D-E)"; System.out.println("Infix Expression: " + exp); System.out.println("Postfix Expression: " + infixToPostFix(exp)); } } EXERCISE 2 Develop and execute a Java program to evaluate a valid postfix expression using stack. Assume that the postfix expression is read as a single line consisting of non-negative single digit operands and binary arithmetic operators. The operators are +(add), -(subtract), *(multiply), /(divide) and %(Remainder). EVALUATION POSTFIX STEPS Use operand stack . Read all the characters one by one from the Postfix expression Step-1 : If the reading character is OPERAND then push into the stack Step-2: If the reading character is OPERATOR then POP the two elements and apply the operator and push the result back to the Stack. Step-3: After Completion of reading all the characters from Postfix expression the result will be available in the stack. EX • 562*+ // Java proram to evaluate value of a postfix // expression having multiple digit operands import java.util.Stack; class Test1 { // Method to evaluate value of a postfix expression static int evaluatePostfix(String exp) { //create a stack Stack<Integer> stack = new Stack<>(); // Scan all characters one by one for(int i = 0; i < exp.length(); i++) { char c = exp.charAt(i); // Scanning each character from left. // If character is a delimitter, move on. if(c == ' ') continue; // If the scanned character is an operand // (number here),extract the number // Push it to the stack. else if(Character.isDigit(c)) { int n = 0; //extract the characters and store it in num // use it when you get a string from your stack. while(Character.isDigit(c)) { n = n*10 + (int)(c-'0’); //operand = (operand*10) + (expression[i] - '0'); i++; c = exp.charAt(i); } // Finally, you will come out of while loop with i set to a non-numeric character or end of string // decrement i because it will be incremented in increment section of loop once again. // We do not want to skip the non-numeric character by incrementing i twice. i--; //push the number in stack stack.push(n); } // If the scanned character is an operator, pop two // elements from stack apply the operator else { int val1 = stack.pop(); int val2 = stack.pop(); switch(c) { case '+': stack.push(val2+val1); break; case '-': stack.push(val2- val1); break; case '/': stack.push(val2/val1); break; } } } } case '*': stack.push(val2*val1); break; } return stack.pop(); // Driver program to test above functions public static void main(String[] args) { String exp = "100 200 + 2 / 5 * 7 +"; System.out.println(evaluatePostfix(exp)); } // This code is contributed by Arnab Kundu EXERCISE 2 Develop and execute a Java program to convert a valid infix expression to pre fix expression using stack. Assume that the infix expression is read as a single line consisting of non-negative single digit operands and binary arithmetic operators. The operators are +(add), -(subtract), *(multiply), /(divide) and %(Remainder). https://blog.usejournal.com/infix-to-prefix-conversion-fb73ddcafc6e STEPS TO CONVERT INFIX EXPRESSION TO PREFIX 1. First, reverse the given infix expression. 2. Scan the characters one by one. 3. If the character is an operand, copy it to the prefix notation output. 4. If the character is a closing parenthesis, then push it to the stack. 5. If the character is an opening parenthesis, pop the elements in the stack until we find the corresponding closing parenthesis. 6. If the character scanned is an operator • If the operator has precedence greater than or equal to the top of the stack, push the operator to the stack. • If the operator has precedence lesser than the top of the stack, pop the operator and output it to the prefix notation output and then check the above condition again with the new top of the stack. 7. After all the characters are scanned, reverse the prefix notation output. HOMWORK Develop and execute a Java program to evaluate a valid prefix expression using stack. Assume that the prefix expression is read as a single line consisting of non-negative single digit operands and binary arithmetic operators. The operators are +(add), -(subtract), *(multiply), /(divide) and %(Remainder).