Parenthesis and internal arithmetic equation with operation

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • muhammadlodhi
    New Member
    • Apr 2010
    • 7

    #1

    Parenthesis and internal arithmetic equation with operation

    I have an equation like ((3+4)-(24/5)), and if the user presses ., then the equation has ended, and it checks that the parentheses are balanced and solves all the internal operations; what should I do? How do I make this program? Please help, thank you. I am required to use arrays to make sure the parentheses are balanced."
  • jkmyoung
    Recognized Expert Top Contributor
    • Mar 2006
    • 2057

    #2
    There are many ways to go about implementing this program. You also have to worry about order of operation.
    I suggest something that considers the following:
    - Tokenize: Each number, each operator, and each parenthesis counts as a token.
    - Do multiple passes, where each operation determines the highest precedence operation.
    - If you have a parentheses, it automatically makes it highest precedence.
    - With parentheses, you can recursively solve by solving the entire operation inside the parentheses first.
    Eg. Let's take a different example (5 + 4 * 3) + (3 * 2 / 1) * 3
    First pass. We immediately hit parentheses, so let's solve for that.

    subsolve 5 + 4 * 3.. * is highest priority.
    5 + 12 + is highest priority
    17. return

    17 + (3 * 2 / 1) * 3 . Parentheses again.

    Solve 3 * 2 / 1 * is highest priority
    6 /1 / is highest priority
    6. return

    17 + 6 * 3 * is highest priority
    17 + 18 + is highest priority
    35

    One possible structure that might lend itself to this problem is a linked list.

    Comment

    • donbock
      Recognized Expert Top Contributor
      • Mar 2008
      • 2427

      #3
      What are your requirements for an expression like (4+6/2)?
      • Evaluate according to arithmetic order of operations - the result is 7.
      • Evaluate from left to right - the result is 5.
      • This expression is illegal, the user is not allowed to input any expression where there are more than two terms within the parentheses.

      Comment

      • muhammadlodhi
        New Member
        • Apr 2010
        • 7

        #4
        the solution must be from left to right and paranthesis of c code must be balanced

        Comment

        • Dheeraj Joshi
          Recognized Expert Top Contributor
          • Jul 2009
          • 1129

          #5
          You can user stack to implement this.
          Whenever the item is number push them into stack, if the item is operator pop the element and perform the operation. Push the result back to stack.

          You also should consider "(" and ")".
          You need to modify the algorithm for infix and postfix expressions.

          This link may give you some idea

          Regards
          Dheeraj Joshi

          Comment

          Working...