Question
Write a program, using stacks, to evaluate arithmetic expressions. Specifications The mathematic expression is fully parenthesized. For example ((1+2)*(3+4)) Use 2 stacks: One stack holds
Write a program, using stacks, to evaluate arithmetic expressions.
Specifications The mathematic expression is fully parenthesized. For example ((1+2)*(3+4))
Use 2 stacks: One stack holds numbers, the other stack holds operators Processing expressions: Numbers push it onto the number stack
Operators (+, -, *, /) push it onto the operator stack '(' is ignored ')' triggers the calculation:
Get an operator from operator stack Get 2 operands from number stack Note:
The first number popped off the stack is operand #2 The 2nd number popped off the stack is operand #1 Push the result onto the number stack
//
Pseducode
for evaluate arithmetic expressions:
while
(input is ok) and (next character is not '
')
if the next character is a digit (0
9)
read the number
push it on to the numStack
otherwise if it is an operator +, -
, * , or /
read the character
push it on to the operStack
otherwise if it is a right parenthesis
ignore this character
do one calculation (get 2 operands from numStack and the operation from operStack)
( remember to push the result on to the numStack)
otherwise if the character is a left parenthesis
ignore this character
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started