Atholton - AP Central

Download Report

Transcript Atholton - AP Central

Atholton High School
Columbia, Maryland
Nifty Assignments: Mighty
Cabbage Patch Micro
Infix Expressions
Operands
A+B*C
Operators
Postfix Expressions
ABC*+
Prefix Expressions
+A*BC
Converting
Infix Expressions
Postfix String
Assembly Language Code
Step 1
Creating a postfix string using
a stack
Let’s try a simple
one:
A+B*C
Rule
Every operator gets pushed onto the operator stack
but not until all operators with equal or greater
precedence have been popped. Operands are
appended to the postfix string immediately.
Infix String Operator Stack
A
+
B
*
C
+
+
+*
+*
Postfix String
A
A
AB
AB
A BC*+
Let’s try a more difficult
one:
A–B/C$D*E
Infix String Operator Stack
A
–
B
/
C
$
D
*
E
–
–
–
–
–
–
–
–
/
/
/$
/$
*
*
Postfix String
A
A
AB
AB
A BC
A BC
A BCD
A BCD $ /
A B C D $ / E* –
One for you to try: V + W * X $ Y – Z
What about parentheses?
(A + B) * (C – D) $ E * F
Infix String Operator Stack
(
A
+
B
)
*
(
C
–
D
)
$
E
*
F
(
(
(+
(+
*
*(
*(
*(–
*(–
*
*$
*$
*
*
Postfix String
A
A
AB
AB+
AB+
AB+
AB+C
AB+C
AB+C D
AB+C D –
AB+C D –
AB+C D – E
AB+C D – E $ *
A B + C D – E $ *F *
Step 2
Creating assembly language
code using a stack
Concept and Terminology
Accumulator: Where arithmetic
takes place
LDA A: Load the accumulator
with number stored in location A
ADD B: Add to the accumulator
the number stored in location B
STA T : Store value from
accumulator in T
0
0
Rule
When you meet an operator, pop two elements from
the stack. The first element becomes the right
operand; the other becomes the left.
Postfix String Operand Stack ALC
A
B
C
*
+
A
AB
ABC
A T0
T1
LDA B
MUL C
STA T0
LDA A
ADD T0
STA T1
Postfix String Operand Stack
A
B
+
C
D
–
E
$
*
F
*
A
AB
T0
T0 C
T0 C D
T0 T1
T0 T1 E
T0 T2
T3
T3 F
T4
One for you to try:
AB+CDE–/F+*G–
ALC
LDA A
ADD B
STA T0
LDA C
SUB D
STA T1
LDA T1
EXP E
STA T2
LDA T0
MUL T2
STA T3
LDA T3
MUL F
STA T4
Pseudocode
Infix Expression
Postfix String
Infix [i]
'('
'A'…'Z'
')'
'+', '-', '*', '/'
Action
Push onto operator stack
postfix string += infix [i]
operator.pop (temp)
while (temp != '('){
postfix string += temp
operator.pop (temp)}
while (!done && !operator.isEmpty ())
if (precedence (operator.top (), infix [i])
postfix string += operator.pop (temp)
else
done = true
Pseudocode
Postfix Expression
ALC
Postfix [i]
'A'...'Z'
'+', '-', '*', '/'
Action
Push onto operand stack
operand.pop (rtopnd)
operand.pop (ltopnd)
Write ALC
Push temp onto operand stack
Increase value of temp position