0% found this document useful (0 votes)
26 views

Evaluate_Arithmetic Expression

Uploaded by

grojamani
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

Evaluate_Arithmetic Expression

Uploaded by

grojamani
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Arithmetic Expression Evalution

Algorithm for Arithmetic Expression Evaluation


1. Initialize a string consisting of expression and two stacks for storing values
and operators.
2. Iterate from 0 to size of string – 1. Check if the character at the current index
is equal to space, start the next iteration. If the character at the current index is
equal to ‘(‘ insert it in operators stack.
3. If the character at the current index is a digit. Check if there is a number
following next to the digit, pick the whole number else if it is a single-digit
pick the digit. Insert the digit/number in the value stack.
4. Else if the character at the current index is ‘)’, iterate while the size of the
operator’s stack is not zero and character at the current index is not equal to
‘(‘.
5. After that, remove the 2 elements from the top of the value’s stack and 1
element from the operator stack.
6. Apply the arithmetic operation on the two popped digits/numbers. Insert the
answer in a values stack.
7. Similarly, while the size of the operator’s stack is not zero, remove the 2
elements at the top of the value’s stack and an operator from operator stack.
8. Apply the arithmetic operation on the two popped digits/numbers. Insert the
answer in a values stack.
9. Return the element at the top of the value stack.

stack organization is very effective in evaluating arithmetic expressions. Expressions are


usually represented in what is known as Infix notation,
1. Polish notation (prefix notation) –
It refers to the notation in which the operator is placed before its two operands . Here
no parentheses are required, i.e.,
+AB
2. Reverse Polish notation(postfix notation) –
It refers to the analogous notation in which the operator is placed after its two
operands. Again, no parentheses is required in Reverse Polish notation, i.e.,
AB+
The conversion from infix notation to post-fix notation must take into consideration the
operational hierarchy.
There are 3 levels of precedence for 5 binary operators as given below:

Highest: Exponentiation (^)


Next highest: Multiplication (*) and division (/)
Lowest: Addition (+) and Subtraction (-)
For example –
Infix notation: (A-B)*[C/(D+E)+F]
Post-fix notation: AB- CDE +/F +*
Here, we first perform the arithmetic inside the parentheses (A-B) and (D+E). The division of
C/(D+E) must done prior to the addition with F. After that multiply the two terms inside the
parentheses and bracket.
Now we need to calculate the value of these arithmetic operations by using stack.
The procedure for getting the result is:
1. Convert the expression in Reverse Polish notation( post-fix notation).
2. Push the operands into the stack in the order they are appear.
3. When any operator encounter then pop two topmost operands for executing the
operation.
4. After execution push the result obtained into the stack.
5. After the complete execution of expression the final result remains on the top of the
stack.

Example: (postfix notation)0


class EvalReversePolishNotation {

public static int evalRPN(String s) {

// stack to store operands


java.util.Stack stack = new java.util.Stack<Integer>();
String tokens[] = s.split(" ");
int expLength = tokens.length;

// parse the entire expression


for (int i = 0; i < expLength; i++) {
int result, element1, element2;
switch (tokens[i]) {
case "+":
element1 = (Integer) stack.pop();
element2 = (Integer) stack.pop();
result = element2 + element1;
stack.push(result);
break;
case "-":
element1 = (Integer) stack.pop();
element2 = (Integer) stack.pop();
result = element2 - element1;
stack.push(result);
break;
case "*":
element1 = (Integer) stack.pop();
element2 = (Integer) stack.pop();
result = element2 * element1;
stack.push(result);
break;
case "/":
element1 = (Integer) stack.pop();
element2 = (Integer) stack.pop();
result = element2 / element1;
stack.push(result);
break;
default:
result = Integer.parseInt(tokens[i]);
stack.push(result);

}
}
return (Integer) stack.pop();
}

public static void main(String[] args) {


int result = evalRPN("4 13 5 / +");
System.out.println("Result of evaluation = " + result);
int result1 = evalRPN("10 6 9 3 + -11 * / * 17 + 5 +");
System.out.println("Result of evaluation = " + result1);
}
}

Output of above code :

Result of evaluation = 6
Result of evaluation = 22
EXAMPLE: (prefix notation) –
import java.util.Stack;
public class PrefixEvaluationSingleDigitOperand {
public static Double evaluate(double a, double b, char operator){
switch (operator) {
case '+':
return a + b;
case '-':
return b - a;
case '*':
return a * b;
case '/':
if (a == 0)
throw new
UnsupportedOperationException("Cannot divide by zero");
return b / a;
}
return 0.0;
}
public static Double convert(String expression) {

Stack<Double> stack = new Stack<>();

StringBuilder input = new StringBuilder(expression);


input.reverse();

for (int i = 0; i < input.length(); i++) {


char c = input.charAt(i);

if (c == '*' || c == '/' || c == '^' || c == '+' || c == '-') {


double s1 = stack.pop();
double s2 = stack.pop();
double temp = evaluate(s2, s1, c);
stack.push(temp);
} else {
stack.push((double) (c-'0'));
}
}

double result = stack.pop();


return result;
}

public static void main(String[] args) {


String exp = "-/*2*5+3652";
System.out.println("Prefix Expression: " + exp);
System.out.println("Evaluation: " + convert(exp));
}
}

Output:
Prefix Expression: -/*2*5+3652
Evaluation: 16.0

EXAMPLE : INFIX TO PREFIX


import java.util.Stack;
public class InfixToPreFix {
static int precedence(char c){
switch (c){
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
}
return -1;
}

static StringBuilder infixToPreFix(String expression){

StringBuilder result = new StringBuilder();


StringBuilder input = new StringBuilder(expression);
input.reverse();
Stack<Character> stack = new Stack<Character>();

char [] charsExp = new String(input).toCharArray();


for (int i = 0; i < charsExp.length; i++) {

if (charsExp[i] == '(') {
charsExp[i] = ')';
i++;
}
else if (charsExp[i] == ')') {
charsExp[i] = '(';
i++;
}
}
for (int i = 0; i <charsExp.length ; i++) {
char c = charsExp[i];

//check if char is operator or operand


if(precedence(c)>0){
while(stack.isEmpty()==false && precedence(stack.peek())>=precedence(c)){
result.append(stack.pop());
}
stack.push(c);
}else if(c==')'){
char x = stack.pop();
while(x!='('){
result.append(x);
x = stack.pop();
}
}else if(c=='('){
stack.push(c);
}else{
//character is neither operator nor "("
result.append(c);
}
}

for (int i = 0; i <=stack.size() ; i++) {


result.append(stack.pop());
}
return result.reverse();
}

public static void main(String[] args) {


String exp = "A+B*(C^D-E)";
System.out.println("Infix Expression: " + exp);
System.out.println("Prefix Expression: " + infixToPreFix(exp));
}
}

OUTPUT: Infix Expression: A+B*(C^D-E)


Prefix Expression: +A*B-^CDE

You might also like