views:

144

answers:

4
+1  Q: 

Calculator stack

My understanding of calculators is that they are stack-based. When you use most calculators, if you type 1 + 2 [enter] [enter] you get 5. 1 is pushed on the stack, + is the operator, then 2 is pushed on the stack. The 1st [enter] should pop 1 and 2 off the stack, add them to get 3 then push 3 back on the stack. The 2nd [enter] shouldn't have access to the 2 because it effectively doesn't exist anywhere.

How is the 2 retained so that the 2nd [enter] can use it?

Is 2 pushed back onto the stack before the 3 or is it retained somewhere else for later use? If it is pushed back on the stack, can you conceivably cause a stack overflow by repeatedly doing [operator] [number] [enter] [enter]?

+2  A: 

All you would need to do is retain the last operator and operand, and just apply them if the stack is empty.

Ignacio Vazquez-Abrams
Technically, the stack won't be empty. It will contain the final calculated number.
Dinah
Fair enough. If the stack does not contain a usable operator then.
Ignacio Vazquez-Abrams
+3  A: 

The only true stack based calculators are calculators which have Reverse Polish Notation as the input method, as that notation directly operates on stacks.

Yann Ramin
Infix expressions can easily be converted to postfix expressions, which can then use a stack.
Ignacio Vazquez-Abrams
Right. It's worth emphasizing that ordinary hand calculators simply are not stack-based. As Matt points out, they may have as few as two registers. They don't do operator precedence or parentheses (features which would require a stack).
Jason Orendorff
A: 

There is an excellent description and tutorial of the Shunting-yard algorithm (infix -> rpn conversion) on wikipedia.

ergosys
For reference: http://en.wikipedia.org/wiki/Shunting-yard_algorithm
Dinah
+4  A: 

Conceptually, in hardware these values are put into registers. In simple ALU (Arithmatic Logical Units (i.e. simply CPUs)), one of the registers would be considered an accumulator. The values you're discussing could be put on a stack to process, but once the stack is empty, the register value (including the last operation) may be cached in these registers. To which, when told to perform the operation again, uses the accumulator as well as the last argument.

For example,

                    Reg1     Reg2 (Accumulator)  Operator
Input 1                         1
Input +                         1                  +
Input 2               2         1                  +
Enter                 2         3                  +
Enter                 2         5                  +
Enter                 2         7                  +

So it may be a function of the hardware being used.

Matt