AIOC Banner

Problem: RPN Calc

Want to try solving this problem? You can submit your code online if you log in or register.


RPN Calculator

Input File: rpnin.txt
Output File: rpnout.txt

Implement a stack and show it off by writing a programme which reads input from rpnin.txt. After each line of input, print out the contents of the stack, and execute the command given in the table below. If the stack is empty after a pop, print 'stack is empty!'.

+Pop the top two numbers n1 and n2 off the stack and push (n1 + n2) on
-Pop the top two numbers n1 and n2 off the stack and push (n2n1) on
*Pop the top two numbers n1 and n2 off the stack and push (n1 × n2) on
/Pop the top two numbers n1 and n2 off the stack and push (n2 / n1) on
swapExchange the top two numbers on the stack
dupDuplicate the top of the stack
pPop the top number off the stack
qTerminate the program, do not print the stack for this line.
otherwiseIf the input is not a command from above, it is an integer to put on the stack.

You may assume that your stack does not grow beyond 1000 levels deep.

Sample input:

1
2
+
4
*
2
/
10
swap
-
dup
p
5
-
p
q

Sample output:

1
1 2
3
3 4
12
12 2
6
6 10
10 6
4
4 4
4
4 5
-1
stack is empty!

 


Privacy statement
© Australian Mathematics Trust 2001-2024

Contact: training@orac.amt.edu.au
Page generated: 29 March 2024, 10:34pm AEDT