The Student Room Group

Scary programming question

eek ;/

Write a program that recursively parses expressions, input as strings, from the following recursively defined language and calculates and prints out the answer to the calculations.

<EXP> = + <DIGIT> <EXP> | - <DIGIT> <EXP> | &<EXP> | <DIGIT>
<DIGIT> = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
Here EXP stands for expressions, + means do addition, - means subtract and & means calculate the sum up
to the given number. Legal expressions in this language involve putting the operator before its arguments (this is called Polish notation). Instead of writing 1+2, in this language you write +12. Notice only single digits are allowed and spaces are not allowed. Further legal expressions can be seen below.

An example run of the program (characters in bold are typed in by the user and pop-up boxes may be used
for input and output):
Please input the expression 3
The answer is 3
Another example run:
Please input the expression &3
The answer is 6
Another example run:
Please input the expression &+23
The answer is 15
Another example run:
Please input the expression &+1-82
The answer is 28
Another example run:
Please input the expression *2+3+45
The answer is 24
Make sure you split the program in to multiple methods, and use a series of recursive methods following the
structure of the recursive definition about expressions. You must not use an explicit loop at all in your
program. Comment your program with useful comments that give useful information, with every method
commented with what it does, use indentation consistently and ensure that your variable names convey
useful information. Your variables should be positioned so that their scope is small.
what have you tried?
Reply 2
Original post by MalcolmX
what have you tried?

Tried to understand polish notation a little better, an example of factorials using recursion methods (not sure how relevant), and a simple idea of recursion where counting up to a number is the aim. I get why a loop isn't to be used because the recursive methods are meant to take on that job but all the expression stuff really puts me off the question.

I see you're a fan of Malcolm X, you don't get many like Malc
Reply 3
bump

Quick Reply

Latest

Trending

Trending