Skip to content

Latest commit

 

History

History
48 lines (39 loc) · 3.45 KB

README.md

File metadata and controls

48 lines (39 loc) · 3.45 KB

Postfix Calc

This calculates the value of the input postfix notation expression

Program Map

Use this to follow the explanation below

Explanation

Note: Unfortunately Github markdown does not support HTML text coloring...

Input Reading / Initial Logic (Blue)

  1. Push 0 onto stack
  2. The start of the programs main while loop
    • First reads in a character (from now on reffered to as token), if no input left break out of loop and go to blue 2a, else go to blue 3
    • 2a - Pop the initial 0 from the stack and then output the calculated result of the input equation, go to program end (blue 2b)
  3. Push 48 (0) to stack to check if token is a digit or operator
  4. If token is a digit subtract 48 from digit char value (i.e. 49 (1) - 48 = 1) and go to red 1
    • This is done because we need to read all input as a char so we can process operators, but in order to do math, we need digit's as their integer value.
  5. Else token is an operator, so go to orange 1

Operand Logic (Red)

  1. Roll stack to place char value of input on top, then pop it off stack (discard)
  2. Roll stack again to place integer value of input under the initial 0 (operand stack)
    • 2a - Change pointer to loop back to blue 2

Intermission (Orange)

  1. Pop leftover meaningless value that resulted from earlier checks
  2. Push 3 onto the stack twice
    • These are used to guide the program through orange 2a and b to purple 1

Operator Check (Purple)

  1. Push 42 ('*') onto the stack, if operator is *, pop operator from stack, and go to green 1
  2. Push 43 ('+') onto the stack, if operator char value is > 43, continue to purple 3
    • Else, operator is + so pop operator from stack, and go to green 2
  3. Push 45 ('-') onto the stack, if operator is -, pop operator from stack, and go to green 3
    • 3a - Operator is none of the above, thus it's '/', so pop operator from stack and go to green 4

Math (Green)

  1. Roll stack to got the top two operands from the operator stack (which we maintained by keeping under the initial pushed 0), then perform (op1 * op2) and continue to green 5
  2. Roll stack to got the top two operands from the operator stack, then perform (op1 + op2) and continue to green 5
  3. Roll stack to got the top two operands from the operator stack, then perform (op1 - op2) and continue to green 5
  4. Roll stack to got the top two operands from the operator stack, then perform (op1 / op2) and continue to green 5
  5. Roll stack to place the result of the previous operation onto the top of the operand stack (right under the 0), and continue back to blue 2

Limitations

Does not handle multi-digit numbers, negative numbers, or exponents in input.