c - Understanding Reverse Polish Notation, for homework assignment? -


i have been asked write simple reverse polish notation calculator in c part of homework assignment. i'm having difficulty understanding rpn. can please me understand reverse polish notation? also, tips on how approach problem appreciated.

reverse polish notation specific way of writing expressions first write values, operation want perform. instance, add numbers 3 , 4 you'd write 3 4 +.

so write rpn calculator you'll need

  • a means of accepting input, such console
  • a means of tokenizing input (for you're doing, breaking on whitespace sufficient)
  • a stack storing values (operands) (such 3 , 4 in above)
  • a dictionary of operations

then loop becomes, in essence:

while (there's token available) {     token = get_the_token     if (token known operator) {         number of values stack operation requires (usually two); fail if stack doesn't have enough         perform operation on values         push result on stack     }     else if (token valid value) {         push on stack     }     else {         show error: invalid input     } } show result remaining on stack 

you can see why rpn makes writing calcuator easy: don't have worry having operators between values operate on, , don't need parentheses grouping more common infix form of notation. instance, we'd write (10 + (4 * 2)) / 9 in infix notation, we'd write 10 4 2 * + 9 / in rpn. calculator process tokens this:

  • 10: it's value, push on stack
  • 4: it's value, push on stack
  • 2: it's value, push on stack
  • *: it's operator, pop 2 , 4 off stack , multiply them (4 * 2); push result (8) on stack
  • +: it's operator, pop 8 , 10 off stack , add them (10 + 8); push result (18) on stack
  • 9: it's value, push on stack
  • /: it's operator, pop 9 , 18 off stack , divide them (18 / 9); push result (2) on stack (note value @ top of stack — 9, in case — divisor, next value under it — 18 — dividend)
  • end of input, show value(s) on stack: 2

Comments

Popular posts from this blog

javascript - Enclosure Memory Copies -

php - Replacing tags in braces, even nested tags, with regex -