Bodmas program in Java

BODMAS is an acronym that represents the order of operations in mathematics. It is a set of rules used to determine the sequence in which mathematical operations should be performed in an expression. BODMAS stands for:

  • B: Brackets (Parentheses) first
  • O: Orders (Exponents and Roots, such as square roots or cube roots)
  • DM: Division and Multiplication (from left to right)
  • AS: Addition and Subtraction (from left to right)

Following the BODMAS rule ensures that mathematical expressions are evaluated correctly and consistently. It helps to eliminate ambiguity in expressions and ensures that the operations are performed in a predictable order.

For example, consider the expression 2 + 3 * 4 - (8 / 2). Applying the BODMAS rule, we perform the operations in the following order:

  1. First, we evaluate the expression within the parentheses: (8 / 2) = 4.
  2. Next, we perform the multiplication: 3 * 4 = 12.
  3. Then, we perform the addition: 2 + 12 = 14.
  4. Finally, we perform the subtraction: 14 - 4 = 10.

By following the BODMAS rule, we obtain the correct result of 10 for the given expression.

The BODMAS rule is a standard convention used in mathematics to ensure consistent and unambiguous evaluation of mathematical expressions.

Bodmas program in Java

import java.util.Stack;

public class BODMASEvaluator {

    public static double evaluateExpression(String expression) {
        Stack<Double> numbers = new Stack<>();
        Stack<Character> operators = new Stack<>();

        for (int i = 0; i < expression.length(); i++) {
            char ch = expression.charAt(i);

            if (Character.isDigit(ch)) {
                StringBuilder num = new StringBuilder();
                while (i < expression.length() && (Character.isDigit(expression.charAt(i)) || expression.charAt(i) == '.')) {
                    num.append(expression.charAt(i));
                    i++;
                }
                i--;
                numbers.push(Double.parseDouble(num.toString()));
            } else if (ch == '(') {
                operators.push(ch);
            } else if (ch == ')') {
                while (!operators.isEmpty() && operators.peek() != '(') {
                    performOperation(numbers, operators);
                }
                if (!operators.isEmpty()) {
                    operators.pop();
                }
            } else if (isOperator(ch)) {
                while (!operators.isEmpty() && precedence(operators.peek()) >= precedence(ch)) {
                    performOperation(numbers, operators);
                }
                operators.push(ch);
            }
        }

        while (!operators.isEmpty()) {
            performOperation(numbers, operators);
        }

        return numbers.pop();
    }

    private static boolean isOperator(char ch) {
        return ch == '+' || ch == '-' || ch == '*' || ch == '/';
    }

    private static int precedence(char operator) {
        if (operator == '*' || operator == '/') {
            return 2;
        } else if (operator == '+' || operator == '-') {
            return 1;
        } else {
            return 0;
        }
    }

    private static void performOperation(Stack<Double> numbers, Stack<Character> operators) {
        double num2 = numbers.pop();
        double num1 = numbers.pop();
        char operator = operators.pop();
        double result = 0;

        switch (operator) {
            case '+':
                result = num1 + num2;
                break;
            case '-':
                result = num1 - num2;
                break;
            case '*':
                result = num1 * num2;
                break;
            case '/':
                result = num1 / num2;
                break;
        }

        numbers.push(result);
    }

    public static void main(String[] args) {
        String expression = "2*1+1-4/2+1";
        double result = evaluateExpression(expression);
        System.out.println("Result: " + result);
    }
}

Out of the above program will be:- 2

Explanation

  1. The evaluateExpression method takes the input expression as a parameter and returns the evaluated result.
  2. The method initializes two stacks: numbers to store the numbers encountered in the expression, and operators to store the operators.
  3. The code iterates through each character in the expression using a for loop.
  4. If the character is a digit, it means we have encountered a number. We extract the entire number by continuously appending consecutive digits or decimal points. The loop ensures that we capture the complete numeric value. Once we have the number, we convert it to a double and push it onto the numbers stack.
  5. If the character is an operator (+, -, *, /), we compare its precedence with the operator at the top of the operators stack. If the top operator has higher or equal precedence, we perform the operation and push the result onto the numbers stack. We repeat this process until we can push the current operator onto the operators stack.
  6. After processing all characters in the expression, there might be some remaining operations left in the operators stack. We perform those operations one by one until the operators stack is empty.
  7. Finally, we retrieve the final result from the numbers stack, which will be the evaluated result of the expression.
  8. The isOperator method checks if a character is an operator (+, -, *, /).
  9. The precedence method assigns a precedence value to each operator. Operators with higher precedence will be evaluated first.
  10. The performOperation method takes the top two numbers from the numbers stack, the top operator from the operators stack, performs the corresponding operation, and pushes the result back onto the numbers stack.
  11. In the main method, we initialize the input expression (2*1+1-4/2+1 in this case), call the evaluateExpression method, and print the result.

By following the BODMAS rule (operator precedence) and using stacks to handle numbers and operators, the code evaluates the expression and produces the correct result.

That’s all about Bodmas program in Java.

  1. Write a program for Factorial in java?
  2. Write a program for Armstrong Numbers in java?