SlideShare a Scribd company logo
Problem Solving withalgorithm and Data Structure
Infix, Prefix and Postfix Expressions:
When you write an arithmetic expression such as B * C, the form of the expression provides you
with information so that you can interpret it correctly. In this case we know that the variable B
is being multiplied by the variable C since the multiplication operator * appears between them
in the expression. This type of notation is referred to as infix since the operator is in
between the two operands that it is working on.
Consider another infix example, A + B * C. The operators + and * still appear between the
operands, but there is a problem. Which operands do they work on? Does the + work on A and
B or does the * take B and C? The expression seems ambiguous.
In fact, you have been reading and writing these types of expressions for a long time and they
do not cause you any problem. The reason for this is that you know something about the
operators + and *. Each operator has a precedence level. Operators of higher precedence are
used before operators of lower precedence. The only thing that can change that order is the
presence of parentheses. The precedence order for arithmetic operators places multiplication
and division above addition and subtraction. If two operators of equal precedence appear, then
a left-to-right ordering or associatively is used.
Let’s interpret the troublesome expression A + B * C using operator precedence. B and C are
multiplied first, and A is then added to that result. (A + B) * C would force the addition of A and
B to be done first before the multiplication. In expression A + B + C, by precedence (via
associatively), the leftmost + would be done first.
Although all this may be obvious to you, remember that computers need to know exactly what
operators to perform and in what order. One way to write an expression that guarantees there
will be no confusion with respect to the order of operations is to create what is called a fully
parenthesized expression. This type of expression uses one pair of parentheses for each
operator. The parentheses dictate the order of operations; there is no ambiguity. There is also
no need to remember any precedence rules.
The expression A + B * C + D can be rewritten as ((A + (B * C)) + D) to show that the
multiplication happens first, followed by the leftmost addition. A + B + C + D can be written as
(((A + B) + C) + D) since the addition operations associate from left to right.
There are two other very important expression formats that may not seem obvious to you at
first. Consider the infix expression A + B. What would happen if we moved the operator before
the two operands? The resulting expression would be + A B. Likewise, we could move the
operator to the end. We would get A B +. These look a bit strange.
These changes to the position of the operator with respect to the operands create two new
expression formats, prefix and postfix. Prefix expression notation requires that all operators
precede the two operands that they work on. Postfix, on the other hand, requires that its
operators come after the corresponding operands. A few more examples should help to make
this a bit clearer (see Table 2).
A + B * C would be written as + A * B C in prefix. The multiplication operator comes
immediately before the operands B and C, denoting that * has precedence over +. The addition
operator then appears before the A and the result of the multiplication.
In postfix, the expression would be A B C * +. Again, the order of operations is preserved since
the * appears immediately after the B and the C, denoting that * has precedence, with +
coming after. Although the operators moved and now appear either before or after their
respective operands, the order of the operands stayed exactly the same relative to one
another.
Table 2: Examples of Infix, Prefix, and Postfix
Infix Expression Prefix Expression Postfix Expression
A + B + A B A B +
A + B * C + A * B C A B C * +
Now consider the infix expression (A + B) * C. Recall that in this case, infix requires the parentheses
to force the performance of the addition before the multiplication. However, when A + B was written
in prefix, the addition operator was simply moved before the operands, + A B. The result of this
operation becomes the first operand for the multiplication. The multiplication operator is moved in
front of the entire expression, giving us * + A B C. Likewise, in postfix A B + forces the addition to
happen first. The multiplication can be done to that result and the remaining operand C. The proper
postfix expression is then A B + C *.
Consider these three expressions again (see Table 3). Something very important has happened.
Where did the parentheses go? Why don’t we need them in prefix and postfix? The answer is that
the operators are no longer ambiguous with respect to the operands that they work on. Only infix
notation requires the additional symbols. The order of operations within prefix and postfix
expressions is completely determined by the position of the operator and nothing else. In many
ways, this makes infix the least desirable notation to use.
Table 3: An Expression with Parentheses
Infix Expression Prefix Expression Postfix Expression
Table 3: An Expression with Parentheses
Infix Expression Prefix Expression Postfix Expression
(A + B) * C * + A B C A B + C *
Table 4 shows some additional examples of infix expressions and the equivalent prefix and postfix
expressions. Be sure that you understand how they are equivalent in terms of the order of the
operations being performed.
Table 4: Additional Examples of Infix, Prefix, and Postfix
Infix Expression Prefix Expression Postfix Expression
A + B * C + D + + A * B C D A B C * + D +
(A + B) * (C + D) * + A B + C D A B + C D + *
A * B + C * D + * A B * C D A B * C D * +
A + B + C + D + + + A B C D A B + C + D +
Conversion of InfixExpressionsto Prefixand Postfix
So far, we have used ad hoc methods to convert between infix expressions and the equivalent
prefix and postfix expression notations. As you might expect, there are algorithmic ways to
perform the conversion that allow any expression of any complexity to be correctly
transformed.
The first technique that we will consider uses the notion of a fully parenthesized expression
that was discussed earlier. Recall that A + B * C can be written as (A + (B * C)) to show explicitly
that the multiplication has precedence over the addition. On closer observation, however, you
can see that each parenthesis pair also denotes the beginning and the end of an operand pair
with the corresponding operator in the middle.
Look at the right parenthesis in the sub expression (B * C) above. If we were to move the
multiplication symbol to that position and remove the matching left parenthesis, giving us B C
*, we would in effect have converted the sub expression to postfix notation. If the addition
operator were also moved to its corresponding right parenthesis position and the matching left
parenthesis were removed, the complete postfix expression would result (see Figure 6).
Figure 6: Moving Operators to the Right for Postfix Notation
If we do the same thing but instead of moving the symbol to the position of the right
parenthesis, we move it to the left, we get prefix notation (see Figure 7). The position of the
parenthesis pair is actually a clue to the final position of the enclosed operator.
Figure 7: Moving Operators to the Left for Prefix Notation
So in order to convert an expression, no matter how complex, to either prefix or postfix
notation, fully parenthesize the expression using the order of operations. Then move the
enclosed operator to the position of either the left or the right parenthesis depending on
whether you want prefix or postfix notation.
Here is a more complex expression: (A + B) * C - (D - E) * (F + G). Figure 8 shows the conversion
to postfix and prefix notations.
Figure 8: Converting a Complex Expression to Prefix and Postfix Notations
Ad

More Related Content

What's hot (20)

[ITP - Lecture 05] Datatypes
[ITP - Lecture 05] Datatypes[ITP - Lecture 05] Datatypes
[ITP - Lecture 05] Datatypes
Muhammad Hammad Waseem
 
Cd2 [autosaved]
Cd2 [autosaved]Cd2 [autosaved]
Cd2 [autosaved]
BBDITM LUCKNOW
 
Data types in python part 2
Data types in python part 2Data types in python part 2
Data types in python part 2
Learnbay Datascience
 
Compiler Design QA
Compiler Design QACompiler Design QA
Compiler Design QA
Dr. C.V. Suresh Babu
 
Unit 2 application of stack
Unit 2  application of stack Unit 2  application of stack
Unit 2 application of stack
LavanyaJ28
 
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
STRINGS IN C MRS.SOWMYA JYOTHI.pdfSTRINGS IN C MRS.SOWMYA JYOTHI.pdf
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
SowmyaJyothi3
 
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdf
MANAGING INPUT AND OUTPUT OPERATIONS IN C    MRS.SOWMYA JYOTHI.pdfMANAGING INPUT AND OUTPUT OPERATIONS IN C    MRS.SOWMYA JYOTHI.pdf
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdf
SowmyaJyothi3
 
Getting Started with C++
Getting Started with C++Getting Started with C++
Getting Started with C++
Praveen M Jigajinni
 
Strings
StringsStrings
Strings
Saranya saran
 
07 top-down-parsing
07 top-down-parsing07 top-down-parsing
07 top-down-parsing
Harish Khodke
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
SaranyaK68
 
Constants Variables Datatypes by Mrs. Sowmya Jyothi
Constants Variables Datatypes by Mrs. Sowmya JyothiConstants Variables Datatypes by Mrs. Sowmya Jyothi
Constants Variables Datatypes by Mrs. Sowmya Jyothi
SowmyaJyothi3
 
Top Down Parsing, Predictive Parsing
Top Down Parsing, Predictive ParsingTop Down Parsing, Predictive Parsing
Top Down Parsing, Predictive Parsing
Tanzeela_Hussain
 
C programming part4
C programming part4C programming part4
C programming part4
Keroles karam khalil
 
Csharp4 operators and_casts
Csharp4 operators and_castsCsharp4 operators and_casts
Csharp4 operators and_casts
Abed Bukhari
 
Type Conversion in C++ and C# Arithmetic Expressions
Type Conversion in C++ and C# Arithmetic ExpressionsType Conversion in C++ and C# Arithmetic Expressions
Type Conversion in C++ and C# Arithmetic Expressions
PVS-Studio
 
Lập trình C
Lập trình CLập trình C
Lập trình C
Viet NguyenHoang
 
[ITP - Lecture 15] Arrays & its Types
[ITP - Lecture 15] Arrays & its Types[ITP - Lecture 15] Arrays & its Types
[ITP - Lecture 15] Arrays & its Types
Muhammad Hammad Waseem
 
Top down parsing
Top down parsingTop down parsing
Top down parsing
Prankit Mishra
 
Variable declaration
Variable declarationVariable declaration
Variable declaration
Mark Leo Tarectecan
 
Unit 2 application of stack
Unit 2  application of stack Unit 2  application of stack
Unit 2 application of stack
LavanyaJ28
 
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
STRINGS IN C MRS.SOWMYA JYOTHI.pdfSTRINGS IN C MRS.SOWMYA JYOTHI.pdf
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
SowmyaJyothi3
 
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdf
MANAGING INPUT AND OUTPUT OPERATIONS IN C    MRS.SOWMYA JYOTHI.pdfMANAGING INPUT AND OUTPUT OPERATIONS IN C    MRS.SOWMYA JYOTHI.pdf
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdf
SowmyaJyothi3
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
SaranyaK68
 
Constants Variables Datatypes by Mrs. Sowmya Jyothi
Constants Variables Datatypes by Mrs. Sowmya JyothiConstants Variables Datatypes by Mrs. Sowmya Jyothi
Constants Variables Datatypes by Mrs. Sowmya Jyothi
SowmyaJyothi3
 
Top Down Parsing, Predictive Parsing
Top Down Parsing, Predictive ParsingTop Down Parsing, Predictive Parsing
Top Down Parsing, Predictive Parsing
Tanzeela_Hussain
 
Csharp4 operators and_casts
Csharp4 operators and_castsCsharp4 operators and_casts
Csharp4 operators and_casts
Abed Bukhari
 
Type Conversion in C++ and C# Arithmetic Expressions
Type Conversion in C++ and C# Arithmetic ExpressionsType Conversion in C++ and C# Arithmetic Expressions
Type Conversion in C++ and C# Arithmetic Expressions
PVS-Studio
 

Viewers also liked (16)

Data structures & problem solving unit 1 ppt
Data structures & problem solving unit 1 pptData structures & problem solving unit 1 ppt
Data structures & problem solving unit 1 ppt
aviban
 
All-Reduce and Prefix-Sum Operations
All-Reduce and Prefix-Sum Operations All-Reduce and Prefix-Sum Operations
All-Reduce and Prefix-Sum Operations
Syed Zaid Irshad
 
Amistad & amor
Amistad & amorAmistad & amor
Amistad & amor
miickiizerafiin
 
тема 2.7.внимание
тема 2.7.вниманиетема 2.7.внимание
тема 2.7.внимание
Вера Шевлякова
 
тема 1.2. методы психологии
тема 1.2. методы психологиитема 1.2. методы психологии
тема 1.2. методы психологии
Вера Шевлякова
 
Trabajo de Investigacion
Trabajo de InvestigacionTrabajo de Investigacion
Trabajo de Investigacion
Anthony Pereda
 
fisheYe Snapshot
fisheYe SnapshotfisheYe Snapshot
fisheYe Snapshot
Lara Nina Shabb
 
тема 2.9. эмоции
тема 2.9. эмоциитема 2.9. эмоции
тема 2.9. эмоции
Вера Шевлякова
 
Professional Liability Insurance application for Adult day care
Professional Liability Insurance application for Adult day careProfessional Liability Insurance application for Adult day care
Professional Liability Insurance application for Adult day care
evaj171
 
тема 4.5. характер
тема 4.5. характертема 4.5. характер
тема 4.5. характер
Вера Шевлякова
 
DEEPIKA VERMA (RESUME) (1)
DEEPIKA VERMA (RESUME) (1)DEEPIKA VERMA (RESUME) (1)
DEEPIKA VERMA (RESUME) (1)
deepika verma
 
Problem Solving with Algorithms and Data Structures
Problem Solving with Algorithms and Data StructuresProblem Solving with Algorithms and Data Structures
Problem Solving with Algorithms and Data Structures
Yi-Lung Tsai
 
Top 5 algorithms used in Data Science
Top 5 algorithms used in Data ScienceTop 5 algorithms used in Data Science
Top 5 algorithms used in Data Science
Edureka!
 
john-devkit: 100 типов хешей спустя / john-devkit: 100 Hash Types Later
john-devkit: 100 типов хешей спустя / john-devkit: 100 Hash Types Laterjohn-devkit: 100 типов хешей спустя / john-devkit: 100 Hash Types Later
john-devkit: 100 типов хешей спустя / john-devkit: 100 Hash Types Later
Positive Hack Days
 
Problem Solving with Algorithms and Data Structure - Lists
Problem Solving with Algorithms and Data Structure - ListsProblem Solving with Algorithms and Data Structure - Lists
Problem Solving with Algorithms and Data Structure - Lists
Yi-Lung Tsai
 
Database structure Structures Link list and trees and Recurison complete
Database structure Structures Link list and trees and Recurison complete  Database structure Structures Link list and trees and Recurison complete
Database structure Structures Link list and trees and Recurison complete
Adnan abid
 
Data structures & problem solving unit 1 ppt
Data structures & problem solving unit 1 pptData structures & problem solving unit 1 ppt
Data structures & problem solving unit 1 ppt
aviban
 
All-Reduce and Prefix-Sum Operations
All-Reduce and Prefix-Sum Operations All-Reduce and Prefix-Sum Operations
All-Reduce and Prefix-Sum Operations
Syed Zaid Irshad
 
Trabajo de Investigacion
Trabajo de InvestigacionTrabajo de Investigacion
Trabajo de Investigacion
Anthony Pereda
 
Professional Liability Insurance application for Adult day care
Professional Liability Insurance application for Adult day careProfessional Liability Insurance application for Adult day care
Professional Liability Insurance application for Adult day care
evaj171
 
DEEPIKA VERMA (RESUME) (1)
DEEPIKA VERMA (RESUME) (1)DEEPIKA VERMA (RESUME) (1)
DEEPIKA VERMA (RESUME) (1)
deepika verma
 
Problem Solving with Algorithms and Data Structures
Problem Solving with Algorithms and Data StructuresProblem Solving with Algorithms and Data Structures
Problem Solving with Algorithms and Data Structures
Yi-Lung Tsai
 
Top 5 algorithms used in Data Science
Top 5 algorithms used in Data ScienceTop 5 algorithms used in Data Science
Top 5 algorithms used in Data Science
Edureka!
 
john-devkit: 100 типов хешей спустя / john-devkit: 100 Hash Types Later
john-devkit: 100 типов хешей спустя / john-devkit: 100 Hash Types Laterjohn-devkit: 100 типов хешей спустя / john-devkit: 100 Hash Types Later
john-devkit: 100 типов хешей спустя / john-devkit: 100 Hash Types Later
Positive Hack Days
 
Problem Solving with Algorithms and Data Structure - Lists
Problem Solving with Algorithms and Data Structure - ListsProblem Solving with Algorithms and Data Structure - Lists
Problem Solving with Algorithms and Data Structure - Lists
Yi-Lung Tsai
 
Database structure Structures Link list and trees and Recurison complete
Database structure Structures Link list and trees and Recurison complete  Database structure Structures Link list and trees and Recurison complete
Database structure Structures Link list and trees and Recurison complete
Adnan abid
 
Ad

Similar to Problem solving with algorithm and data structure (20)

Conversion of in fix pre fix,infix by sarmad baloch
Conversion of in fix pre fix,infix by sarmad balochConversion of in fix pre fix,infix by sarmad baloch
Conversion of in fix pre fix,infix by sarmad baloch
Sarmad Baloch
 
Polish Notation In Data Structure
Polish Notation In Data StructurePolish Notation In Data Structure
Polish Notation In Data Structure
Meghaj Mallick
 
Applications of Stack (Data Structure).pdf
Applications of Stack (Data Structure).pdfApplications of Stack (Data Structure).pdf
Applications of Stack (Data Structure).pdf
parwarsmko98
 
Prefix and PostFIx presentation for DSA .pptx
Prefix and PostFIx presentation for DSA .pptxPrefix and PostFIx presentation for DSA .pptx
Prefix and PostFIx presentation for DSA .pptx
rtiwary190801
 
computer notes - Data Structures - 6
computer notes - Data Structures - 6computer notes - Data Structures - 6
computer notes - Data Structures - 6
ecomputernotes
 
Data structures (Infix, Prefix and Postfix notations).pptx
Data structures (Infix, Prefix and Postfix notations).pptxData structures (Infix, Prefix and Postfix notations).pptx
Data structures (Infix, Prefix and Postfix notations).pptx
itzsomeone50
 
Lecture6
Lecture6Lecture6
Lecture6
Muhammad Zubair
 
Associativity of operators
Associativity of operatorsAssociativity of operators
Associativity of operators
Ajay Chimmani
 
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
ecomputernotes
 
2.2 stack applications Infix to Postfix & Evaluation of Post Fix
2.2 stack applications Infix to Postfix & Evaluation of Post Fix2.2 stack applications Infix to Postfix & Evaluation of Post Fix
2.2 stack applications Infix to Postfix & Evaluation of Post Fix
P. Subathra Kishore, KAMARAJ College of Engineering and Technology, Madurai
 
Compiler Design - Ambiguous grammar, LMD & RMD, Infix & Postfix, Implementati...
Compiler Design - Ambiguous grammar, LMD & RMD, Infix & Postfix, Implementati...Compiler Design - Ambiguous grammar, LMD & RMD, Infix & Postfix, Implementati...
Compiler Design - Ambiguous grammar, LMD & RMD, Infix & Postfix, Implementati...
Saikrishna Tanguturu
 
STACK APPLICATIONS: INFOX TO POSTFIX CONVERSION AND EVALUATION OF POSTFIX EXP...
STACK APPLICATIONS: INFOX TO POSTFIX CONVERSION AND EVALUATION OF POSTFIX EXP...STACK APPLICATIONS: INFOX TO POSTFIX CONVERSION AND EVALUATION OF POSTFIX EXP...
STACK APPLICATIONS: INFOX TO POSTFIX CONVERSION AND EVALUATION OF POSTFIX EXP...
devismileyrockz
 
Data structures
Data structures Data structures
Data structures
Rokonuzzaman Rony
 
C programming operators
C programming operatorsC programming operators
C programming operators
Suneel Dogra
 
C++ revision tour
C++ revision tourC++ revision tour
C++ revision tour
Swarup Kumar Boro
 
Oop with c++ notes unit 01 introduction
Oop with c++ notes   unit 01 introductionOop with c++ notes   unit 01 introduction
Oop with c++ notes unit 01 introduction
Ananda Kumar HN
 
Data Structures And Algorithms(stacks queues)
Data Structures And Algorithms(stacks queues)Data Structures And Algorithms(stacks queues)
Data Structures And Algorithms(stacks queues)
lahariit406
 
Lec5-Stack-bukc-28022024-112316am (1) .pptx
Lec5-Stack-bukc-28022024-112316am (1) .pptxLec5-Stack-bukc-28022024-112316am (1) .pptx
Lec5-Stack-bukc-28022024-112316am (1) .pptx
haaamin01
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
Srikanth Mylapalli
 
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
Muhammad Hammad Waseem
 
Conversion of in fix pre fix,infix by sarmad baloch
Conversion of in fix pre fix,infix by sarmad balochConversion of in fix pre fix,infix by sarmad baloch
Conversion of in fix pre fix,infix by sarmad baloch
Sarmad Baloch
 
Polish Notation In Data Structure
Polish Notation In Data StructurePolish Notation In Data Structure
Polish Notation In Data Structure
Meghaj Mallick
 
Applications of Stack (Data Structure).pdf
Applications of Stack (Data Structure).pdfApplications of Stack (Data Structure).pdf
Applications of Stack (Data Structure).pdf
parwarsmko98
 
Prefix and PostFIx presentation for DSA .pptx
Prefix and PostFIx presentation for DSA .pptxPrefix and PostFIx presentation for DSA .pptx
Prefix and PostFIx presentation for DSA .pptx
rtiwary190801
 
computer notes - Data Structures - 6
computer notes - Data Structures - 6computer notes - Data Structures - 6
computer notes - Data Structures - 6
ecomputernotes
 
Data structures (Infix, Prefix and Postfix notations).pptx
Data structures (Infix, Prefix and Postfix notations).pptxData structures (Infix, Prefix and Postfix notations).pptx
Data structures (Infix, Prefix and Postfix notations).pptx
itzsomeone50
 
Associativity of operators
Associativity of operatorsAssociativity of operators
Associativity of operators
Ajay Chimmani
 
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
ecomputernotes
 
Compiler Design - Ambiguous grammar, LMD & RMD, Infix & Postfix, Implementati...
Compiler Design - Ambiguous grammar, LMD & RMD, Infix & Postfix, Implementati...Compiler Design - Ambiguous grammar, LMD & RMD, Infix & Postfix, Implementati...
Compiler Design - Ambiguous grammar, LMD & RMD, Infix & Postfix, Implementati...
Saikrishna Tanguturu
 
STACK APPLICATIONS: INFOX TO POSTFIX CONVERSION AND EVALUATION OF POSTFIX EXP...
STACK APPLICATIONS: INFOX TO POSTFIX CONVERSION AND EVALUATION OF POSTFIX EXP...STACK APPLICATIONS: INFOX TO POSTFIX CONVERSION AND EVALUATION OF POSTFIX EXP...
STACK APPLICATIONS: INFOX TO POSTFIX CONVERSION AND EVALUATION OF POSTFIX EXP...
devismileyrockz
 
C programming operators
C programming operatorsC programming operators
C programming operators
Suneel Dogra
 
Oop with c++ notes unit 01 introduction
Oop with c++ notes   unit 01 introductionOop with c++ notes   unit 01 introduction
Oop with c++ notes unit 01 introduction
Ananda Kumar HN
 
Data Structures And Algorithms(stacks queues)
Data Structures And Algorithms(stacks queues)Data Structures And Algorithms(stacks queues)
Data Structures And Algorithms(stacks queues)
lahariit406
 
Lec5-Stack-bukc-28022024-112316am (1) .pptx
Lec5-Stack-bukc-28022024-112316am (1) .pptxLec5-Stack-bukc-28022024-112316am (1) .pptx
Lec5-Stack-bukc-28022024-112316am (1) .pptx
haaamin01
 
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
Muhammad Hammad Waseem
 
Ad

Recently uploaded (20)

Molecular methods diagnostic and monitoring of infection - Repaired.pptx
Molecular methods diagnostic and monitoring of infection  -  Repaired.pptxMolecular methods diagnostic and monitoring of infection  -  Repaired.pptx
Molecular methods diagnostic and monitoring of infection - Repaired.pptx
7tzn7x5kky
 
computer organization and assembly language.docx
computer organization and assembly language.docxcomputer organization and assembly language.docx
computer organization and assembly language.docx
alisoftwareengineer1
 
VKS-Python Basics for Beginners and advance.pptx
VKS-Python Basics for Beginners and advance.pptxVKS-Python Basics for Beginners and advance.pptx
VKS-Python Basics for Beginners and advance.pptx
Vinod Srivastava
 
chapter3 Central Tendency statistics.ppt
chapter3 Central Tendency statistics.pptchapter3 Central Tendency statistics.ppt
chapter3 Central Tendency statistics.ppt
justinebandajbn
 
DPR_Expert_Recruitment_notice_Revised.pdf
DPR_Expert_Recruitment_notice_Revised.pdfDPR_Expert_Recruitment_notice_Revised.pdf
DPR_Expert_Recruitment_notice_Revised.pdf
inmishra17121973
 
Data Analytics Overview and its applications
Data Analytics Overview and its applicationsData Analytics Overview and its applications
Data Analytics Overview and its applications
JanmejayaMishra7
 
FPET_Implementation_2_MA to 360 Engage Direct.pptx
FPET_Implementation_2_MA to 360 Engage Direct.pptxFPET_Implementation_2_MA to 360 Engage Direct.pptx
FPET_Implementation_2_MA to 360 Engage Direct.pptx
ssuser4ef83d
 
C++_OOPs_DSA1_Presentation_Template.pptx
C++_OOPs_DSA1_Presentation_Template.pptxC++_OOPs_DSA1_Presentation_Template.pptx
C++_OOPs_DSA1_Presentation_Template.pptx
aquibnoor22079
 
Deloitte Analytics - Applying Process Mining in an audit context
Deloitte Analytics - Applying Process Mining in an audit contextDeloitte Analytics - Applying Process Mining in an audit context
Deloitte Analytics - Applying Process Mining in an audit context
Process mining Evangelist
 
Medical Dataset including visualizations
Medical Dataset including visualizationsMedical Dataset including visualizations
Medical Dataset including visualizations
vishrut8750588758
 
04302025_CCC TUG_DataVista: The Design Story
04302025_CCC TUG_DataVista: The Design Story04302025_CCC TUG_DataVista: The Design Story
04302025_CCC TUG_DataVista: The Design Story
ccctableauusergroup
 
Secure_File_Storage_Hybrid_Cryptography.pptx..
Secure_File_Storage_Hybrid_Cryptography.pptx..Secure_File_Storage_Hybrid_Cryptography.pptx..
Secure_File_Storage_Hybrid_Cryptography.pptx..
yuvarajreddy2002
 
Ch3MCT24.pptx measure of central tendency
Ch3MCT24.pptx measure of central tendencyCh3MCT24.pptx measure of central tendency
Ch3MCT24.pptx measure of central tendency
ayeleasefa2
 
Perencanaan Pengendalian-Proyek-Konstruksi-MS-PROJECT.pptx
Perencanaan Pengendalian-Proyek-Konstruksi-MS-PROJECT.pptxPerencanaan Pengendalian-Proyek-Konstruksi-MS-PROJECT.pptx
Perencanaan Pengendalian-Proyek-Konstruksi-MS-PROJECT.pptx
PareaRusan
 
Calories_Prediction_using_Linear_Regression.pptx
Calories_Prediction_using_Linear_Regression.pptxCalories_Prediction_using_Linear_Regression.pptx
Calories_Prediction_using_Linear_Regression.pptx
TijiLMAHESHWARI
 
Classification_in_Machinee_Learning.pptx
Classification_in_Machinee_Learning.pptxClassification_in_Machinee_Learning.pptx
Classification_in_Machinee_Learning.pptx
wencyjorda88
 
GenAI for Quant Analytics: survey-analytics.ai
GenAI for Quant Analytics: survey-analytics.aiGenAI for Quant Analytics: survey-analytics.ai
GenAI for Quant Analytics: survey-analytics.ai
Inspirient
 
183409-christina-rossetti.pdfdsfsdasggsag
183409-christina-rossetti.pdfdsfsdasggsag183409-christina-rossetti.pdfdsfsdasggsag
183409-christina-rossetti.pdfdsfsdasggsag
fardin123rahman07
 
Just-In-Timeasdfffffffghhhhhhhhhhj Systems.ppt
Just-In-Timeasdfffffffghhhhhhhhhhj Systems.pptJust-In-Timeasdfffffffghhhhhhhhhhj Systems.ppt
Just-In-Timeasdfffffffghhhhhhhhhhj Systems.ppt
ssuser5f8f49
 
LLM finetuning for multiple choice google bert
LLM finetuning for multiple choice google bertLLM finetuning for multiple choice google bert
LLM finetuning for multiple choice google bert
ChadapornK
 
Molecular methods diagnostic and monitoring of infection - Repaired.pptx
Molecular methods diagnostic and monitoring of infection  -  Repaired.pptxMolecular methods diagnostic and monitoring of infection  -  Repaired.pptx
Molecular methods diagnostic and monitoring of infection - Repaired.pptx
7tzn7x5kky
 
computer organization and assembly language.docx
computer organization and assembly language.docxcomputer organization and assembly language.docx
computer organization and assembly language.docx
alisoftwareengineer1
 
VKS-Python Basics for Beginners and advance.pptx
VKS-Python Basics for Beginners and advance.pptxVKS-Python Basics for Beginners and advance.pptx
VKS-Python Basics for Beginners and advance.pptx
Vinod Srivastava
 
chapter3 Central Tendency statistics.ppt
chapter3 Central Tendency statistics.pptchapter3 Central Tendency statistics.ppt
chapter3 Central Tendency statistics.ppt
justinebandajbn
 
DPR_Expert_Recruitment_notice_Revised.pdf
DPR_Expert_Recruitment_notice_Revised.pdfDPR_Expert_Recruitment_notice_Revised.pdf
DPR_Expert_Recruitment_notice_Revised.pdf
inmishra17121973
 
Data Analytics Overview and its applications
Data Analytics Overview and its applicationsData Analytics Overview and its applications
Data Analytics Overview and its applications
JanmejayaMishra7
 
FPET_Implementation_2_MA to 360 Engage Direct.pptx
FPET_Implementation_2_MA to 360 Engage Direct.pptxFPET_Implementation_2_MA to 360 Engage Direct.pptx
FPET_Implementation_2_MA to 360 Engage Direct.pptx
ssuser4ef83d
 
C++_OOPs_DSA1_Presentation_Template.pptx
C++_OOPs_DSA1_Presentation_Template.pptxC++_OOPs_DSA1_Presentation_Template.pptx
C++_OOPs_DSA1_Presentation_Template.pptx
aquibnoor22079
 
Deloitte Analytics - Applying Process Mining in an audit context
Deloitte Analytics - Applying Process Mining in an audit contextDeloitte Analytics - Applying Process Mining in an audit context
Deloitte Analytics - Applying Process Mining in an audit context
Process mining Evangelist
 
Medical Dataset including visualizations
Medical Dataset including visualizationsMedical Dataset including visualizations
Medical Dataset including visualizations
vishrut8750588758
 
04302025_CCC TUG_DataVista: The Design Story
04302025_CCC TUG_DataVista: The Design Story04302025_CCC TUG_DataVista: The Design Story
04302025_CCC TUG_DataVista: The Design Story
ccctableauusergroup
 
Secure_File_Storage_Hybrid_Cryptography.pptx..
Secure_File_Storage_Hybrid_Cryptography.pptx..Secure_File_Storage_Hybrid_Cryptography.pptx..
Secure_File_Storage_Hybrid_Cryptography.pptx..
yuvarajreddy2002
 
Ch3MCT24.pptx measure of central tendency
Ch3MCT24.pptx measure of central tendencyCh3MCT24.pptx measure of central tendency
Ch3MCT24.pptx measure of central tendency
ayeleasefa2
 
Perencanaan Pengendalian-Proyek-Konstruksi-MS-PROJECT.pptx
Perencanaan Pengendalian-Proyek-Konstruksi-MS-PROJECT.pptxPerencanaan Pengendalian-Proyek-Konstruksi-MS-PROJECT.pptx
Perencanaan Pengendalian-Proyek-Konstruksi-MS-PROJECT.pptx
PareaRusan
 
Calories_Prediction_using_Linear_Regression.pptx
Calories_Prediction_using_Linear_Regression.pptxCalories_Prediction_using_Linear_Regression.pptx
Calories_Prediction_using_Linear_Regression.pptx
TijiLMAHESHWARI
 
Classification_in_Machinee_Learning.pptx
Classification_in_Machinee_Learning.pptxClassification_in_Machinee_Learning.pptx
Classification_in_Machinee_Learning.pptx
wencyjorda88
 
GenAI for Quant Analytics: survey-analytics.ai
GenAI for Quant Analytics: survey-analytics.aiGenAI for Quant Analytics: survey-analytics.ai
GenAI for Quant Analytics: survey-analytics.ai
Inspirient
 
183409-christina-rossetti.pdfdsfsdasggsag
183409-christina-rossetti.pdfdsfsdasggsag183409-christina-rossetti.pdfdsfsdasggsag
183409-christina-rossetti.pdfdsfsdasggsag
fardin123rahman07
 
Just-In-Timeasdfffffffghhhhhhhhhhj Systems.ppt
Just-In-Timeasdfffffffghhhhhhhhhhj Systems.pptJust-In-Timeasdfffffffghhhhhhhhhhj Systems.ppt
Just-In-Timeasdfffffffghhhhhhhhhhj Systems.ppt
ssuser5f8f49
 
LLM finetuning for multiple choice google bert
LLM finetuning for multiple choice google bertLLM finetuning for multiple choice google bert
LLM finetuning for multiple choice google bert
ChadapornK
 

Problem solving with algorithm and data structure

  • 1. Problem Solving withalgorithm and Data Structure Infix, Prefix and Postfix Expressions: When you write an arithmetic expression such as B * C, the form of the expression provides you with information so that you can interpret it correctly. In this case we know that the variable B is being multiplied by the variable C since the multiplication operator * appears between them in the expression. This type of notation is referred to as infix since the operator is in between the two operands that it is working on. Consider another infix example, A + B * C. The operators + and * still appear between the operands, but there is a problem. Which operands do they work on? Does the + work on A and B or does the * take B and C? The expression seems ambiguous. In fact, you have been reading and writing these types of expressions for a long time and they do not cause you any problem. The reason for this is that you know something about the operators + and *. Each operator has a precedence level. Operators of higher precedence are used before operators of lower precedence. The only thing that can change that order is the presence of parentheses. The precedence order for arithmetic operators places multiplication and division above addition and subtraction. If two operators of equal precedence appear, then a left-to-right ordering or associatively is used. Let’s interpret the troublesome expression A + B * C using operator precedence. B and C are multiplied first, and A is then added to that result. (A + B) * C would force the addition of A and B to be done first before the multiplication. In expression A + B + C, by precedence (via associatively), the leftmost + would be done first. Although all this may be obvious to you, remember that computers need to know exactly what operators to perform and in what order. One way to write an expression that guarantees there will be no confusion with respect to the order of operations is to create what is called a fully parenthesized expression. This type of expression uses one pair of parentheses for each operator. The parentheses dictate the order of operations; there is no ambiguity. There is also no need to remember any precedence rules. The expression A + B * C + D can be rewritten as ((A + (B * C)) + D) to show that the multiplication happens first, followed by the leftmost addition. A + B + C + D can be written as (((A + B) + C) + D) since the addition operations associate from left to right. There are two other very important expression formats that may not seem obvious to you at first. Consider the infix expression A + B. What would happen if we moved the operator before the two operands? The resulting expression would be + A B. Likewise, we could move the operator to the end. We would get A B +. These look a bit strange. These changes to the position of the operator with respect to the operands create two new expression formats, prefix and postfix. Prefix expression notation requires that all operators precede the two operands that they work on. Postfix, on the other hand, requires that its
  • 2. operators come after the corresponding operands. A few more examples should help to make this a bit clearer (see Table 2). A + B * C would be written as + A * B C in prefix. The multiplication operator comes immediately before the operands B and C, denoting that * has precedence over +. The addition operator then appears before the A and the result of the multiplication. In postfix, the expression would be A B C * +. Again, the order of operations is preserved since the * appears immediately after the B and the C, denoting that * has precedence, with + coming after. Although the operators moved and now appear either before or after their respective operands, the order of the operands stayed exactly the same relative to one another. Table 2: Examples of Infix, Prefix, and Postfix Infix Expression Prefix Expression Postfix Expression A + B + A B A B + A + B * C + A * B C A B C * + Now consider the infix expression (A + B) * C. Recall that in this case, infix requires the parentheses to force the performance of the addition before the multiplication. However, when A + B was written in prefix, the addition operator was simply moved before the operands, + A B. The result of this operation becomes the first operand for the multiplication. The multiplication operator is moved in front of the entire expression, giving us * + A B C. Likewise, in postfix A B + forces the addition to happen first. The multiplication can be done to that result and the remaining operand C. The proper postfix expression is then A B + C *. Consider these three expressions again (see Table 3). Something very important has happened. Where did the parentheses go? Why don’t we need them in prefix and postfix? The answer is that the operators are no longer ambiguous with respect to the operands that they work on. Only infix notation requires the additional symbols. The order of operations within prefix and postfix expressions is completely determined by the position of the operator and nothing else. In many ways, this makes infix the least desirable notation to use. Table 3: An Expression with Parentheses Infix Expression Prefix Expression Postfix Expression
  • 3. Table 3: An Expression with Parentheses Infix Expression Prefix Expression Postfix Expression (A + B) * C * + A B C A B + C * Table 4 shows some additional examples of infix expressions and the equivalent prefix and postfix expressions. Be sure that you understand how they are equivalent in terms of the order of the operations being performed. Table 4: Additional Examples of Infix, Prefix, and Postfix Infix Expression Prefix Expression Postfix Expression A + B * C + D + + A * B C D A B C * + D + (A + B) * (C + D) * + A B + C D A B + C D + * A * B + C * D + * A B * C D A B * C D * + A + B + C + D + + + A B C D A B + C + D + Conversion of InfixExpressionsto Prefixand Postfix So far, we have used ad hoc methods to convert between infix expressions and the equivalent prefix and postfix expression notations. As you might expect, there are algorithmic ways to perform the conversion that allow any expression of any complexity to be correctly transformed. The first technique that we will consider uses the notion of a fully parenthesized expression that was discussed earlier. Recall that A + B * C can be written as (A + (B * C)) to show explicitly that the multiplication has precedence over the addition. On closer observation, however, you can see that each parenthesis pair also denotes the beginning and the end of an operand pair with the corresponding operator in the middle. Look at the right parenthesis in the sub expression (B * C) above. If we were to move the multiplication symbol to that position and remove the matching left parenthesis, giving us B C
  • 4. *, we would in effect have converted the sub expression to postfix notation. If the addition operator were also moved to its corresponding right parenthesis position and the matching left parenthesis were removed, the complete postfix expression would result (see Figure 6). Figure 6: Moving Operators to the Right for Postfix Notation If we do the same thing but instead of moving the symbol to the position of the right parenthesis, we move it to the left, we get prefix notation (see Figure 7). The position of the parenthesis pair is actually a clue to the final position of the enclosed operator. Figure 7: Moving Operators to the Left for Prefix Notation So in order to convert an expression, no matter how complex, to either prefix or postfix notation, fully parenthesize the expression using the order of operations. Then move the enclosed operator to the position of either the left or the right parenthesis depending on whether you want prefix or postfix notation. Here is a more complex expression: (A + B) * C - (D - E) * (F + G). Figure 8 shows the conversion to postfix and prefix notations. Figure 8: Converting a Complex Expression to Prefix and Postfix Notations