Postfix Calculator
Concept
Postfix notation is a method of arranging an expression with the operator after the two operands. For example, the expression ‘3+5′, which is called infix notation, would be written as ‘35+’ in postfix notation.
Application
Using stacks, this evaluation is particularly easy. Once the string is entered, it is first checked for errors (such as too many, too few, or misplaced operators), then pushed into a stack character by character until an operator is encountered. At that point the two operands and operator are evaluated, and the returned result is put back into the stack as a character.
My biggest challenge was dealing with the conversion from string/character format into integer and retaining the proper value. The solution to this turned out to be that I merely needed to set the integer to the character value, subtract 48 (the ASCII value of a numerical character) from the integer, and then pass it to the function to evaluate it.
Stripping
void strip(string &s) { for(int i =0; i < s.length(); i++) { if(!isOperand(s[i]) && !isOperator(s[i]) ) { s.erase(i,1); } } }
Error Checking
int errorChecking(string s) { int operand =0; int operate = 0; for(int i = 0; i < s.length(); i++) { if( isOperand(s[i]) ) operand++; else if( isOperator(s[i]) ) operate++; /* check if there are ever as many operators * as operands at ANY point in the equation * if so, give error */ if(operand <= operate) break; } if(operand == operate+1) return 1; else return 0; }
Testing Operator/Operand
int isOperator(char s) { if( s==‘*’ || s==‘-’ || s==‘+’ ) { return 1; } else { return 0; } } int isOperand(char s) { if(s==‘0′ || s==‘1′ || s==‘2′|| s==‘3′ ||s==‘4′ || s==‘5′ || s==‘6′ || s==‘7′ || s==‘8′ || s==‘9′ ) { return 1; } else { return 0; } }
Evaluation
int performOperation(int a, int b, char operand) { if(operand == ‘+’) { return (a + b); } else if( operand == ‘-’) { return (a - b); } else if ( operand == ‘*’) { return (a * b); } else { return 0; } }
Screenshots

Improvements
- allowing multi-digit numbers
- retaining letter variables instead of stripping them from the equation
- graphic-based version
No comments yet. Be the first.
Leave a reply