EVALUATION OF POSTFIX & PREFIX EXPRESSIONS

Lets see the logic to evaluate both postfix & prefix expressions.

Logic for evaluating Postfix

Do refer the code available the end of this section to understand the following thoery.

  1. Create stack for operands using arrays of float type.
  2. Scan the postfix expression from left to right.
  3. If the character read is an operand then convert it into it's corresponding numeric value and push it to the stack.
  4. Else perform the following operation:
    1. Pop the top of stack and save it as operand2.
    2. Once again pop the top of stack and save it as operand1.
    3. Compute the relevant operation between operand1, operator(character read) & operand2.
    4. Push this result to the stack.
  5. After scanning all the characters of the postfix expression, pop the top of stack and save is as result.
  6. If the stack is not empty then the given postfix expression is invalid. Else print the result.

Logic for evaluating Prefix

Do refer the code available the end of this section to understand the following theory.

  1. Create stack for operands using arrays of float type.
  2. Scan the prefix expression from right to left.
  3. If the character read is an operand then convert it into it's corresponding numeric value and push it to the stack.
  4. Else perform the following operation:
    1. Pop the top of stack and save it as operand1.
    2. Once again pop the top of stack and save it as operand2.
    3. Compute the relevant operation between operand1, operator(character read) & operand2.
    4. Push this result to the stack.
  5. After scanning all the characters of the prefix expression, pop the top of stack and save is as result.
  6. If the stack is not empty then the given prefix expression is invalid. Else print the result.

Code file

Please open this in your pc or with a compatible app in your mobile.

C++ Implementation for EVALUATION OF POSTFIX & PREFIX EXPRESSIONS

That's it from this blog post. If you liked it then do share this blog with your friends or people who wanna get into programming world. Thank You!

Copyright © NStF Blogs 2021