SlideShare une entreprise Scribd logo
1  sur  8
Télécharger pour lire hors ligne
ecomputernote.com Data Structures                           Lecture No. 07
___________________________________________________________________


Data Structures

Lecture No. 07


Evaluating postfix expressions
In the previous lecture, we talked about infix and postfix expression and tried to
understand how to write the postfix notation of mathematical expressions. A
programmer can write the operators either after the operands i.e. postfix notation or
before the operands i.e. prefix notation. Some of the examples are as under:

                   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/+

The last expression seems a bit confusing but may prove simple by following the rules
in letter and spirit. 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.

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. As the operators are binary (we are not talking about unary
operators here), so two operands are needed for each operator. The nature of these
operators is not affected in the postfix form i.e. the plus operator (+) will apply on two
operands. Each time we read an operand, we will push it on the stack. 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. After
reading this code, you will understand the algorithm.


         Stack s;                         // declare a stack
         while( not end of input ) {           // not end of postfix expression


                                                                              Page 1 of 8
ecomputernote.com Data Structures                           Lecture No. 07
___________________________________________________________________
              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();


We have declared a Stack s . There is a while loop along with not end of input
condition. Here the input is our postfix expression. You can get the expression from
the keyboard and use the enter key to finish the expression. In the next statement, we
get the next element and store it in e . This element can be operator or operand. The
operand needs not to be single digit. It may be of two digits or even more like 60 or
234 etc. The complete number is stored in the e . Then we have an if statement to
check whether e is an operand or not. 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 .
Then the operator in e is applied to op1 and op2 before storing the result in value.
In the end, we push the value on the stack. After exiting the loop, a programmer may
have only one element in the stack. We pop this element which is the final result.

Consider the example of 4+3*2 having 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 *. Two operands will be popped from the stack and *
is being applied on these. As stack is a LIFO structure, so we get 2 first and then 3 as a
result of pop. So 2 is store in op1 and 3 in op2 . Let s have a look on the program
again. On applying * on these, we will push the result (i.e. 6) on the stack. The while
loop will be executed again. In case of getting the next input as operand, we will push
it on the stack otherwise we will pop the two operands and apply the operator on
these. Here the next element is the operator +. So two operands will be popped from
the stack i.e. 6 and 4. We will apply the operator plus on these and push the result (i.e.
10) on the stack. The input is finished. Now we will pop the stack to get the final result
i.e. 10.

An Example
In the earlier example, we have used the stack to solve the postfix expression. Let s
see another comprehensive example. The postfix expression is:

         623+-382/+*2↑3+

We want to evaluate this long expression using stack. Let s try to solve it on paper.
We have five columns here i.e. input, op1, op2, value and stack. We will run our


                                                                              Page 2 of 8
ecomputernote.com Data Structures                           Lecture No. 07
___________________________________________________________________
pseudo code program. In the start, we read the input as a result we get number 6. As 6
is operand, so it will be pushed on the stack. Then we have number 2 which will also
be pushed on the stack. Now 2 is the most recent element. The next element is the
number 3 that will also be pushed on the stack. Now, there are three elements on the
stack i.e. 3, 2 and 6. The number 3 is the most recent. On popping, we will get the
number 3 first of all. The next element is + , an operator. Now the else part of our
pseudo code is executed. We will pop two operands from the stack and apply the
operator (+) on these. The number 3 will be stored in variable op2 and number 2 in
op1. The operator (+) will be applied on these i.e. 2+3 and the result is stored in value.
Now we will push the value (i.e. 5) on the stack. Now we have two numbers on the
stack i.e. 5 and 6. The number 5 is the most recent element. The next element is - . As
it is also an operator, so we will pop the two elements from the stack i.e. 5 and 6. Now
we have 5 in op2 and 6 in op1. On applying the operator (-), we will get the result as 1
(6-5). We can t say op2 - op1. The result (1) will be pushed on stack. Now on the
stack, we have only one element i.e. 1. Next three elements are operands so we pushed
3, 8 and 2 on the stack. The most recent element is 2. The next input is an operator in
the expression i.e. / , we will pop two elements from the stack. The number 2 will be
stored in op2 while number 8 in op1. We apply the operator (/) on the op1 and op2 i.e.
(op1/op2), the result is 4 (i.e. 8/2). We push the result on the stack. We have, now,
three elements i.e. 4, 3, and 1 on the stack. The next element is operator plus (+). We
will pop the two elements i.e. 4 and 3 and will apply the operator (+). The result (7)
will be pushed on the stack. The next input element is operator multiply (*). We will
pop the two elements i.e. 7 and 1 and the result (7*1 = 7) is pushed on the stack. You
have noted that whenever we have an operator in the input expression, we have two or
more elements on the stack. As the operators we are using are binary and we need two
operands for them. It will never be the case that you want to pop two elements from
the stack and there is only one or no element on the stack. If this happens than it means
there is an error in the program and you have popped more values than required. The
next input element is 2 that is pushed on the stack. We have, now, the operator ( ↑ ) in
the input. So we will pop the two elements, op2 will hold 2 and op1 will have the
number 7. The operator ( ↑ ) will be applied on the operands i.e. (7 ↑ 2) and the result
(49) is pushed on the stack. We have, now, the number 3 in the element being pushed
on the stack. The last element is the operator plus (+). So we pop the two elements i.e.
49 and 2 and apply the operator on these. The result (49+3 = 52) is pushed on the
stack. The input expression is finished, resulting in the final result i.e. 52.

This the tabular form of the evaluation of the postfix expression.

                 Input       op1      op2       value         stack
                 6                                            6
                 2                                            2
                                                              6
                 3                                            3
                                                              2
                                                              6
                 +           2        3         5             5
                                                              6
                 -           6        5         1             1



                                                                              Page 3 of 8
ecomputernote.com Data Structures                           Lecture No. 07
___________________________________________________________________
                 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. Suppose you
want to make a calculator that is a part of some application e.g. some spreadsheet
program. This calculator will be used to evaluate expressions. You may want to
calculate the value of a cell after evaluating different cells. Evaluation of the infix form
programmatically is difficult but it can be done. We will see another data structure
which being used to solve the expressions in infix form. Currently, we have to evaluate
the values in different cells and put this value in another cell. How can we do that? We
will make the postfix form of the expression associated with that cell. Then we can
apply the above algorithm to solve the postfix expression and the final result will be
placed at that cell. This is one of the usages of the stack.

Infix to postfix Conversion
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 example of a
spreadsheet. We have to evaluate expressions. The users of this spreadsheet will
employ the infix form of expressions. 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. In the first expression
 A+B*C , the postfix expression is ABC*+ . In the postfix form multiplication comes
before the plus operator. In scanning from left to right, the operand A can be inserted
into postfix expression. First rule of algorithm is that if we find the operand in the infix
form, put it in the postfix form. The rules for operators are different. The + cannot be
inserted in the postfix expression until its second operand has been scanned and


                                                                               Page 4 of 8
ecomputernote.com Data Structures                           Lecture No. 07
___________________________________________________________________
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. You do the same thing while using the
calculator. First you will multiply the B*C and then add A into the result. The + has
to be stored away until its proper position is found. When B is seen, it is immediately
inserted into the postfix expression. As B is the operand, we will send the operand to
the postfix form. Can the + be inserted now? In case of A+B*C , we cannot insert
 + because * has precedence. To perform multiplication, we need the second
operand. The first operand of multiplication is B while the second one is C . So at
first, we will perform the multiplication before adding result to A .

In case of (A+B)*C , the closing parenthesis indicates that + must be performed
first. After sending the A and B to postfix perform, we can perform the addition due to
the presence of the parenthesis. Then C will be sent to the postfix expression. It will be
followed by the multiplication of the C and the result of A + B. The postfix form of
this expression is AB+C*. Sometimes, we have two operators and need to decide
which to apply first like in this case + and * . In this case, we have to see which
operator has higher precedence. Assume that we have a function 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.

Now we will try to form an algorithm to convert infix form into postfix form. For this
purpose, a pseudo code will be written. We will also write the loops and if conditions.
The pseudo code is independent of languages. 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:

        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;
          }

First we will declare a stack s . The while loop will continue till the end of input. We


                                                                              Page 5 of 8
ecomputernote.com Data Structures                           Lecture No. 07
___________________________________________________________________
read the input character and store it in the c . 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. However, in this case, the order of operators may
change. If c is the operator, then we will, at first, check that stack is not empty
besides identifying the precedence of the operators between the input operator and the
operator that is at the top of the stack. In case of the precedence of the operator that is
on the stack is higher, we will pop it from the stack and send to the postfix string. For
example if we have * on the stack and the new input operator is +. As the precedence
of the + operator is less than the * operator, the operands of the multiplication has
already been sent to the postfix expression. Now, we should send the * operator to the
postfix form. The plus operator (+) will wait. When the while loop sends all such
operators to the postfix string, it will push the new operator to the stack that is in c .
It has to wait till we get the second operand. Then we will again get the input. On the
completion of the input, the while loop will be finished. There may be a case that input
may be completed even at the time when there are still some elements on the stack.
These are operators. To check this, we have another while loop. This loop checks if
the stack is not empty, pops the operator and put it in the postfix string. Let s take a
look at a comprehensive example to understand it. In case of the infix expression, A +
B * C, we have three columns, one each for input symbol, the postfix expression and
the stack respectively. Now let s execute the pseudo code. First of all, we get the A
as input. It is an operand so we put it on the postfix string. The next input is the plus
operator (+) which will be pushed on the stack. As it is an operator and we need two
operands for it. On having a look at the expression, you might have figure out that the
second operand for the plus operator is B*C. The next input is the operand B being
sent to the postfix expression form. The next thing we get is the input element as * .
We know that the precedence of * is higher than that of the +. Let s see how we can
do that according to our pseudo code. The prcd(s.top(), op) takes two operands. We
will get the top element of the stack i.e. + will be used as first argument. The second
argument is the input operator i.e. *. So the function call will be as prcd(+, *) while
the function returns false because the precedence of the plus operator is not higher
than the multiplication operator. So far, we have only one operand for multiplication
i.e. B. As multiplication is also a binary operator, it will also have to wait for the
second operand. It has to wait and the waiting room is stack. So we will push it on the
stack. Now the top element of the stack is *. The next symbol is C . Being an
operand, C will be added to the postfix expression. At this point, our input expression
has been completed. Our first while loop executes till the end of input. After the end
of the input, the loop will be terminated. Now the control goes to the second while
loop which says if there is something on the stack, pop it and add it the postfix
expression. In this case, we have * and + on the stack. The * is at the top of the stack.
So when we pop, we get * which is at the top of the stack and it will be added to the
postfix expression. In the result of second pop, we get the plus operator (+) which is
also added to the postfix expression. The stack is empty now. The while loop will be
terminated and postfix expression is formed i.e. ABC*+.

                 Symbol          postfix                  stack
                   A               A
                   +               A                        +


                                                                               Page 6 of 8
ecomputernote.com Data Structures                           Lecture No. 07
___________________________________________________________________
                    B               AB                      +
                    *               AB                      *
                                                            +
                    C              ABC                      *
                                                            +
                                 ABC*                       +
                                 ABC*+

If we have to convert the infix expression into the postfix form, the job is easily done
with the help of stack. The above algorithm can easily be written in C++ or C
language, specially, if you already have the stack class. Now you can convert very big
infix expressions into postfix expressions. Why we have done this? This can be
understood with the help of the example of spreadsheet programming where the value
of cell is the evaluation of some expression. The user of the spreadsheets will use the
infix expressions as they are used to it.

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. What is the reason
to put the parenthesis on the stack? It is due to the fact that as long as the closing
parenthesis is not found, the open parenthesis has to wait. It is not a unary or binary
operator. Actually, it is a way to show or write precedence. We can handle the
parenthesis by adding some extra functionality in our prcd function. When we call
prcd(op, ( ), it will return false for all the operators and be pushed on the stack. Also,
prcd( ( ,op ) is FALSE which ensures that an operator after ( is pushed on the stack.
When a ) is read. All operators up to the first ( must be popped and placed in the
postfix string. To achieve this our function prcd( op, ) ) should return true for all the
operators. Both the ( and the ) will not go to the postfix expression. In postfix
expression, we do not need parenthesis. The precedence of the operators is established
in such a way that there is no need of the parenthesis. To include the handling of
parenthesis, we have to change our algorithm. We have to change the line s.push(c) to:

         if( s.empty() || symb != ) )
               s.push( c );
         else
               s.pop(); // discard the (

If the input symbol is not ) and the stack is not empty, we will push the operator on
the stack. Otherwise, it is advisable to pop the stack and discard the ( . The following
functionality has to be added in the prcd function.

         prcd( ( , op )     =    FALSE             for any operator
         prcd( op, ) )      =    FALSE             for any operator other than )
         prcd( op, ) )      =    TRUE              for any operator other than (
         prcd( ) , op )     =    error             for any operator.


                                                                              Page 7 of 8
ecomputernote.com Data Structures                           Lecture No. 07
___________________________________________________________________


In the next lecture we will see in detail an example regarding the use of parenthesis.




                                                                              Page 8 of 8

Contenu connexe

Tendances

Computer Networking Lab File
Computer Networking Lab FileComputer Networking Lab File
Computer Networking Lab FileNitin Bhasin
 
Prefix, Infix and Post-fix Notations
Prefix, Infix and Post-fix NotationsPrefix, Infix and Post-fix Notations
Prefix, Infix and Post-fix NotationsAfaq Mansoor Khan
 
Stack data structure
Stack data structureStack data structure
Stack data structureTech_MX
 
Polish Notation In Data Structure
Polish Notation In Data StructurePolish Notation In Data Structure
Polish Notation In Data StructureMeghaj Mallick
 
My lecture infix-to-postfix
My lecture infix-to-postfixMy lecture infix-to-postfix
My lecture infix-to-postfixSenthil Kumar
 
Manchester & Differential Manchester encoding scheme
Manchester & Differential Manchester encoding schemeManchester & Differential Manchester encoding scheme
Manchester & Differential Manchester encoding schemeArunabha Saha
 
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...Balwant Gorad
 
linked list in Data Structure, Simple and Easy Tutorial
linked list in Data Structure, Simple and Easy Tutoriallinked list in Data Structure, Simple and Easy Tutorial
linked list in Data Structure, Simple and Easy TutorialAfzal Badshah
 
Stack data structure in Data Structure using C
Stack data structure in Data Structure using C Stack data structure in Data Structure using C
Stack data structure in Data Structure using C Meghaj Mallick
 
ELEMENTS OF TRANSPORT PROTOCOL
ELEMENTS OF TRANSPORT PROTOCOLELEMENTS OF TRANSPORT PROTOCOL
ELEMENTS OF TRANSPORT PROTOCOLShashank Rustagi
 
Algorithm analysis
Algorithm analysisAlgorithm analysis
Algorithm analysissumitbardhan
 

Tendances (20)

Computer Networking Lab File
Computer Networking Lab FileComputer Networking Lab File
Computer Networking Lab File
 
Prefix, Infix and Post-fix Notations
Prefix, Infix and Post-fix NotationsPrefix, Infix and Post-fix Notations
Prefix, Infix and Post-fix Notations
 
B and B+ tree
B and B+ treeB and B+ tree
B and B+ tree
 
File handling in c
File handling in cFile handling in c
File handling in c
 
Stack data structure
Stack data structureStack data structure
Stack data structure
 
Packet tracer
Packet tracerPacket tracer
Packet tracer
 
Polish Notation In Data Structure
Polish Notation In Data StructurePolish Notation In Data Structure
Polish Notation In Data Structure
 
Osi model
Osi modelOsi model
Osi model
 
My lecture infix-to-postfix
My lecture infix-to-postfixMy lecture infix-to-postfix
My lecture infix-to-postfix
 
Manchester & Differential Manchester encoding scheme
Manchester & Differential Manchester encoding schemeManchester & Differential Manchester encoding scheme
Manchester & Differential Manchester encoding scheme
 
stack presentation
stack presentationstack presentation
stack presentation
 
Application Layer
Application LayerApplication Layer
Application Layer
 
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
 
Issues in Data Link Layer
Issues in Data Link LayerIssues in Data Link Layer
Issues in Data Link Layer
 
Logic gates presentation
Logic gates presentationLogic gates presentation
Logic gates presentation
 
linked list in Data Structure, Simple and Easy Tutorial
linked list in Data Structure, Simple and Easy Tutoriallinked list in Data Structure, Simple and Easy Tutorial
linked list in Data Structure, Simple and Easy Tutorial
 
Stack data structure in Data Structure using C
Stack data structure in Data Structure using C Stack data structure in Data Structure using C
Stack data structure in Data Structure using C
 
ELEMENTS OF TRANSPORT PROTOCOL
ELEMENTS OF TRANSPORT PROTOCOLELEMENTS OF TRANSPORT PROTOCOL
ELEMENTS OF TRANSPORT PROTOCOL
 
Algorithm analysis
Algorithm analysisAlgorithm analysis
Algorithm analysis
 
Ethernet
EthernetEthernet
Ethernet
 

En vedette

Conversion from infix to prefix using stack
Conversion from infix to prefix using stackConversion from infix to prefix using stack
Conversion from infix to prefix using stackHaqnawaz Ch
 
Infix to Prefix (Conversion, Evaluation, Code)
Infix to Prefix (Conversion, Evaluation, Code)Infix to Prefix (Conversion, Evaluation, Code)
Infix to Prefix (Conversion, Evaluation, Code)Ahmed Khateeb
 
Infix to-postfix examples
Infix to-postfix examplesInfix to-postfix examples
Infix to-postfix examplesmua99
 
Fundamentals of data structures ellis horowitz & sartaj sahni
Fundamentals of data structures   ellis horowitz & sartaj sahniFundamentals of data structures   ellis horowitz & sartaj sahni
Fundamentals of data structures ellis horowitz & sartaj sahniHitesh Wagle
 
Infix prefix postfix expression -conversion
Infix  prefix postfix expression -conversionInfix  prefix postfix expression -conversion
Infix prefix postfix expression -conversionSyed Mustafa
 
Stacks Implementation and Examples
Stacks Implementation and ExamplesStacks Implementation and Examples
Stacks Implementation and Examplesgreatqadirgee4u
 

En vedette (10)

Conversion from infix to prefix using stack
Conversion from infix to prefix using stackConversion from infix to prefix using stack
Conversion from infix to prefix using stack
 
Infix to Prefix (Conversion, Evaluation, Code)
Infix to Prefix (Conversion, Evaluation, Code)Infix to Prefix (Conversion, Evaluation, Code)
Infix to Prefix (Conversion, Evaluation, Code)
 
Infix to-postfix examples
Infix to-postfix examplesInfix to-postfix examples
Infix to-postfix examples
 
Infix to postfix conversion
Infix to postfix conversionInfix to postfix conversion
Infix to postfix conversion
 
Infix to postfix
Infix to postfixInfix to postfix
Infix to postfix
 
Ch06 Stack
Ch06  StackCh06  Stack
Ch06 Stack
 
Fundamentals of data structures ellis horowitz & sartaj sahni
Fundamentals of data structures   ellis horowitz & sartaj sahniFundamentals of data structures   ellis horowitz & sartaj sahni
Fundamentals of data structures ellis horowitz & sartaj sahni
 
Stack
StackStack
Stack
 
Infix prefix postfix expression -conversion
Infix  prefix postfix expression -conversionInfix  prefix postfix expression -conversion
Infix prefix postfix expression -conversion
 
Stacks Implementation and Examples
Stacks Implementation and ExamplesStacks Implementation and Examples
Stacks Implementation and Examples
 

Similaire à computer notes - Evaluating postfix expressions

computer notes - Conversion from infix to postfix
computer notes - Conversion from infix to postfixcomputer notes - Conversion from infix to postfix
computer notes - Conversion from infix to postfixecomputernotes
 
computer notes - Stack
computer notes - Stackcomputer notes - Stack
computer notes - Stackecomputernotes
 
C operators
C operatorsC operators
C operatorsGPERI
 
Although people may be very accustomed to reading and understanding .docx
Although people may be very accustomed to reading and understanding .docxAlthough people may be very accustomed to reading and understanding .docx
Although people may be very accustomed to reading and understanding .docxmilissaccm
 
The concept of stack is extremely important in computer science and .pdf
The concept of stack is extremely important in computer science and .pdfThe concept of stack is extremely important in computer science and .pdf
The concept of stack is extremely important in computer science and .pdfarihantsherwani
 
1.4 expression tree
1.4 expression tree  1.4 expression tree
1.4 expression tree Krish_ver2
 
Linear Data Structures_SSD.pdf
Linear Data Structures_SSD.pdfLinear Data Structures_SSD.pdf
Linear Data Structures_SSD.pdfssuser37b0e0
 
Evaluation of prefix expression with example
Evaluation of prefix expression with exampleEvaluation of prefix expression with example
Evaluation of prefix expression with exampleGADAPURAMSAINIKHIL
 
Class_IX_Operators.pptx
Class_IX_Operators.pptxClass_IX_Operators.pptx
Class_IX_Operators.pptxrinkugupta37
 
MP 4 – Continuation-Passing StyleCS 421 – Fall 2012Revis.docx
MP 4 – Continuation-Passing StyleCS 421 – Fall 2012Revis.docxMP 4 – Continuation-Passing StyleCS 421 – Fall 2012Revis.docx
MP 4 – Continuation-Passing StyleCS 421 – Fall 2012Revis.docxrosemarybdodson23141
 
computer notes - Priority queue
computer notes -  Priority queuecomputer notes -  Priority queue
computer notes - Priority queueecomputernotes
 
computer notes - Linked list
computer notes - Linked listcomputer notes - Linked list
computer notes - Linked listecomputernotes
 
C++ Course - Lesson 2
C++ Course - Lesson 2C++ Course - Lesson 2
C++ Course - Lesson 2Mohamed Ahmed
 
computer notes - Memory organization
computer notes - Memory organizationcomputer notes - Memory organization
computer notes - Memory organizationecomputernotes
 
Control system Lab record
Control system Lab record Control system Lab record
Control system Lab record Yuvraj Singh
 
Unit 2 application of stack
Unit 2  application of stack Unit 2  application of stack
Unit 2 application of stack LavanyaJ28
 

Similaire à computer notes - Evaluating postfix expressions (20)

computer notes - Conversion from infix to postfix
computer notes - Conversion from infix to postfixcomputer notes - Conversion from infix to postfix
computer notes - Conversion from infix to postfix
 
computer notes - Stack
computer notes - Stackcomputer notes - Stack
computer notes - Stack
 
C operators
C operatorsC operators
C operators
 
Although people may be very accustomed to reading and understanding .docx
Although people may be very accustomed to reading and understanding .docxAlthough people may be very accustomed to reading and understanding .docx
Although people may be very accustomed to reading and understanding .docx
 
C++.pptx
C++.pptxC++.pptx
C++.pptx
 
The concept of stack is extremely important in computer science and .pdf
The concept of stack is extremely important in computer science and .pdfThe concept of stack is extremely important in computer science and .pdf
The concept of stack is extremely important in computer science and .pdf
 
1.4 expression tree
1.4 expression tree  1.4 expression tree
1.4 expression tree
 
Linear Data Structures_SSD.pdf
Linear Data Structures_SSD.pdfLinear Data Structures_SSD.pdf
Linear Data Structures_SSD.pdf
 
DS UNIT1_STACKS.pptx
DS UNIT1_STACKS.pptxDS UNIT1_STACKS.pptx
DS UNIT1_STACKS.pptx
 
Evaluation of prefix expression with example
Evaluation of prefix expression with exampleEvaluation of prefix expression with example
Evaluation of prefix expression with example
 
Class_IX_Operators.pptx
Class_IX_Operators.pptxClass_IX_Operators.pptx
Class_IX_Operators.pptx
 
MP 4 – Continuation-Passing StyleCS 421 – Fall 2012Revis.docx
MP 4 – Continuation-Passing StyleCS 421 – Fall 2012Revis.docxMP 4 – Continuation-Passing StyleCS 421 – Fall 2012Revis.docx
MP 4 – Continuation-Passing StyleCS 421 – Fall 2012Revis.docx
 
computer notes - Priority queue
computer notes -  Priority queuecomputer notes -  Priority queue
computer notes - Priority queue
 
Sortsearch
SortsearchSortsearch
Sortsearch
 
computer notes - Linked list
computer notes - Linked listcomputer notes - Linked list
computer notes - Linked list
 
C++ Course - Lesson 2
C++ Course - Lesson 2C++ Course - Lesson 2
C++ Course - Lesson 2
 
computer notes - Memory organization
computer notes - Memory organizationcomputer notes - Memory organization
computer notes - Memory organization
 
Control system Lab record
Control system Lab record Control system Lab record
Control system Lab record
 
Python-Cheat-Sheet.pdf
Python-Cheat-Sheet.pdfPython-Cheat-Sheet.pdf
Python-Cheat-Sheet.pdf
 
Unit 2 application of stack
Unit 2  application of stack Unit 2  application of stack
Unit 2 application of stack
 

Plus de ecomputernotes

computer notes - Data Structures - 30
computer notes - Data Structures - 30computer notes - Data Structures - 30
computer notes - Data Structures - 30ecomputernotes
 
computer notes - Data Structures - 39
computer notes - Data Structures - 39computer notes - Data Structures - 39
computer notes - Data Structures - 39ecomputernotes
 
computer notes - Data Structures - 11
computer notes - Data Structures - 11computer notes - Data Structures - 11
computer notes - Data Structures - 11ecomputernotes
 
computer notes - Data Structures - 20
computer notes - Data Structures - 20computer notes - Data Structures - 20
computer notes - Data Structures - 20ecomputernotes
 
computer notes - Data Structures - 15
computer notes - Data Structures - 15computer notes - Data Structures - 15
computer notes - Data Structures - 15ecomputernotes
 
Computer notes - Including Constraints
Computer notes - Including ConstraintsComputer notes - Including Constraints
Computer notes - Including Constraintsecomputernotes
 
Computer notes - Date time Functions
Computer notes - Date time FunctionsComputer notes - Date time Functions
Computer notes - Date time Functionsecomputernotes
 
Computer notes - Subqueries
Computer notes - SubqueriesComputer notes - Subqueries
Computer notes - Subqueriesecomputernotes
 
Computer notes - Other Database Objects
Computer notes - Other Database ObjectsComputer notes - Other Database Objects
Computer notes - Other Database Objectsecomputernotes
 
computer notes - Data Structures - 28
computer notes - Data Structures - 28computer notes - Data Structures - 28
computer notes - Data Structures - 28ecomputernotes
 
computer notes - Data Structures - 19
computer notes - Data Structures - 19computer notes - Data Structures - 19
computer notes - Data Structures - 19ecomputernotes
 
computer notes - Data Structures - 31
computer notes - Data Structures - 31computer notes - Data Structures - 31
computer notes - Data Structures - 31ecomputernotes
 
computer notes - Data Structures - 4
computer notes - Data Structures - 4computer notes - Data Structures - 4
computer notes - Data Structures - 4ecomputernotes
 
computer notes - Data Structures - 13
computer notes - Data Structures - 13computer notes - Data Structures - 13
computer notes - Data Structures - 13ecomputernotes
 
Computer notes - Advanced Subqueries
Computer notes -   Advanced SubqueriesComputer notes -   Advanced Subqueries
Computer notes - Advanced Subqueriesecomputernotes
 
Computer notes - Aggregating Data Using Group Functions
Computer notes - Aggregating Data Using Group FunctionsComputer notes - Aggregating Data Using Group Functions
Computer notes - Aggregating Data Using Group Functionsecomputernotes
 
computer notes - Data Structures - 16
computer notes - Data Structures - 16computer notes - Data Structures - 16
computer notes - Data Structures - 16ecomputernotes
 
computer notes - Data Structures - 22
computer notes - Data Structures - 22computer notes - Data Structures - 22
computer notes - Data Structures - 22ecomputernotes
 
computer notes - Data Structures - 35
computer notes - Data Structures - 35computer notes - Data Structures - 35
computer notes - Data Structures - 35ecomputernotes
 
computer notes - Data Structures - 36
computer notes - Data Structures - 36computer notes - Data Structures - 36
computer notes - Data Structures - 36ecomputernotes
 

Plus de ecomputernotes (20)

computer notes - Data Structures - 30
computer notes - Data Structures - 30computer notes - Data Structures - 30
computer notes - Data Structures - 30
 
computer notes - Data Structures - 39
computer notes - Data Structures - 39computer notes - Data Structures - 39
computer notes - Data Structures - 39
 
computer notes - Data Structures - 11
computer notes - Data Structures - 11computer notes - Data Structures - 11
computer notes - Data Structures - 11
 
computer notes - Data Structures - 20
computer notes - Data Structures - 20computer notes - Data Structures - 20
computer notes - Data Structures - 20
 
computer notes - Data Structures - 15
computer notes - Data Structures - 15computer notes - Data Structures - 15
computer notes - Data Structures - 15
 
Computer notes - Including Constraints
Computer notes - Including ConstraintsComputer notes - Including Constraints
Computer notes - Including Constraints
 
Computer notes - Date time Functions
Computer notes - Date time FunctionsComputer notes - Date time Functions
Computer notes - Date time Functions
 
Computer notes - Subqueries
Computer notes - SubqueriesComputer notes - Subqueries
Computer notes - Subqueries
 
Computer notes - Other Database Objects
Computer notes - Other Database ObjectsComputer notes - Other Database Objects
Computer notes - Other Database Objects
 
computer notes - Data Structures - 28
computer notes - Data Structures - 28computer notes - Data Structures - 28
computer notes - Data Structures - 28
 
computer notes - Data Structures - 19
computer notes - Data Structures - 19computer notes - Data Structures - 19
computer notes - Data Structures - 19
 
computer notes - Data Structures - 31
computer notes - Data Structures - 31computer notes - Data Structures - 31
computer notes - Data Structures - 31
 
computer notes - Data Structures - 4
computer notes - Data Structures - 4computer notes - Data Structures - 4
computer notes - Data Structures - 4
 
computer notes - Data Structures - 13
computer notes - Data Structures - 13computer notes - Data Structures - 13
computer notes - Data Structures - 13
 
Computer notes - Advanced Subqueries
Computer notes -   Advanced SubqueriesComputer notes -   Advanced Subqueries
Computer notes - Advanced Subqueries
 
Computer notes - Aggregating Data Using Group Functions
Computer notes - Aggregating Data Using Group FunctionsComputer notes - Aggregating Data Using Group Functions
Computer notes - Aggregating Data Using Group Functions
 
computer notes - Data Structures - 16
computer notes - Data Structures - 16computer notes - Data Structures - 16
computer notes - Data Structures - 16
 
computer notes - Data Structures - 22
computer notes - Data Structures - 22computer notes - Data Structures - 22
computer notes - Data Structures - 22
 
computer notes - Data Structures - 35
computer notes - Data Structures - 35computer notes - Data Structures - 35
computer notes - Data Structures - 35
 
computer notes - Data Structures - 36
computer notes - Data Structures - 36computer notes - Data Structures - 36
computer notes - Data Structures - 36
 

Dernier

Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 

Dernier (20)

Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 

computer notes - Evaluating postfix expressions

  • 1. ecomputernote.com Data Structures Lecture No. 07 ___________________________________________________________________ Data Structures Lecture No. 07 Evaluating postfix expressions In the previous lecture, we talked about infix and postfix expression and tried to understand how to write the postfix notation of mathematical expressions. A programmer can write the operators either after the operands i.e. postfix notation or before the operands i.e. prefix notation. Some of the examples are as under: 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/+ The last expression seems a bit confusing but may prove simple by following the rules in letter and spirit. 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. 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. As the operators are binary (we are not talking about unary operators here), so two operands are needed for each operator. The nature of these operators is not affected in the postfix form i.e. the plus operator (+) will apply on two operands. Each time we read an operand, we will push it on the stack. 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. After reading this code, you will understand the algorithm. Stack s; // declare a stack while( not end of input ) { // not end of postfix expression Page 1 of 8
  • 2. ecomputernote.com Data Structures Lecture No. 07 ___________________________________________________________________ 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(); We have declared a Stack s . There is a while loop along with not end of input condition. Here the input is our postfix expression. You can get the expression from the keyboard and use the enter key to finish the expression. In the next statement, we get the next element and store it in e . This element can be operator or operand. The operand needs not to be single digit. It may be of two digits or even more like 60 or 234 etc. The complete number is stored in the e . Then we have an if statement to check whether e is an operand or not. 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 . Then the operator in e is applied to op1 and op2 before storing the result in value. In the end, we push the value on the stack. After exiting the loop, a programmer may have only one element in the stack. We pop this element which is the final result. Consider the example of 4+3*2 having 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 *. Two operands will be popped from the stack and * is being applied on these. As stack is a LIFO structure, so we get 2 first and then 3 as a result of pop. So 2 is store in op1 and 3 in op2 . Let s have a look on the program again. On applying * on these, we will push the result (i.e. 6) on the stack. The while loop will be executed again. In case of getting the next input as operand, we will push it on the stack otherwise we will pop the two operands and apply the operator on these. Here the next element is the operator +. So two operands will be popped from the stack i.e. 6 and 4. We will apply the operator plus on these and push the result (i.e. 10) on the stack. The input is finished. Now we will pop the stack to get the final result i.e. 10. An Example In the earlier example, we have used the stack to solve the postfix expression. Let s see another comprehensive example. The postfix expression is: 623+-382/+*2↑3+ We want to evaluate this long expression using stack. Let s try to solve it on paper. We have five columns here i.e. input, op1, op2, value and stack. We will run our Page 2 of 8
  • 3. ecomputernote.com Data Structures Lecture No. 07 ___________________________________________________________________ pseudo code program. In the start, we read the input as a result we get number 6. As 6 is operand, so it will be pushed on the stack. Then we have number 2 which will also be pushed on the stack. Now 2 is the most recent element. The next element is the number 3 that will also be pushed on the stack. Now, there are three elements on the stack i.e. 3, 2 and 6. The number 3 is the most recent. On popping, we will get the number 3 first of all. The next element is + , an operator. Now the else part of our pseudo code is executed. We will pop two operands from the stack and apply the operator (+) on these. The number 3 will be stored in variable op2 and number 2 in op1. The operator (+) will be applied on these i.e. 2+3 and the result is stored in value. Now we will push the value (i.e. 5) on the stack. Now we have two numbers on the stack i.e. 5 and 6. The number 5 is the most recent element. The next element is - . As it is also an operator, so we will pop the two elements from the stack i.e. 5 and 6. Now we have 5 in op2 and 6 in op1. On applying the operator (-), we will get the result as 1 (6-5). We can t say op2 - op1. The result (1) will be pushed on stack. Now on the stack, we have only one element i.e. 1. Next three elements are operands so we pushed 3, 8 and 2 on the stack. The most recent element is 2. The next input is an operator in the expression i.e. / , we will pop two elements from the stack. The number 2 will be stored in op2 while number 8 in op1. We apply the operator (/) on the op1 and op2 i.e. (op1/op2), the result is 4 (i.e. 8/2). We push the result on the stack. We have, now, three elements i.e. 4, 3, and 1 on the stack. The next element is operator plus (+). We will pop the two elements i.e. 4 and 3 and will apply the operator (+). The result (7) will be pushed on the stack. The next input element is operator multiply (*). We will pop the two elements i.e. 7 and 1 and the result (7*1 = 7) is pushed on the stack. You have noted that whenever we have an operator in the input expression, we have two or more elements on the stack. As the operators we are using are binary and we need two operands for them. It will never be the case that you want to pop two elements from the stack and there is only one or no element on the stack. If this happens than it means there is an error in the program and you have popped more values than required. The next input element is 2 that is pushed on the stack. We have, now, the operator ( ↑ ) in the input. So we will pop the two elements, op2 will hold 2 and op1 will have the number 7. The operator ( ↑ ) will be applied on the operands i.e. (7 ↑ 2) and the result (49) is pushed on the stack. We have, now, the number 3 in the element being pushed on the stack. The last element is the operator plus (+). So we pop the two elements i.e. 49 and 2 and apply the operator on these. The result (49+3 = 52) is pushed on the stack. The input expression is finished, resulting in the final result i.e. 52. This the tabular form of the evaluation of the postfix expression. Input op1 op2 value stack 6 6 2 2 6 3 3 2 6 + 2 3 5 5 6 - 6 5 1 1 Page 3 of 8
  • 4. ecomputernote.com Data Structures Lecture No. 07 ___________________________________________________________________ 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. Suppose you want to make a calculator that is a part of some application e.g. some spreadsheet program. This calculator will be used to evaluate expressions. You may want to calculate the value of a cell after evaluating different cells. Evaluation of the infix form programmatically is difficult but it can be done. We will see another data structure which being used to solve the expressions in infix form. Currently, we have to evaluate the values in different cells and put this value in another cell. How can we do that? We will make the postfix form of the expression associated with that cell. Then we can apply the above algorithm to solve the postfix expression and the final result will be placed at that cell. This is one of the usages of the stack. Infix to postfix Conversion 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 example of a spreadsheet. We have to evaluate expressions. The users of this spreadsheet will employ the infix form of expressions. 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. In the first expression A+B*C , the postfix expression is ABC*+ . In the postfix form multiplication comes before the plus operator. In scanning from left to right, the operand A can be inserted into postfix expression. First rule of algorithm is that if we find the operand in the infix form, put it in the postfix form. The rules for operators are different. The + cannot be inserted in the postfix expression until its second operand has been scanned and Page 4 of 8
  • 5. ecomputernote.com Data Structures Lecture No. 07 ___________________________________________________________________ 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. You do the same thing while using the calculator. First you will multiply the B*C and then add A into the result. The + has to be stored away until its proper position is found. When B is seen, it is immediately inserted into the postfix expression. As B is the operand, we will send the operand to the postfix form. Can the + be inserted now? In case of A+B*C , we cannot insert + because * has precedence. To perform multiplication, we need the second operand. The first operand of multiplication is B while the second one is C . So at first, we will perform the multiplication before adding result to A . In case of (A+B)*C , the closing parenthesis indicates that + must be performed first. After sending the A and B to postfix perform, we can perform the addition due to the presence of the parenthesis. Then C will be sent to the postfix expression. It will be followed by the multiplication of the C and the result of A + B. The postfix form of this expression is AB+C*. Sometimes, we have two operators and need to decide which to apply first like in this case + and * . In this case, we have to see which operator has higher precedence. Assume that we have a function 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. Now we will try to form an algorithm to convert infix form into postfix form. For this purpose, a pseudo code will be written. We will also write the loops and if conditions. The pseudo code is independent of languages. 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: 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; } First we will declare a stack s . The while loop will continue till the end of input. We Page 5 of 8
  • 6. ecomputernote.com Data Structures Lecture No. 07 ___________________________________________________________________ read the input character and store it in the c . 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. However, in this case, the order of operators may change. If c is the operator, then we will, at first, check that stack is not empty besides identifying the precedence of the operators between the input operator and the operator that is at the top of the stack. In case of the precedence of the operator that is on the stack is higher, we will pop it from the stack and send to the postfix string. For example if we have * on the stack and the new input operator is +. As the precedence of the + operator is less than the * operator, the operands of the multiplication has already been sent to the postfix expression. Now, we should send the * operator to the postfix form. The plus operator (+) will wait. When the while loop sends all such operators to the postfix string, it will push the new operator to the stack that is in c . It has to wait till we get the second operand. Then we will again get the input. On the completion of the input, the while loop will be finished. There may be a case that input may be completed even at the time when there are still some elements on the stack. These are operators. To check this, we have another while loop. This loop checks if the stack is not empty, pops the operator and put it in the postfix string. Let s take a look at a comprehensive example to understand it. In case of the infix expression, A + B * C, we have three columns, one each for input symbol, the postfix expression and the stack respectively. Now let s execute the pseudo code. First of all, we get the A as input. It is an operand so we put it on the postfix string. The next input is the plus operator (+) which will be pushed on the stack. As it is an operator and we need two operands for it. On having a look at the expression, you might have figure out that the second operand for the plus operator is B*C. The next input is the operand B being sent to the postfix expression form. The next thing we get is the input element as * . We know that the precedence of * is higher than that of the +. Let s see how we can do that according to our pseudo code. The prcd(s.top(), op) takes two operands. We will get the top element of the stack i.e. + will be used as first argument. The second argument is the input operator i.e. *. So the function call will be as prcd(+, *) while the function returns false because the precedence of the plus operator is not higher than the multiplication operator. So far, we have only one operand for multiplication i.e. B. As multiplication is also a binary operator, it will also have to wait for the second operand. It has to wait and the waiting room is stack. So we will push it on the stack. Now the top element of the stack is *. The next symbol is C . Being an operand, C will be added to the postfix expression. At this point, our input expression has been completed. Our first while loop executes till the end of input. After the end of the input, the loop will be terminated. Now the control goes to the second while loop which says if there is something on the stack, pop it and add it the postfix expression. In this case, we have * and + on the stack. The * is at the top of the stack. So when we pop, we get * which is at the top of the stack and it will be added to the postfix expression. In the result of second pop, we get the plus operator (+) which is also added to the postfix expression. The stack is empty now. The while loop will be terminated and postfix expression is formed i.e. ABC*+. Symbol postfix stack A A + A + Page 6 of 8
  • 7. ecomputernote.com Data Structures Lecture No. 07 ___________________________________________________________________ B AB + * AB * + C ABC * + ABC* + ABC*+ If we have to convert the infix expression into the postfix form, the job is easily done with the help of stack. The above algorithm can easily be written in C++ or C language, specially, if you already have the stack class. Now you can convert very big infix expressions into postfix expressions. Why we have done this? This can be understood with the help of the example of spreadsheet programming where the value of cell is the evaluation of some expression. The user of the spreadsheets will use the infix expressions as they are used to it. 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. What is the reason to put the parenthesis on the stack? It is due to the fact that as long as the closing parenthesis is not found, the open parenthesis has to wait. It is not a unary or binary operator. Actually, it is a way to show or write precedence. We can handle the parenthesis by adding some extra functionality in our prcd function. When we call prcd(op, ( ), it will return false for all the operators and be pushed on the stack. Also, prcd( ( ,op ) is FALSE which ensures that an operator after ( is pushed on the stack. When a ) is read. All operators up to the first ( must be popped and placed in the postfix string. To achieve this our function prcd( op, ) ) should return true for all the operators. Both the ( and the ) will not go to the postfix expression. In postfix expression, we do not need parenthesis. The precedence of the operators is established in such a way that there is no need of the parenthesis. To include the handling of parenthesis, we have to change our algorithm. We have to change the line s.push(c) to: if( s.empty() || symb != ) ) s.push( c ); else s.pop(); // discard the ( If the input symbol is not ) and the stack is not empty, we will push the operator on the stack. Otherwise, it is advisable to pop the stack and discard the ( . The following functionality has to be added in the prcd function. prcd( ( , op ) = FALSE for any operator prcd( op, ) ) = FALSE for any operator other than ) prcd( op, ) ) = TRUE for any operator other than ( prcd( ) , op ) = error for any operator. Page 7 of 8
  • 8. ecomputernote.com Data Structures Lecture No. 07 ___________________________________________________________________ In the next lecture we will see in detail an example regarding the use of parenthesis. Page 8 of 8