You are on page 1of 141

LECTURE

Negative Numbers and


Subtraction
• The adders we designed can add only non-negative numbers
– If we can represent negative numbers, then subtraction is “just” the
ability to add two numbers (one of which may be negative).
• We’ll look at three different ways of representing signed numbers.
• How can we decide representation is better?
– The best one should result in the simplest and fastest operations.
– This is just like choosing a data structure in programming.
• We’re mostly concerned with two particular operations:
– Negating a signed number, or converting x into -x.
– Adding two signed numbers, or computing x + y.
– So, we will compare the representation on how fast (and how
easily) these operations can be done on them
Signed magnitude
representation
• Humans use a signed-magnitude system:
we add + or - in front of a magnitude to
indicate the sign.
• We could do this in binary as well, by
adding an extra sign bit to the front of
our numbers. By convention:
– A 0 sign bit represents a positive number.
– A 1 sign bit represents a negative number.
• Examples:
• 11012 = 1310 (a 4-bit unsigned number)
• 0 1101 = +1310 (a positive number in 5-bit signed magnitude)
• 1 1101 = -1310 (a negative number in 5-bit signed magnitude)

01002 = 410 (a 4-bit unsigned number)


0 0100 = +410 (a positive number in 5-bit signed magnitude)
1 0100 = -410 (a negative number in 5-bit signed magnitude)
Signed magnitude operations
• Negating a signed-magnitude number is trivial: just change the sign
bit from 0 to 1, or vice versa.
• Adding numbers is difficult, though. Signed magnitude is basically
what people use, so think about the grade-school approach to
addition. It’s based on comparing the signs of the augend and
addend:
– If they have the same sign, add the magnitudes and keep that sign.
– If they have different signs, then subtract the smaller magnitude
from the larger one. The sign of the number with the larger
magnitude is the sign of the result.
• This method of subtraction would lead to a rather complex circuit.

5 13 17
+3 7 9 6 4 7
+ -6 4 7 because - 3 7 9
-2 6 8 2 6 8
One’s complement
representation
• A different approach, one’s complement, negates
numbers by complementing each bit of the number.
• We keep the sign bits: 0 for positive numbers, and 1 for
negative. The sign bit is complemented along with the
rest of the bits.
• Examples:
11012 = 1310 (a 4-bit unsigned number)
0 1101 = +1310 (a positive number in 5-bit one’s complement)
1 0010 = -1310 (a negative number in 5-bit one’s complement)

01002 = 410 (a 4-bit unsigned number)


0 0100 = +410 (a positive number in 5-bit one’s complement)
1 1011 = -410 (a negative number in 5-bit one’s complement)
Why is it called “one’s
complement?”
• Complementing a single bit is equivalent to subtracting it
from 1.
 0’ = 1, and 1 - 0 = 1 1’ = 0,
and 1 - 1 = 0
• Similarly, complementing each bit of an n-bit number is
equivalent to subtracting that number from 2n-1.
• For example, we can negate the 5-bit number 01101.
– Here n=5, and 2n-1 = 3110 = 111112.
– Subtracting 01101 from 11111 yields 10010:

1 1 1 1 1
• - 01 1 01
1 00 1 0
One’s complement addition
• To add one’s complement numbers:
– First do unsigned addition on the numbers, including the
sign bits.
– Then take the carry out and add it to the sum.
• Two examples:
• 0011 (+3)
0111 (+7) + 0010 + (+2)

+ 1011 + (-4) 0 0101

1 0010
• 0101
0010 + 0

+ 1 0101 (+5)
This is
 simpler
0011and more uniform than signed
(+3)
magnitude addition.
Two’s complement
• Our final idea is two’s complement. To
negate a number, complement each bit
(just as for ones’ complement) and then
add 1.
• Examples:1101 = 13 (a 4-bit unsigned number)
2 10
0 1101 = +1310 (a positive number in 5-bit two’s complement)
1 0010 = -1310 (a negative number in 5-bit ones’ complement)
1 0011 = -1310 (a negative number in 5-bit two’s complement)

01002 = 410 (a 4-bit unsigned number)


0 0100 = +410 (a positive number in 5-bit two’s complement)
1 1011 = -410 (a negative number in 5-bit ones’ complement)
More about two’s complement
• Two other equivalent ways to negate two’s
complement numbers:
– You can subtract an n-bit two’s
complement number from 2n.
– 1 00000 1 00000
- 0 0 1 0 0 (+410 )
– - 0 1 1 0 1 (+1310 )
1 1 1 0 0 (-410 )
1 0 0 1 1 (-1310 )


– You can complement all of the bits to the left of the rightmost 1.

 01101 = +1310 (a positive number in two’s complement)


 10011 = -1310 (a negative number in two’s complement)
 00100 = +410 (a positive number in two’s complement)
 11100 = -410 (a negative number in two’s complement)

• Often, people talk about “taking the two’s complement” of a number.


This is a confusing phrase, but it usually means to negate some
number that’s already in two’s complement format.

Two’s complement addition
• Negating a two’s complement number takes a bit of work, but
addition is much easier than with the other two systems.
• To find A + B, you just have to:
– Do unsigned addition on A and B, including their sign bits.
– Ignore any carry out.
• For example, to find 0111 + 1100, or (+7) + (-4):
– First add 0111 + 1100 as unsigned numbers:

– 01 1 1
– + 1 1 00

1 001 1
– Discard the carry out (1).
– The answer is 0011 (+3).
Another two’s complement
example
• To further convince you that this works, let’s try adding
two negative numbers—1101 + 1110, or (-3) + (-2) in
decimal.
• Adding the numbers gives 11011:

• 1 1 01
• + 1110
1 1 01 1

• Dropping the carry out (1) leaves us with the answer,
1011 (-5).
Why does this work?
• For n-bit numbers, the negation of B in two’s complement is 2n - B
(this is one of the alternative ways of negating a two’s-
complement number).
 A - B = A + (-B)

= A + (2n - B)

= (A - B) + 2n
• If A  B, then (A - B) is a positive number, and 2n represents a carry
out of 1. Discarding this carry out is equivalent to subtracting 2n,
which leaves us with the desired result (A - B).
• If A  B, then (A - B) is a negative number and we have 2n - (A - B).
This corresponds to the desired result, -(A - B), in two’s
complement form.
Comparing the signed number systems
Decimal S.M. 1’s comp. 2’s comp.
• Here are all the 4-bit 7 0111 0111 0111
6 0110 0110 0110
numbers in the 5 0101 0101 0101
different systems. 4 0100 0100 0100
3 0011 0011 0011
• Positive numbers are the 2 0010 0010 0010
same in all three 1 0001 0001 0001
0 0000 0000 0000
representations. -0 1000 1111 —
• Signed magnitude and -1
-2
1001
1010
1110
1101
1111
1110
one’s complement -3 1011 1100 1101
have two ways of -4 1100 1011 1100
-5 1101 1010 1011
representing 0. This -6 1110 1001 1010
makes things more -7 1111 1000 1001
-8 — — 1000
complicated.
• Two’s complement has asymmetric
ranges; there is one more negative
number than positive number. Here, you
can represent -8 but not +8.
• However, two’s complement is preferred
because it has only one 0, and its
addition algorithm is the simplest.

Ranges of the signed number
systems
• How many negative and positive numbers
can be represented in each of the
different systems on the previous page?



• Signed One’s Two’s

• Smallest Unsigned
0000 (0)
Magnitude
1111 (-7)
complement complement
1000 (-7) 1000 (-8)
• Largest 1111 (15) 0111 (+7) 0111 (+7) 0111 (+7)
• In general, with n-bit numbers including
the sign, the ranges are:



Converting signed numbers to
decimal
• Convert 110101 to decimal, assuming this
is a number in:

 (a) signed magnitude format

 (b) ones’ complement

 (c) two’s complement



Example solution
• Convert 110101 to decimal, assuming this is a number in:
 Since the sign bit is 1, this is a negative number. The easiest way
to find the magnitude is to convert it to a positive number.
 (a) signed magnitude format
 Negating the original number, 110101, gives 010101, which is
+21 in decimal. So 110101 must represent -21.
 (b) ones’ complement
 Negating 110101 in ones’ complement yields 001010 = +1010 ,
so the original number must have been -1010 .

(c) two’s complement

 Negating 110101 in two’s complement


gives 001011 = 1110 , which means 110101 =
-1110 .
• The most important point here is that a binary
number has different meanings depending on
which representation is assumed.


Our four-bit unsigned adder
circuit
• Here is the four-bit unsigned additionNope, never saw
circuit from last Wednesday. it
before in my life.
Making a subtraction
circuit
• We could build a subtraction circuit directly, similar to the
way we made unsigned adders yesterday.
• However, by using two’s complement we can convert
any subtraction problem into an addition problem.
Algebraically,

A - B = A + (-B)

• So to subtract B from A, we can instead add the


negation of B to A.
• This way we can re-use the unsigned adder hardware
from last week.
A two’s complement subtraction
circuit
• To find A - B with an adder, we’ll need to:
– Complement each bit of B.
– Set the adder’s carry in to 1.
• The net result is A + B’ + 1, where B’ + 1 is
the two’s complement negation of B.





Small differences
• The only differences between the adder
and subtractor circuits are:
– The subtractor has to negate B3 B2 B1 B0.
– The subtractor sets the initial carry in to 1,
instead of 0.





An adder-subtractor circuit
• XOR gates let us selectively complement the B
input.
 X0=X X1=
X’
• When Sub = 0, the XOR gates output B3 B2 B1
B0 and the carry in is 0. The adder output will
be A + B + 0, or just A + B.
• When Sub = 1, the XOR gates output B3’ B2’
B1’ B0’ and the carry in is 1. Thus, the adder
output will be a two’s complement subtraction,
A - B.
Signed overflow
• With two’s complement and a 4-bit adder,
for example, the largest representable
decimal number is +7, and the smallest
is -8.
• What if you try to compute 4 + 5, or (-4) +
(-5)?
1 1 00 (-4)
01 00 (+4) + 1 01 1 (-5)
+ 01 01 (+5) 1 01 1 1 (+7)
01 001 (-7)
• We cannot just include the carry out to produce
a five-digit result, as for unsigned addition. If
we did, (-4) + (-5) would result in +23!
• Also, unlike the case with unsigned numbers,
the carry out cannot be used to detect
overflow.
– In the example on the left, the carry out is 0 but
there is overflow.
– Conversely, there are situations where the carry
out is 1 but there is no overflow.

Detecting signed overflow
• The easiest way to detect signed overflow
is to look at all the sign bits.



0 1 0 0 (+4) 1 1 0 0 (-4)
• + 01 01 (+5) + 1 01 1 (-5)
01 001 (-7) 1 01 1 1 (+7)
• Overflow occurs only in the two situations
above:
– If you add two positive numbers and get a
negative result.
– If you add two negative numbers and get a
positive result.
• Overflow cannot occur if you add a
positive number to a negative number.
Do you see why?

Sign extension
• In everyday life, decimal numbers are
assumed to have an infinite number of
0s in front of them. This helps in “lining
up” numbers.
• To subtract 231 and 3, for instance, you
can imagine:
 231
 - 003
 228
• You need to be careful in extending signed
binary numbers, because the leftmost bit is
the sign and not part of the magnitude.
• If you just add 0s in front, you might accidentally
change a negative number into a positive one!
• For example, going from 4-bit to 8-bit numbers:
– 0101 (+5) should become 0000 0101 (+5).
– But 1100 (-4) should become 1111 1100 (-4).
• The proper way to extend a signed binary
number is to replicate the sign bit, so the sign
is preserved.

Subtraction summary
• A good representation for negative numbers
makes subtraction hardware much easier to
design.
– Two’s complement is used most often (although
signed magnitude shows up sometimes, such as
in floating-point systems, which we’ll discuss on
Wednesday).
– Using two’s complement, we can build a
subtractor with minor changes to the adder from
last week.
– We can also make a single circuit which can both
add and subtract.
• Overflow is still a problem, but signed
overflow is very different from the
unsigned overflow we mentioned last
time.
• Sign extension is needed to properly
“lengthen” negative numbers.

• Tomorrow we’ll use most of the ideas
we’ve seen so far to build an ALU – an
important part of a processor.

Program Concept
• Hardwired systems are inflexible
• General purpose hardware can do
different tasks, given correct control
signals
• Instead of re-wiring, supply a new set of
control signals

What is a program?
• A sequence of steps
• For each step, an arithmetic or logical
operation is done
• For each operation, a different set of
control signals is needed

Function of Control Unit
• For each operation a unique code is
provided
– e.g. ADD, MOVE
• A hardware segment accepts the code
and issues the control signals


Components
• The Control Unit and the Arithmetic and
Logic Unit constitute the Central
Processing Unit
• Data and instructions need to get into the
system and results out
– Input/output
• Temporary storage of code and results is
needed
– Main memory
Computer Components:
Top Level View
Instruction Cycle
• Two steps:
– Fetch
– Execute
Fetch Cycle
• Program Counter (PC) holds address of next instruction
to fetch
• Processor fetches instruction from memory location
pointed to by PC
• Increment PC
– Unless told otherwise
• Instruction loaded into Instruction Register (IR)
• Processor interprets instruction and performs required
actions
Execute Cycle
• Processor-memory
– data transfer between CPU and main memory
• Processor I/O
– Data transfer between CPU and I/O module
• Data processing
– Some arithmetic or logical operation on data
• Control
– Alteration of sequence of operations
– e.g. jump
• Combination of above
Example of Program Execution
Connecting
• All the units must be connected
• Different type of connection for different
type of unit
– Memory
– Input/Output
– CPU
Memory Connection
• Receives and sends data
• Receives addresses (of locations)
• Receives control signals
– Read
– Write
– Timing
Input/Output Connection(1)
• Similar to memory from computer’s
viewpoint
• Output
– Receive data from computer
– Send data to peripheral
• Input
– Receive data from peripheral
– Send data to computer

Input/Output Connection(2)
• Receive control signals from computer
• Send control signals to peripherals
– e.g. spin disk
• Receive addresses from computer
– e.g. port number to identify peripheral
• Send interrupt signals (control)
CPU Connection
• Reads instruction and data
• Writes out data (after processing)
• Sends control signals to other units
• Receives (& acts on) interrupts

Buses
• There are a number of possible
interconnection systems
• Single and multiple BUS structures are
most common
• e.g. Control/Address/Data bus (PC)
• e.g. Unibus (DEC-PDP)
What is a Bus?
• A communication pathway connecting two
or more devices
• Usually broadcast
• Often grouped
– A number of channels in one bus
– e.g. 32 bit data bus is 32 separate single
bit channels
• Power lines may not be shown
Data Bus
• Carries data
– Remember that there is no difference
between “data” and “instruction” at this
level
• Width is a key determinant of performance
– 8, 16, 32, 64 bit
Address bus
• Identify the source or destination of data
• e.g. CPU needs to read an instruction
(data) from a given location in memory
• Bus width determines maximum memory
capacity of system
– e.g. 8080 has 16 bit address bus giving
64k address space
Control Bus
• Control and timing information
– Memory read/write signal
– Interrupt request
– Clock signals


Bus Interconnection Scheme
• What do buses look like?
– Parallel lines on circuit boards
– Ribbon cables
– Strip connectors on mother boards
• e.g. PCI
– Sets of wires
Single Bus Problems
• Lots of devices on one bus leads to:
– Propagation delays
• Long data paths mean that co-ordination of
bus use can adversely affect performance
• If aggregate data transfer approaches bus
capacity
• Most systems use multiple buses to
overcome these problems
Traditional (ISA)
(with cache)
High Performance Bus
Bus Types
• Dedicated
– Separate data & address lines
• Multiplexed
– Shared lines
– Address valid or data valid control line
– Advantage - fewer lines
– Disadvantages
• More complex control
• Ultimate performance

Bus Arbitration
• More than one module controlling the bus
• e.g. CPU and DMA controller
• Only one module may control bus at one
time
• Arbitration may be centralised or
distributed
Centralised Arbitration
• Single hardware device controlling bus
access
– Bus Controller
– Arbiter
• May be part of CPU or separate

Distributed Arbitration
• Each module may claim the bus
• Control logic on all modules

Timing
• Co-ordination of events on bus
• Synchronous
– Events determined by clock signals
– Control Bus includes clock line
– A single 1-0 is a bus cycle
– All devices can read clock line
– Usually sync on leading edge
– Usually a single cycle for an event
Synchronous Timing Diagram
Asynchronous Timing Diagram
PCI Bus
• Peripheral Component Interconnection
• Intel released to public domain
• 32 or 64 bit
• 50 lines

• The PDP-11 was a series of 16-bit minicomputers sold
by Digital Equipment Corp. in the 1970s and 1980s.
The PDP-11 was a successor to DEC's PDP-8
computer in the PDP series of computers.
• It had several uniquely innovative features, and was
easier to program than its predecessors. While well-
liked by programmers, it was replaced in the mid-
range minicomputer niche by the VAX-11 32-bit
extension of the PDP-11.
• Much of the market for both machines would be taken by
personal computers, including the IBM PC and Apple
II, and workstations, such as those from Sun
Microsystems.
Arithmetic & Logic Unit
• Does the calculations
• Everything else in the computer is there to
service this unit
• Handles integers
• May handle floating point (real) numbers
• May be separate FPU (maths co-
processor)
• May be on chip separate FPU (486DX +)
ALU Inputs and Outputs
Integer Representation
• Only have 0 & 1 to represent everything
• Positive numbers stored in binary
– e.g. 41=00101001
• No minus sign
• No period
• Sign-Magnitude
• Two’s compliment
Sign-Magnitude
• Left most bit is sign bit
• 0 means positive
• 1 means negative
• +18 = 00010010
• -18 = 10010010
• Problems
– Need to consider both sign and magnitude in
arithmetic
– Two representations of zero (+0 and -0)
Two’s Compliment
• +3 = 00000011
• +2 = 00000010
• +1 = 00000001
• +0 = 00000000
• -1 = 11111111
• -2 = 11111110
• -3 = 11111101
Benefits
• One representation of zero
• Arithmetic works easily (see later)
• Negating is fairly easy
– 3 = 00000011
– Boolean complement gives 11111100
– Add 1 to LSB 11111101

Geometric Depiction of Twos
Complement Integers
Negation Special Case 1
• 0= 00000000
• Bitwise not 11111111
• Add 1 to LSB +1
• Result 1 00000000
• Overflow is ignored, so:
• -0=0
Negation Special Case 2
• -128 = 10000000
• bitwise not 01111111
• Add 1 to LSB +1
• Result 10000000
• So:
• -(-128) = -128 X
• Monitor MSB (sign bit)
• It should change during negation

Range of Numbers
• 8 bit 2s compliment
– +127 = 01111111 = 27 -1
– -128 = 10000000 = -27
• 16 bit 2s compliment
– +32767 = 011111111 11111111 = 215 - 1
– -32768 = 100000000 00000000 = -215

Conversion Between Lengths
• Positive number pack with leading zeros
• +18 = 00010010
• +18 = 00000000 00010010
• Negative numbers pack with leading ones
• -18 = 10010010
• -18 = 11111111 10010010
• i.e. pack with MSB (sign bit)
Addition and Subtraction
• Normal binary addition
• Monitor sign bit for overflow

• Take twos compliment of substahend and
add to minuend
– i.e. a - b = a + (-b)

• So we only need addition and complement
circuits
Hardware for Addition and
Subtraction
Multiplication
• Complex
• Work out partial product for each digit
• Take care with place value (column)
• Add partial products

Multiplication Example
• 1011 Multiplicand (11 dec)
• x 1101 Multiplier (13 dec)
• 1011 Partial products
• 0000 Note: if multiplier bit is 1 copy
• 1011 multiplicand (place value)
• 1011 otherwise zero
• 10001111 Product (143 dec)
• Note: need double length result
Unsigned Binary Multiplication
Execution of Example
Flowchart for Unsigned Binary
Multiplication
Multiplying Negative Numbers
• This does not work!
• Solution 1
– Convert to positive if required
– Multiply as above
– If signs were different, negate answer
• Solution 2
– Booth’s algorithm

Booth’s Algorithm
Example of Booth’s Algorithm
Division
• More complex than multiplication
• Negative numbers are really bad!
• Based on long division
Division of Unsigned Binary
Integers
00001101 Quotient
Divisor 1011 10010011 Dividend
1011
001110
Partial 1011
Remainders
001111
1011
100 Remainder
Real Numbers
• Numbers with fractions
• Could be done in pure binary
– 1001.1010 = 24 + 20 +2-1 + 2-3 =9.625
• Where is the binary point?
• Fixed?
– Very limited
• Moving?
– How do you show where it is?
Sign bit Floating Point

Biased Significand or Mantissa


Exponent
• +/- .significand x 2exponent
• Point is actually fixed between sign bit and
body of mantissa
• Exponent indicates place value (point
position)
Floating Point Examples
Signs for Floating Point
• Mantissa is stored in 2s compliment
• Exponent is in excess or biased notation
– e.g. Excess (bias) 128 means
– 8 bit exponent field
– Pure value range 0-255
– Subtract 128 to get correct value
– Range -128 to +127
Normalization
• FP numbers are usually normalized
• i.e. exponent is adjusted so that leading bit
(MSB) of mantissa is 1
• Since it is always 1 there is no need to
store it
• (c.f. Scientific notation where numbers are
normalized to give a single digit before
the decimal point
• e.g. 3.123 x 103)
FP Ranges
• For a 32 bit number
– 8 bit exponent
– +/- 2256  1.5 x 1077
• Accuracy
– The effect of changing lsb of mantissa
– 23 bit mantissa 2-23  1.2 x 10-7
– About 6 decimal places
Expressible Numbers
IEEE 754
• Standard for floating point storage
• 32 and 64 bit standards
• 8 and 11 bit exponent respectively
• Extended formats (both mantissa and
exponent) for intermediate results

FP Arithmetic +/-
• Check for zeros
• Align significands (adjusting exponents)
• Add or subtract significands
• Normalize result
FP Arithmetic x/
• Check for zero
• Add/subtract exponents
• Multiply/divide significands (watch sign)
• Normalize
• Round
• All intermediate results should be in
double length storage
Floating
Point
Multiplication
Floating
Point
Division
Use of Stack
• Examples of uses of
stack include-
traversing and
evaluating prefix, infix
and postfix expressions.
• Consider the expression A+B:
we think of applying the
operator “+” to the operands
A and B

• Firstly, + operator requires two


operators or in other words
“+” is a binary operator.
• Secondly, in the expression A+B,
the one operand A is on left of
the operator while the other
operand B is on the right side.

• This kind of expressions where the


operator is present between two
operands called infix
expressions.
• There are two other ways of writing
expressions:
• We could write +AB, the operator is
written before the operands A
and B. These kinds of
expressions are called Prefix
Expressions.
• We can also write it as AB+, the
operator is written after the
operands A and B. This
expression is called Postfix
expression.
• Evaluating postfix
expressions
• An example
• Infix to postfix Conversion

Evaluating postfix expressions
• We have discussed about
post fix and infix expression

INFIX POSTFIX
A+B AB+
12 + 60 – 23 12 60 + 23 –
(A + B)*(C – D ) AB+CD–*
A  B * C – D + E/F A B  C*D – E F/+
• In the postfix form, parentheses
are not used.
• Consider the infix expressions
as ‘4+3*5’ and ‘(4+3)*5’.
• The parentheses are not
needed in the first but are
necessary in the second
expression. The postfix forms
are:
• 4+3*5 435*+
• (4+3)*5 43+5*
• In case of not using the
parenthesis in the infix form,
you have to see the
precedence rule before
evaluating the expression.
• In the postfix form, we do not need
to use parenthesis.

• The position of operators and


operands in the expression
makes it clear in which order we
have to do the multiplication and
addition.
• Now we will see how the infix
expression can be evaluated.
Suppose we have a postfix
expression.
• How can we evaluate it? Each
operator in a postfix
expression refers to the
previous two operands.
Evaluating postfix expressions
• In the postfix form, parentheses
are not used.
• Consider the infix expressions as
‘4+3*5’ and ‘(4+3)*5’. The
parentheses are not needed in
the first but are necessary in the
second expression. The postfix
forms are:
 4+3*5 435*+
(4+3)*5 43+5*
• In case of not using the
parenthesis in the infix
form, you have to see the
precedence rule before
evaluating the expression
• In the above example, if we want to
add first then we have to use the
parenthesis.
• In the postfix form, we do not need
to use parenthesis. The position
of operators and operands in the
expression makes it clear in
which order we have to do the
multiplication and addition.
Evaluating postfix expressions

• We are going to evaluate the


postfix expression with the
help of stack.
• After reaching an operator, we
pop the two operands from
the top of the stack, apply the
operator and push the result
back on the stack.
• Now we will see an example
to comprehend the working
of stack for the evaluation
of the postfix form. Here is
the algorithm in pseudo
code form.

• Stack s; //declare a stack
• while( not end of input ) { // not end of postfix
expression
• e = get next element of input
• if( e is an operand )
• s.push( e );
• else {
• op2 = s.pop();
• op1 = s.pop();
• value = result of applying operator ‘e’ to op1 and
op2;
• s.push( value );
• }
• }
• finalresult = s.pop();
• If ‘e’ is an operand than we wrote
s.push(e) i.e. we pushed the ‘e’
onto the stack.
• If ‘e’ is not the operand, it may be
an operator. Therefore we will
pop the two elements and apply
that operator. We pop the stack
and store the operand in ‘op2’.
We pop the stack again and store
the element in ‘op1’.
• Consider a postfix form of
432*+.
• Here 4, 3, and 2 are
operands whereas + and *
are operators.
• We will push the numbers 4,
3 and 2 on the stack before
getting the operator *.
An Example

• The postfix expression is:


•6 2 3 + - 3 8 2 / + * 2  3 +
Input op1 op2 value stack

6 6

2 2
6

3 3
2
6

+ 2 3 5 5
6

- 6 5 1 1

3 6 5 1 3
1

8 6 5 1 8
3
1

2 6 5 1 2
8
3
1

/ 8 2 4 4
3
1

+ 3 4 7 7
1

* 1 7 7 7

2 1 7 7 2
7

 7 2 49 49

3 7 2 49 3
49

+ 49 3 52 52
•With the help of stack
we can easily solve a
very big postfix
expression.
Conversion from infix to postfix

• We have seen how to evaluate the


postfix expressions while using
the stack. How can we convert
the infix expression into postfix
form?
• Consider the infix expressions
‘A+B*C’ and ‘(A+B)*C’. The
postfix versions are ‘ABC*+’ and
‘AB+C*’ respectively.
• The order of operands in
postfix is the same as that in
the infix.

• In both the infix expressions,


we have the order of operands
as A, B and then C.
• In the postfix expressions too, the
order is the same i.e. A, B, followed
by C. The order of operands is not
changed in postfix form. However,
the order of operators may be
changed.

•Now we will try to
form an algorithm
to convert infix form
into postfix form.
• We will be using a stack in this
algorithm. Here, the infix
expression is in the form of a
string. The algorithm is as
follows:
• First rule of algorithm is that if we
find the operand in the infix form,
put it in the postfix form
• Stack s;
• while( not end of input ) {
• c = next input character;
• if( c is an operand )
• add c to postfix string;
• else {
• while( !s.empty() && prcd(s.top(),c) ){
• op = s.pop();
• add op to the postfix string;
• }
• s.push( c );
• }
• while( !s.empty() ) {
• op = s.pop();
• add op to postfix string;
• }
• Here the input character does not mean
one character, but an operand or an
operator.
• Then we have a conditional if
statement.
• If ‘c’ is an operand, then we will have to
add it to postfix string. Whenever we
get an operand in the infix form, it will
be added to the postfix form. The
order of operands does not change in
the conversion
Symbol postfix stack

A A

+ A +

B AB +

* AB *
+

C ABC* +

ABC*+
• Sometimes we do need the
parenthesis in the infix form.

• We have to evaluate the lower


precedence operator before the
higher precedence operator.

• If we have the expression (A+B) *C, this
means that we have to evaluate +
before the multiplication. The
objective of using parenthesis is to
establish precedence.

• It forces to evaluate the expression first


of all.
• We also have to handle parenthesis
while converting the infix expression
into postfix one.
• When an open parenthesis ‘(‘ is read, it
must be pushed on the stack. This
can be done by setting prcd(op,‘(‘ ) to
be FALSE.
• The rules for operators are
different. The ‘+’ cannot be
inserted in the postfix
expression until its second
operand has been scanned
and inserted.
•Keep the expression
A+B*C in your
mind.
• What is the second operand
of the plus? The first
operand is A and the
second operand is the
result of B*C. The ‘+’ has
to wait until the ‘*’ has not
been performed.
• In case of ‘(A+B)*C’, the
closing parenthesis
indicates that ‘+’ must
be performed first.
• prcd(op1,op2)’
• where op1 and op2 are two
operators
• The function ‘prcd(op1,op2)’ will
return TRUE if op1 has
precedence over op2, FASLE
otherwise.
• Suppose we call this function
with the arguments ‘*’ and ‘+’
i.e. prcd(*, +), it will return
true.
• It will also return true in case
both op1 and op2 are ‘+’ e.g. if
we have A+B+C, then it does
not matter which + we
perform first.
• The call prcd(+ , *) will return
false as the precedence of *
is higher than the +
operator. The ‘+’ has to
wait until * is performed.

You might also like