SlideShare a Scribd company logo
1 of 40
EVALUATION OF POSTFIX AND PREFIX
EXPRESSIONS
CONTENTS
1. INTRODUCTION
2. OBJECTIVE
3. INFIX, POSTFIX, EXPRESSIONS
4. EVALUATION OF EXPRESSIONS
4.1 EVALUATION OF INFIX EXPRESSIONS
4.2 EVALUATION OF POSTFIX EXPRESSIONS
4.3 EVALUATION OF PREFIX EXPRESSIONS
5. TOOLS/PLATFORMS, HARDWARE AND SOFTWARE
REQUIREMENTS
6. SOURCE CODE
7. OUTPUT
8. CONCLUSION
9. REFERENCE
1.INTRODUCTION
Data structure provides a means to maintain and manipulate large
amount of data efficiently. Data structures are used in almost every
program or software for manipulation of data. A data structure is a
specialized format for organizing and storing data. General data
structure types include the array, the file, the record, the table, the tree,
and so on. Any data structure is designed to organize data to suit a
specific purpose so that it can be accessed and worked with in
appropriate ways. A data structure is a format of storing, organizing,
transforming and retrieving data in a computer so that it can be used
efficiently. Address book is application created using the features of
data structure.
Data Structure can be defined as the group of data elements which
provides an efficient way of storing and organizing data in the
computer so that it can be used efficiently. Some examples of Data
Structures are arrays, Linked List, Stack, Queue, etc. Data Structures
are widely used in almost every aspect of Computer Science i.e.
operating System, Compiler Design, Artificial intelligence, Graphics
and many more. Data Structures are the main part of many computer
science algorithms as they enable the programmers to handle the data
in an efficient way. It plays a vital role in enhancing the performance
of software or a program as the main function of the software is to store
and retrieve the user's data as fast as possible. Linked list is a linear data
structure which is used to maintain a list in the memory. It can be seen
as the collection of nodes stored at non-contiguous memory locations.
Each node of the list contains a pointer to its adjacent node.
In any programming language, if we want to perform any calculation
or to frame a condition etc., we use a set of symbols to perform the task.
These set of symbols makes an expression. An expression can be
defined as a collection of operators and operands that represents a
specific value. In above definition, operator is a symbol which performs
a particular task like arithmetic operation or logical operation or
conditional operation etc., Operands are the values on which the
operators can perform the task. Here operand can be a direct value or
variable or address of memory location. Based on the operator position,
expressions are divided into three types. They are as:
1. Infix expression
2. Postfix expression
3. Prefix expression
Infix is so common in mathematics, it is much easier to read, and so
is used in most computer languages (e.g. a simple Infix calculator).
However, Prefix is often used for operators that take a single operand
(e.g. negation) and function calls. Although Postfix and Prefix
notations have similar complexity, Postfix is slightly easier to
evaluate in simple circumstances, such as in some calculators (e.g. a
simple Postfix calculator), as the operators really are evaluated
strictly left-to-right.
Infix notation, is inherently limited to functions with two parameters.
This is purely a syntactical issue, due to the fact that the source code
is written linearly in a one-dimensional line. There are only two spots,
the left and the right, to the infix operator. In a similar way, prefix and
postfix notations, are inherently limited to functions with one
parameter. You might think that's not true because we can use
parenthesis to enclose function's arguments. Once you let in a
matching delimiter for function's parameters, you have a syntax for
nesting of functions, and it is no longer the simple prefix, postfix, or
infix notation, you have functional notation.
2.OBJECTIVES
The objective of this case study is to evaluate mathematical expressions
using postfix and prefix notations. In any programming language, if we
want to perform any calculation or to frame a condition etc., we use a
set of symbols to perform the task. These set of symbols makes an
expression. An expression can be defined as a collection of operators
and operands that represents a specific value. Here we use postfix and
prefix notations to perform mathematical expressions.
3.INFIX, POSTFIX AND PREFIX EXPRESSIONS
Infix, Postfix and Prefix notations are three different but equivalent
ways of writing expressions. It is easiest to demonstrate the
differences by looking at examples of operators that take two
operands.
Infix notation: X + Y
Operators are written in-between their operands. This is the usual way
we write expressions. An expression such as A * ( B + C ) / D is
usually taken to mean something like: "First add B and C together,
then multiply the result by A, then divide by D to give the final
answer."
Infix notation needs extra information to make the order of evaluation
of the operators clear: rules built into the language about operator
precedence and associativity, and brackets ( ) to allow users to
override these rules. For example, the usual rules for associativity say
that we perform operations from left to right, so the multiplication by
A is assumed to come before the division by D. Similarly, the usual
rules for precedence say that we perform multiplication and division
before we perform addition and subtraction.
Fig1: example of infix expression
Postfix notation: XY+
It is also known as "Reverse Polish notation. Here operators are
written after their operands. The infix expression given above is
equivalent to A B C + * D /
The order of evaluation of operators is always left-to-right, and
brackets cannot be used to change this order. Because the "+" is to the
left of the "*" in the example above, the addition must be performed
before the multiplication. Operators act on values immediately to the
left of them. For example, the "+" above uses the "B" and "C". We
can add (totally unnecessary) brackets to make this explicit:
( (A (B C +) *) D /)
Thus, the "*" uses the two values immediately preceding: "A", and
the result of the addition. Similarly, the "/" uses the result of the
multiplication and the "D".
Fig2: example for postfix expression
Prefix notation: + X Y
It is also known as "Polish notation”. Here, operators are written
before their operands. The expressions given above are equivalent to
/ * A + B C D
As for Postfix, operators are evaluated left-to-right and brackets are
superfluous. Operators act on the two nearest values on the right. I
have again added brackets to make this clear:
(/ (* A (+ B C) ) D)
Fig3: example for prefix expression
Although Prefix "operators are evaluated left-to-right", they use
values to their right, and if these values themselves involve
computations then this changes the order that the operators have to be
evaluated in. In the example above, although the division is the first
operator on the left, it acts on the result of the multiplication, and so
the multiplication has to happen before the division (and similarly the
addition has to happen before the multiplication).
Because Postfix operators use values to their left, any values
involving computations will already have been calculated as we go
left-to-right, and so the order of evaluation of the operators is not
disrupted in the same way as in Prefix expressions.
In all three versions, the operands occur in the same order, and just
the operators have to be moved to keep the meaning correct. (This is
particularly important for asymmetric operators like subtraction and
division: A - B does not mean the same as B - A; the former is
equivalent to A B - or - A B, the latter to B A - or - B A).
Example 1:
Infix Postfix Prefix Notes
A * B + C / D A B * C D / + + * A B / C D
multiply A and B,
divide C by D,
add the results
A * (B + C) / D A B C + * D / / * A + B C D
add B and C,
multiply by A,
divide by D
A * (B + C / D) A B C D / + * * A + B / C D
divide C by D,
add B,
multiply by A
Example 2:
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 +
4.EVALUATION OF EXPRESSIONS
So far, it is discussed about the ad hoc methods to convert between infix
expressions and the equivalent prefix and postfix expression notations.
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. We know, 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, we 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
subexpression (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 subexpression
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 ie shown in the below figure.
Fig:4
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
(fig:5). The position of the parenthesis pair is actually a clue to the final
position of the enclosed operator.
Fig:5
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 6 shows the conversion to postfix and prefix notations.
Fig:6
4.1 GENERAL INFIX TO POSTFIX CONVERSION
We need to develop an algorithm to convert any infix expression to a
postfix expression. To do this we will look closer at the conversion
process. Consider once again the expression A + B * C. As shown
above, A B C * + is the postfix equivalent. We have already noted that
the operands A, B, and C stay in their relative positions. It is only the
operators that change position. Let’s look again at the operators in the
infix expression. The first operator that appears from left to right is +.
However, in the postfix expression, + is at the end since the next
operator, *, has precedence over addition. The order of the operators in
the original expression is reversed in the resulting postfix expression.
As we process the expression, the operators have to be saved
somewhere since their corresponding right operands are not seen yet.
Also, the order of these saved operators may need to be reversed due to
their precedence. This is the case with the addition and the
multiplication in this example. Since the addition operator comes
before the multiplication operator and has lower precedence, it needs
to appear after the multiplication operator is used. Because of this
reversal of order, it makes sense to consider using a stack to keep the
operators until they are needed. Again, processing this infix expression
from left to right, we see + first. In this case, when we see *, + has
already been placed in the result expression because it has precedence
over * by virtue of the parentheses. We can now start to see how the
conversion algorithm will work. When we see a left parenthesis, we
will save it to denote that another operator of high precedence will be
coming. That operator will need to wait until the corresponding right
parenthesis appears to denote its position. When that right parenthesis
does appear, the operator can be popped from the stack.
As we scan the infix expression from left to right, we will use a stack
to keep the operators. This will provide the reversal that we noted in
the first example. The top of the stack will always be the most recently
saved operator. Whenever we read a new operator, we will need to
consider how that operator compares in precedence with the operators,
if any, already on the stack.
Assume the infix expression is a string of tokens delimited by spaces.
The operator tokens are *, /, +, and -, along with the left and right
parentheses, ( and ). The operand tokens are the single-character
identifiers A, B, C, and so on.
The following steps will produce a string of tokens in postfix order.
1.Create an empty stack called opstack for keeping operators.
Create an empty list for output.
2. Convert the input infix string to a list by using the string method
split.
3.Scan the token list from left to right.
 If the token is an operand, append it to the end of the output
list.
 If the token is a left parenthesis, push it on the opstack.
 If the token is a right parenthesis, pop the opstack until the
corresponding left parenthesis is removed. Append each
operator to the end of the output list.
4.If the token is an operator, *, /, +, or -, push it on the opstack.
However, first remove any operators already on the opstack that
have higher or equal precedence and append them to the output
list.
When the input expression has been completely processed, check the
opstack. Any operators still on the stack can be removed and appended
to the end of the output list.
Figure 7 shows the conversion algorithm working on the expression A
* B + C * D. Note that the first * operator is removed upon seeing the
+ operator. Also, + stays on the stack when the second * occurs, since
multiplication has precedence over addition. At the end of the infix
expression the stack is popped twice, removing both operators and
placing + as the last operator in the postfix expression.
Fig:7
4.2 POSTFIX EVALUATION
A postfix expression can be evaluated using the Stack data structure.
To evaluate a postfix expression using Stack data structure we can use
the following steps.
1. Read all the symbols one by one from left to right in the given
Postfix Expression
2. If the reading symbol is operand, then push it on to the Stack.
3. If the reading symbol is operator (+, - , * , / etc.,), then perform
TWO pop operations and store the two popped operands in two
different variables (operand1 and operand2). Then perform reading
symbol operation using operand1 and operand2 and push result back
on to the Stack.
Infix expression: The expression of the form a op b. When an operator
is in-between every pair of operands.
Postfix expression: The expression of the form a b op. When an
operator is followed for every pair of operands.
The compiler finds it convenient to evaluate an expression in its postfix
form. The virtues of postfix form include elimination of parentheses
which signify priority of evaluation and the elimination of the need to
observe rules of hierarchy, precedence and associativity during
evaluation of the expression.
As Postfix expression is without parenthesis and can be evaluated as
two operands and an operator at a time, this becomes easier for the
compiler and the computer to handle. Evaluation rule of a Postfix
Expression states:
1. While reading the expression from left to right, push the element
in the stack if it is an operand.
2. Pop the two operands from the stack, if the element is an operator
and then evaluate it.
3. Push back the result of the evaluation. Repeat it till the end of the
expression.
The Postfix notation is used to represent algebraic expressions. The
expressions written in postfix form are evaluated faster compared to
infix notation as parenthesis are not required in postfix.
Following is algorithm for evaluation postfix expressions.
1) Create a stack to store operands (or values).
2) Scan the given expression and do following for every scanned
element.
a) If the element is a number, push it into the stack
b) If the element is a operator, pop operands for the operator from
stack. Evaluate the operator and push the result back to the stack
3) When the expression is ended, the number in the stack is the final
answer
Example:
Let the given expression be “2 3 1 * + 9 -“. We scan all elements one
by one.
1) Scan ‘2’, it’s a number, so push it to stack. Stack contains ‘2’
2) Scan ‘3’, again a number, push it to stack, stack now contains ‘2 3’
(from bottom to top)
3) Scan ‘1’, again a number, push it to stack, stack now contains ‘2 3
1’
4) Scan ‘*’, it’s an operator, pop two operands from stack, apply the *
operator on operands, we get 3*1 which results in 3. We push the result
‘3’ to stack. Stack now becomes ‘2 3’.
5) Scan ‘+’, it’s an operator, pop two operands from stack, apply the +
operator on operands, we get 3 + 2 which results in 5. We push the
result ‘5’ to stack. Stack now becomes ‘5’.
6) Scan ‘9’, it’s a number, we push it to the stack. Stack now becomes
‘5 9’.
7) Scan ‘-‘, it’s an operator, pop two operands from stack, apply the –
operator on operands, we get 5 – 9 which results in -4. We push the
result ‘-4’ to stack. Stack now becomes ‘-4’.
8) There are no more elements to scan, we return the top element from
stack (which is the only element left in stack).
4.3 EVALUATION OF PREFIX EXPRESSION
Prefix and Postfix expressions can be evaluated faster than an infix
expression. This is because we don’t need to process any brackets or
follow operator precedence rule. In postfix and prefix expressions
which ever operator comes before will be evaluated first, irrespective
of its priority. Also, there are no brackets in these expressions. As long
as we can guarantee that a valid prefix or postfix expression is used, it
can be evaluated with correctness. We can convert infix to postfix and
can covert infix to prefix. The method is similar to evaluating a postfix
expression.
Algorithm
EVALUATE_POSTFIX(STRING)
Step 1: Put a pointer P at the end of the end
Step 2: If character at P is an operand push it to Stack
Step 3: If the character at P is an operator pop two
elements from the Stack. Operate on these elements
according to the operator, and push the result
back to the Stack
Step 4: Decrement P by 1 and go to Step 2 as long as there
are characters left to be scanned in the expression.
Step 5: The Result is stored at the top of the Stack,
return it
Step 6: End
Example to demonstrate working of the algorithm:
Expression: +9*26
Character | Stack | Explanation
Scanned | (Front to |
| Back) |
-------------------------------------------
6 6 6 is an operand,
push to Stack
2 6 2 2 is an operand,
push to Stack
* 12 (6*2) * is an operator,
pop 6 and 2, multiply
them and push result
to Stack
to Stack
+ 21 (12+9) + is an operator, pop
12 and 9 add them and
push result to Stack
Result: 21
Complexity: The algorithm has linear complexity since we scan the
expression once and perform at most O(N) push and pop operations
which take constant time. It can be also evaluated as follows:
• Accept a prefix string from the user.
say (-*+ABCD), let A=4, B=3, C=2, D=5
i.e. (-*+4325) is the input prefix string.
• Start scanning the string from the right one character at a time.
• If it is an operand, push it in stack.
• If it is an operator, pop opnd1, opnd2 and perform the operation,
specified by the operator. Push the result in the stack.
• Repeat these steps until arr of input prefix strings ends.
This algorithm works fine, if given prefix expressions are evaluated
from left to right without considering precedence of operators, which
will not give correct result in all the cases, where precedence rules of
operators must be followed to get correct result.
For example: Consider the following two prefix notations:
(a) +*435 and (b) *+435
Infix equivalent of a is 4*3+5 and that of b is 4+3*5. Result of a is
12+5=17 and that of b is 7*5=35, which is not the desired result since
the precedence of * operator is higher as compared to +. Result should
be 4+3*5=4+15 = 19 or if the expression is (4+3)*5, then
(7)*5=7*5=35.
Thus precedence of operators and availability of brackets must be kept
in mind for evaluating a given prefix string to result in a correct output.
Therefore, correct result may only be achieved from a prefix string, if
while converting from infix to prefix, due consideration is kept in mind
for precedence of operators and that of brackets.
5.TOOLS/PLATFORM HARDWARE & SOFTWARE
REQUIREMENTS
5.1 HARDWARE REQUIREMENTS
• Processor : Dual core @ 1.60 GHz or more
• RAM : 1 GB or more
• Hard Disk Drive : 160 GB
• Monitor : SVGA Color
• Keyboard : Standard Keyboard
• Mouse : Standard Mouse
5.2 SOFTWARE REQUIREMENTS
• Operating System : Windows XP/07/08/10
• Coding : C++
5.3 C++
C++ is general-purpose object-oriented programming (OOP) language,
developed by Bjarne Stroustrup, and is an extension of the C language.
It is therefore possible to code C++ in a "C style" or "object-oriented
style." In certain scenarios, it can be coded in either way and is thus an
effective example of a hybrid language.
C++ is considered to be an intermediate-level language, as it
encapsulates both high- and low-level language features. Initially, the
language was called "C with classes" as it had all the properties of the
C language with an additional concept of "classes." However, it was
renamed C++ in 1983.It is pronounced "see-plus-plus."
C++ is one of the most popular languages primarily utilized with
system/application software, drivers, client-server applications and
embedded firmware. The main highlight of C++ is a collection of
predefined classes, which are data types that can be instantiated
multiple times. The language also facilitates declaration ofuser-defined
classes. Classes can further accommodate member functions to
implement specific functionality. Multiple objects of a particular class
can be defined to implement the functions within the class. Objects can
be defined as instances created at run time. These classes can also be
inherited by other new classes which take in the public and protected
functionalities by default.
C++ includes several operators such as comparison, arithmetic, bit
manipulation and logical operators. One of the most attractive features
of C++ is that it enables the overloading of certain operators such as
addition.
A few of the essential concepts within the C++ programming language
include polymorphism, virtual and friend functions, templates,
namespaces and pointers.
Data Structure
A Data structure is a Specific way to store and organize data in a
computer's memory so that these data can be used efficiently later. Data
may be arranged in many different ways such as the logical or
mathematical model for a particular organization of data is termed as a
data structure. The variety of a specific data model depends on the two
factors –
• Firstly, it must be loaded enough in structure to reflect the actual
relationships of the data with the real world object.
• Secondly, the formation should be simple enough so that anyone
can efficiently process the data each time it is necessary.
The data structure can be subdivided into major types:
• Linear Data Structure
• Non-linear Data Structure
Linear Data Structure
A data structure is said to be linear if its elements combine to form any
specific order. There are two techniques of representing such linear
structure within memory.
• The first way is to provide the linear relationships among all the
elements represented using linear memory location. These linear
structures are termed as arrays.
• The second technique is to provide the linear relationship among
all the elements represented by using the concept of pointers or links.
These linear structures are termed as linked lists.
The common examples of the linear data structure are:
• Arrays
• Queues
• Stacks
• Linked lists
Non-linear Data Structure
This structure is mostly used for representing data that contains a
hierarchical relationship among various elements.
Examples of Non-Linear Data Structures are listed below:
• Graphs
• the family of trees and
• table of contents
Tree: In this case, data often contain a hierarchical relationship among
various elements. The data structure that reflects this relationship is
termed as a rooted tree graph or a tree.
Graph: In this case, data sometimes hold a relationship between the
pairs of elements which is not necessarily following the hierarchical
structure. Such a data structure is termed as a Graph.
Linked List
• Linked List can be defined as collection of objects called nodes
that are randomly stored in the memory.
• A node contains two fields i.e. data stored at that particular
address and the pointer which contains the address of the next node in
the memory.
• The last node of the list contains pointer to the null.
Uses of Linked List
• The list is not required to be contiguously present in the memory.
The node can reside anywhere in the memory and linked together to
make a list. This achieves optimized utilization of space.
• List size is limited to the memory size and doesn't need to be
declared in advance.
• Empty node cannot be present in the linked list.
• We can store values of primitive types or objects in the singly
linked list.
Singly Linked List
Singly linked list can be defined as the collection of ordered set of
elements. The number of elements may vary according to need of the
program. A node in the singly linked list consists of two parts: data part
and link part. Data part of the node stores actual information that is to
be represented by the node while the link part of the node stores the
address of its immediate successor. One way chain or singly linked list
can be traversed only in one direction. In other words, we can say that
each node contains only next pointer, therefore we cannot traverse the
list in the reverse direction.
Doubly Linked List
Doubly linked list is a complex type of linked list in which a node
contains a pointer to the previous as well as the next node in the
sequence. Therefore, in a doubly linked list, a node consists of three
parts: node data, pointer to the next node in sequence (next pointer) ,
pointer to the previous node (previous pointer). In a singly linked list,
we could traverse only in one direction, because each node contains
address of the next node and it doesn't have any record of its previous
nodes. However, doubly linked list overcome this limitation of singly
linked list. Due to the fact that, each node of the list contains the address
of its previous node, we can find all the details about the previous node
as well by using the previous address stored inside the previous part of
each node.
6.SOURCE CODE
#include<stdio.h>
#include<iostream>
#include<string.h>
#include<queue>
#include<stack>
using namespace std;
char exp[1000];
// Stack type
struct Stack
{
int top;
unsigned capacity;
int *array;
};
// Stack Operations
struct Stack *
createStack (unsigned capacity)
{
struct Stack *stack = (struct Stack *) malloc (sizeof (struct Stack));
if (!stack)
return NULL;
stack->top = -1;
stack->capacity = capacity;
stack->array = (int *) malloc (stack->capacity * sizeof (int));
if (!stack->array)
return NULL;
return stack;
}
int isEmpty (struct Stack *stack)
{
return stack->top == -1;
}
char peek (struct Stack *stack)
{
return stack->array[stack->top];
}
char pop (struct Stack *stack)
{
if (!isEmpty (stack))
return stack->array[stack->top--];
return '$';
}
void push (struct Stack *stack, char op)
{
stack->array[++stack->top] = op;
}
// The main function that returns value of a given postfix expression
int evaluatePostfix (char *exp)
{
// Create a stack of capacity equal to expression size
struct Stack *stack = createStack (strlen (exp));
int i;
// See if stack was created successfully
if (!stack)
return -1;
// Scan all characters one by one
for (i = 0; exp[i]; ++i)
{
// If the scanned character is an operand (number here),
// push it to the stack.
if (isdigit (exp[i]))
push (stack, exp[i] - '0');
// If the scanned character is an operator, pop two
// elements from stack apply the operator
else
{
int val1 = pop (stack);
int val2 = pop (stack);
switch (exp[i])
{
case '+':push (stack, val2 + val1);
break;
case '-':push (stack, val2 - val1);
break;
case '*':push (stack, val2 * val1);
break;
case '/':push (stack, val2 / val1);
break;
}
}
}
return pop (stack);
}
bool isOperand (char c)
{
// If the character is a digit then it must
// be an operand
return isdigit (c);
}
double evaluatePrefix (string exprsn)
{
stack<double> Stack;
for (int j = exprsn.size() - 1; j >= 0; j--) {
// Push operand to Stack
// To convert exprsn[j] to digit subtract
// '0' from exprsn[j].
if (isOperand(exprsn[j]))
Stack.push(exprsn[j] - '0');
else {
// Operator encountered
// Pop two elements from Stack
double o1 = Stack.top();
Stack.pop();
double o2 = Stack.top();
Stack.pop();
// Use switch case to operate on o1
// and o2 and perform o1 O o2.
switch (exprsn[j]) {
case '+':
Stack.push(o1 + o2);
break;
case '-':
Stack.push(o1 - o2);
break;
case '*':
Stack.push(o1 * o2);
break;
case '/':
Stack.push(o1 / o2);
break;
}
}
}
return Stack.top();
}
// Driver program to test above functions
int main ()
{
char option, flag;
do
{
std::cout << "**************** MENU *************" <<
std::endl;
std::cout << "1. Prefix evaluation" << std::endl;
std::cout << "2. Postfix evaluation" << std::endl;
std::cout << "Enter your choice :" << std::endl;
std::cin >> option;
switch (option)
{
case '1':
{
std::cout << "Enter Prefix expression :" << std::endl;
std::cin >> exp;
cout << evaluatePrefix (exp) << endl;
break;
}
case '2':
{
std::cout << "Enter Postfix expression :" << std::endl;
std::cin >> exp;
std::cout << evaluatePostfix (exp) << std::endl;
break;
}
default:std::cout << "Invalid input" << std::endl;
break;
}
std::cout << "Do you want to continue : Y/N ?" << std::endl;
std::cin >> flag;
}
while (flag == 'y' || flag == 'Y');
return 0;
}
7.OUTPUT
8.CONCLUSION
Both pre- and postfix have basically the same advantagesover infix
notation. The most important of these are:
 Much easier to translate to a format that is suitable for direct
execution. Either format can trivially be turned into a tree for
further processing, and postfix can be directly translated to code
if you use a stack-based processor or virtual machine
 Entirely unambiguous. Infix notation requires precedence and
associativity rules to disambiguate it, or addition of extra
parentheses that are not usually considered part of the notation.
As long as the number of arguments to each operator are known
in advance, both prefix and postfix notation are entirely
unambiguous: "* + 5 6 3" is (5+6)*3, and cannot be interpreted
as 5+(6*3), whereas parenthesis is required to achieve with infix.
 Supports operators with different numbers of arguments without
variation of syntax. "unary-op 5" and "ternary-op 1 2 3" both
work fine, but need special syntax to make them work in infix.
9.REFERENCE
BOOKS
 Introduction to Algorithms, Thomas H. Cormen, Charles E.
Leiserson, Ronald L. Rivest, Clifford Stein
 Data Structures by Seymour Lipschutz
 "Data Structures and Algorithm Analysis in C++"by Mark Allen
Weiss
 Data Structures and Algorithms by Alfred V. Aho, Jeffrey D.
Ullman, John E. Hopcroft
 “Data Structures Using C++” by D S Malik
 Łukasiewicz, Jan (1957). Aristotle's Syllogistic from the
Standpoint of Modern Formal Logic. Oxford University Press.
(Reprinted by Garland Publishing in 1987. ISBN 0-8240-6924-2)
 Hamblin, Charles Leonard (1962). "Translation to and from
Polish notation" . Computer Journal. 5 (3): 210–213.
doi:10.1093/comjnl/5.3.210.
WEBSITES
• http://www.cplusplus.com/
• https://www.tutorialspoint.com/cplusplus/index.htm
• https://www.mycplus.com/
• https://www.cprogramming.com/tutorial/c++-tutorial.html
• http://www.learncpp.com/

More Related Content

What's hot (19)

Assignment8
Assignment8Assignment8
Assignment8
 
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
 
Infix to Postfix Conversion Using Stack
Infix to Postfix Conversion Using StackInfix to Postfix Conversion Using Stack
Infix to Postfix Conversion Using Stack
 
Infix to postfix conversion
Infix to postfix conversionInfix to postfix conversion
Infix to postfix conversion
 
Conversion of Infix To Postfix Expressions
Conversion of Infix To Postfix Expressions Conversion of Infix To Postfix Expressions
Conversion of Infix To Postfix Expressions
 
Assignment5
Assignment5Assignment5
Assignment5
 
Infix postfixcoversion
Infix postfixcoversionInfix postfixcoversion
Infix postfixcoversion
 
C programming session3
C programming  session3C programming  session3
C programming session3
 
stack
stackstack
stack
 
Compiler unit 2&3
Compiler unit 2&3Compiler unit 2&3
Compiler unit 2&3
 
C language Unit 2 Slides, UPTU C language
C language Unit 2 Slides, UPTU C languageC language Unit 2 Slides, UPTU C language
C language Unit 2 Slides, UPTU C language
 
Top Down Parsing, Predictive Parsing
Top Down Parsing, Predictive ParsingTop Down Parsing, Predictive Parsing
Top Down Parsing, Predictive Parsing
 
Top down parsing
Top down parsingTop down parsing
Top down parsing
 
Assignment2
Assignment2Assignment2
Assignment2
 
Getting Started with C++
Getting Started with C++Getting Started with C++
Getting Started with C++
 
C language
C languageC language
C language
 
Compiler Design QA
Compiler Design QACompiler Design QA
Compiler Design QA
 
VTU PCD Model Question Paper - Programming in C
VTU PCD Model Question Paper - Programming in CVTU PCD Model Question Paper - Programming in C
VTU PCD Model Question Paper - Programming in C
 
Storage classes in c language
Storage classes in c languageStorage classes in c language
Storage classes in c language
 

Similar to Mycasestudy

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 balochSarmad Baloch
 
Problem solving with algorithm and data structure
Problem solving with algorithm and data structureProblem solving with algorithm and data structure
Problem solving with algorithm and data structureRabia Tariq
 
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 introductionAnanda Kumar HN
 
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
 
C programming session 02
C programming session 02C programming session 02
C programming session 02Dushmanta Nath
 
Programming presentation
Programming presentationProgramming presentation
Programming presentationFiaz Khokhar
 
Ap Power Point Chpt2
Ap Power Point Chpt2Ap Power Point Chpt2
Ap Power Point Chpt2dplunkett
 
C operators
C operatorsC operators
C operatorsGPERI
 
Operator & Expression in c++
Operator & Expression in c++Operator & Expression in c++
Operator & Expression in c++bajiajugal
 
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
 
Computer programming in C. Library functions in C.
Computer programming in C. Library functions in C.Computer programming in C. Library functions in C.
Computer programming in C. Library functions in C.LamiyQurbanlKomptert
 
Polish Notation In Data Structure
Polish Notation In Data StructurePolish Notation In Data Structure
Polish Notation In Data StructureMeghaj Mallick
 
This first assignment will focus on coding in Python, applying kno.docx
This first assignment will focus on coding in Python, applying kno.docxThis first assignment will focus on coding in Python, applying kno.docx
This first assignment will focus on coding in Python, applying kno.docxabhi353063
 
C++ revision tour
C++ revision tourC++ revision tour
C++ revision tourSwarup Boro
 
component of c language.pptx
component of c language.pptxcomponent of c language.pptx
component of c language.pptxAnisZahirahAzman
 

Similar to Mycasestudy (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
 
Problem solving with algorithm and data structure
Problem solving with algorithm and data structureProblem solving with algorithm and data structure
Problem solving with algorithm and data structure
 
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
 
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...
 
C program
C programC program
C program
 
C programming session 02
C programming session 02C programming session 02
C programming session 02
 
Programming presentation
Programming presentationProgramming presentation
Programming presentation
 
Ap Power Point Chpt2
Ap Power Point Chpt2Ap Power Point Chpt2
Ap Power Point Chpt2
 
C operators
C operatorsC operators
C operators
 
C++ revision tour
C++ revision tourC++ revision tour
C++ revision tour
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
STACK Applications in DS
STACK Applications in DSSTACK Applications in DS
STACK Applications in DS
 
Operator & Expression in c++
Operator & Expression in c++Operator & Expression in c++
Operator & Expression in c++
 
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
 
Computer programming in C. Library functions in C.
Computer programming in C. Library functions in C.Computer programming in C. Library functions in C.
Computer programming in C. Library functions in C.
 
Polish Notation In Data Structure
Polish Notation In Data StructurePolish Notation In Data Structure
Polish Notation In Data Structure
 
This first assignment will focus on coding in Python, applying kno.docx
This first assignment will focus on coding in Python, applying kno.docxThis first assignment will focus on coding in Python, applying kno.docx
This first assignment will focus on coding in Python, applying kno.docx
 
C++ revision tour
C++ revision tourC++ revision tour
C++ revision tour
 
Operators
OperatorsOperators
Operators
 
component of c language.pptx
component of c language.pptxcomponent of c language.pptx
component of c language.pptx
 

More from Emmanuel college

More from Emmanuel college (6)

Public voice
Public voicePublic voice
Public voice
 
Divide and conquer
Divide and conquerDivide and conquer
Divide and conquer
 
Inventory Management System
Inventory Management SystemInventory Management System
Inventory Management System
 
Pillcam
PillcamPillcam
Pillcam
 
High performance computing with accelarators
High performance computing with accelaratorsHigh performance computing with accelarators
High performance computing with accelarators
 
Pill camera ppt
Pill camera pptPill camera ppt
Pill camera ppt
 

Recently uploaded

The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...RKavithamani
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 

Recently uploaded (20)

The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 

Mycasestudy

  • 1. EVALUATION OF POSTFIX AND PREFIX EXPRESSIONS
  • 2. CONTENTS 1. INTRODUCTION 2. OBJECTIVE 3. INFIX, POSTFIX, EXPRESSIONS 4. EVALUATION OF EXPRESSIONS 4.1 EVALUATION OF INFIX EXPRESSIONS 4.2 EVALUATION OF POSTFIX EXPRESSIONS 4.3 EVALUATION OF PREFIX EXPRESSIONS 5. TOOLS/PLATFORMS, HARDWARE AND SOFTWARE REQUIREMENTS 6. SOURCE CODE 7. OUTPUT 8. CONCLUSION 9. REFERENCE
  • 3. 1.INTRODUCTION Data structure provides a means to maintain and manipulate large amount of data efficiently. Data structures are used in almost every program or software for manipulation of data. A data structure is a specialized format for organizing and storing data. General data structure types include the array, the file, the record, the table, the tree, and so on. Any data structure is designed to organize data to suit a specific purpose so that it can be accessed and worked with in appropriate ways. A data structure is a format of storing, organizing, transforming and retrieving data in a computer so that it can be used efficiently. Address book is application created using the features of data structure. Data Structure can be defined as the group of data elements which provides an efficient way of storing and organizing data in the computer so that it can be used efficiently. Some examples of Data Structures are arrays, Linked List, Stack, Queue, etc. Data Structures are widely used in almost every aspect of Computer Science i.e. operating System, Compiler Design, Artificial intelligence, Graphics and many more. Data Structures are the main part of many computer science algorithms as they enable the programmers to handle the data in an efficient way. It plays a vital role in enhancing the performance of software or a program as the main function of the software is to store and retrieve the user's data as fast as possible. Linked list is a linear data structure which is used to maintain a list in the memory. It can be seen as the collection of nodes stored at non-contiguous memory locations. Each node of the list contains a pointer to its adjacent node. In any programming language, if we want to perform any calculation or to frame a condition etc., we use a set of symbols to perform the task. These set of symbols makes an expression. An expression can be defined as a collection of operators and operands that represents a specific value. In above definition, operator is a symbol which performs
  • 4. a particular task like arithmetic operation or logical operation or conditional operation etc., Operands are the values on which the operators can perform the task. Here operand can be a direct value or variable or address of memory location. Based on the operator position, expressions are divided into three types. They are as: 1. Infix expression 2. Postfix expression 3. Prefix expression Infix is so common in mathematics, it is much easier to read, and so is used in most computer languages (e.g. a simple Infix calculator). However, Prefix is often used for operators that take a single operand (e.g. negation) and function calls. Although Postfix and Prefix notations have similar complexity, Postfix is slightly easier to evaluate in simple circumstances, such as in some calculators (e.g. a simple Postfix calculator), as the operators really are evaluated strictly left-to-right. Infix notation, is inherently limited to functions with two parameters. This is purely a syntactical issue, due to the fact that the source code is written linearly in a one-dimensional line. There are only two spots, the left and the right, to the infix operator. In a similar way, prefix and postfix notations, are inherently limited to functions with one parameter. You might think that's not true because we can use parenthesis to enclose function's arguments. Once you let in a matching delimiter for function's parameters, you have a syntax for nesting of functions, and it is no longer the simple prefix, postfix, or infix notation, you have functional notation.
  • 5. 2.OBJECTIVES The objective of this case study is to evaluate mathematical expressions using postfix and prefix notations. In any programming language, if we want to perform any calculation or to frame a condition etc., we use a set of symbols to perform the task. These set of symbols makes an expression. An expression can be defined as a collection of operators and operands that represents a specific value. Here we use postfix and prefix notations to perform mathematical expressions.
  • 6. 3.INFIX, POSTFIX AND PREFIX EXPRESSIONS Infix, Postfix and Prefix notations are three different but equivalent ways of writing expressions. It is easiest to demonstrate the differences by looking at examples of operators that take two operands. Infix notation: X + Y Operators are written in-between their operands. This is the usual way we write expressions. An expression such as A * ( B + C ) / D is usually taken to mean something like: "First add B and C together, then multiply the result by A, then divide by D to give the final answer." Infix notation needs extra information to make the order of evaluation of the operators clear: rules built into the language about operator precedence and associativity, and brackets ( ) to allow users to override these rules. For example, the usual rules for associativity say that we perform operations from left to right, so the multiplication by A is assumed to come before the division by D. Similarly, the usual rules for precedence say that we perform multiplication and division before we perform addition and subtraction. Fig1: example of infix expression
  • 7. Postfix notation: XY+ It is also known as "Reverse Polish notation. Here operators are written after their operands. The infix expression given above is equivalent to A B C + * D / The order of evaluation of operators is always left-to-right, and brackets cannot be used to change this order. Because the "+" is to the left of the "*" in the example above, the addition must be performed before the multiplication. Operators act on values immediately to the left of them. For example, the "+" above uses the "B" and "C". We can add (totally unnecessary) brackets to make this explicit: ( (A (B C +) *) D /) Thus, the "*" uses the two values immediately preceding: "A", and the result of the addition. Similarly, the "/" uses the result of the multiplication and the "D". Fig2: example for postfix expression Prefix notation: + X Y It is also known as "Polish notation”. Here, operators are written before their operands. The expressions given above are equivalent to / * A + B C D
  • 8. As for Postfix, operators are evaluated left-to-right and brackets are superfluous. Operators act on the two nearest values on the right. I have again added brackets to make this clear: (/ (* A (+ B C) ) D) Fig3: example for prefix expression Although Prefix "operators are evaluated left-to-right", they use values to their right, and if these values themselves involve computations then this changes the order that the operators have to be evaluated in. In the example above, although the division is the first operator on the left, it acts on the result of the multiplication, and so the multiplication has to happen before the division (and similarly the addition has to happen before the multiplication). Because Postfix operators use values to their left, any values involving computations will already have been calculated as we go left-to-right, and so the order of evaluation of the operators is not disrupted in the same way as in Prefix expressions. In all three versions, the operands occur in the same order, and just the operators have to be moved to keep the meaning correct. (This is particularly important for asymmetric operators like subtraction and division: A - B does not mean the same as B - A; the former is equivalent to A B - or - A B, the latter to B A - or - B A). Example 1:
  • 9. Infix Postfix Prefix Notes A * B + C / D A B * C D / + + * A B / C D multiply A and B, divide C by D, add the results A * (B + C) / D A B C + * D / / * A + B C D add B and C, multiply by A, divide by D A * (B + C / D) A B C D / + * * A + B / C D divide C by D, add B, multiply by A Example 2: 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 +
  • 10. 4.EVALUATION OF EXPRESSIONS So far, it is discussed about the ad hoc methods to convert between infix expressions and the equivalent prefix and postfix expression notations. 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. We know, 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, we 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 subexpression (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 subexpression 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 ie shown in the below figure. Fig:4 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 (fig:5). The position of the parenthesis pair is actually a clue to the final position of the enclosed operator.
  • 11. Fig:5 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 6 shows the conversion to postfix and prefix notations. Fig:6 4.1 GENERAL INFIX TO POSTFIX CONVERSION We need to develop an algorithm to convert any infix expression to a postfix expression. To do this we will look closer at the conversion process. Consider once again the expression A + B * C. As shown above, A B C * + is the postfix equivalent. We have already noted that the operands A, B, and C stay in their relative positions. It is only the operators that change position. Let’s look again at the operators in the infix expression. The first operator that appears from left to right is +. However, in the postfix expression, + is at the end since the next
  • 12. operator, *, has precedence over addition. The order of the operators in the original expression is reversed in the resulting postfix expression. As we process the expression, the operators have to be saved somewhere since their corresponding right operands are not seen yet. Also, the order of these saved operators may need to be reversed due to their precedence. This is the case with the addition and the multiplication in this example. Since the addition operator comes before the multiplication operator and has lower precedence, it needs to appear after the multiplication operator is used. Because of this reversal of order, it makes sense to consider using a stack to keep the operators until they are needed. Again, processing this infix expression from left to right, we see + first. In this case, when we see *, + has already been placed in the result expression because it has precedence over * by virtue of the parentheses. We can now start to see how the conversion algorithm will work. When we see a left parenthesis, we will save it to denote that another operator of high precedence will be coming. That operator will need to wait until the corresponding right parenthesis appears to denote its position. When that right parenthesis does appear, the operator can be popped from the stack. As we scan the infix expression from left to right, we will use a stack to keep the operators. This will provide the reversal that we noted in the first example. The top of the stack will always be the most recently saved operator. Whenever we read a new operator, we will need to consider how that operator compares in precedence with the operators, if any, already on the stack. Assume the infix expression is a string of tokens delimited by spaces. The operator tokens are *, /, +, and -, along with the left and right parentheses, ( and ). The operand tokens are the single-character identifiers A, B, C, and so on. The following steps will produce a string of tokens in postfix order.
  • 13. 1.Create an empty stack called opstack for keeping operators. Create an empty list for output. 2. Convert the input infix string to a list by using the string method split. 3.Scan the token list from left to right.  If the token is an operand, append it to the end of the output list.  If the token is a left parenthesis, push it on the opstack.  If the token is a right parenthesis, pop the opstack until the corresponding left parenthesis is removed. Append each operator to the end of the output list. 4.If the token is an operator, *, /, +, or -, push it on the opstack. However, first remove any operators already on the opstack that have higher or equal precedence and append them to the output list. When the input expression has been completely processed, check the opstack. Any operators still on the stack can be removed and appended to the end of the output list. Figure 7 shows the conversion algorithm working on the expression A * B + C * D. Note that the first * operator is removed upon seeing the + operator. Also, + stays on the stack when the second * occurs, since multiplication has precedence over addition. At the end of the infix expression the stack is popped twice, removing both operators and placing + as the last operator in the postfix expression.
  • 14. Fig:7
  • 15. 4.2 POSTFIX EVALUATION A postfix expression can be evaluated using the Stack data structure. To evaluate a postfix expression using Stack data structure we can use the following steps. 1. Read all the symbols one by one from left to right in the given Postfix Expression 2. If the reading symbol is operand, then push it on to the Stack. 3. If the reading symbol is operator (+, - , * , / etc.,), then perform TWO pop operations and store the two popped operands in two different variables (operand1 and operand2). Then perform reading symbol operation using operand1 and operand2 and push result back on to the Stack. Infix expression: The expression of the form a op b. When an operator is in-between every pair of operands. Postfix expression: The expression of the form a b op. When an operator is followed for every pair of operands. The compiler finds it convenient to evaluate an expression in its postfix form. The virtues of postfix form include elimination of parentheses which signify priority of evaluation and the elimination of the need to observe rules of hierarchy, precedence and associativity during evaluation of the expression. As Postfix expression is without parenthesis and can be evaluated as two operands and an operator at a time, this becomes easier for the
  • 16. compiler and the computer to handle. Evaluation rule of a Postfix Expression states: 1. While reading the expression from left to right, push the element in the stack if it is an operand. 2. Pop the two operands from the stack, if the element is an operator and then evaluate it. 3. Push back the result of the evaluation. Repeat it till the end of the expression. The Postfix notation is used to represent algebraic expressions. The expressions written in postfix form are evaluated faster compared to infix notation as parenthesis are not required in postfix. Following is algorithm for evaluation postfix expressions. 1) Create a stack to store operands (or values). 2) Scan the given expression and do following for every scanned element. a) If the element is a number, push it into the stack b) If the element is a operator, pop operands for the operator from stack. Evaluate the operator and push the result back to the stack 3) When the expression is ended, the number in the stack is the final answer Example: Let the given expression be “2 3 1 * + 9 -“. We scan all elements one by one. 1) Scan ‘2’, it’s a number, so push it to stack. Stack contains ‘2’ 2) Scan ‘3’, again a number, push it to stack, stack now contains ‘2 3’ (from bottom to top) 3) Scan ‘1’, again a number, push it to stack, stack now contains ‘2 3 1’
  • 17. 4) Scan ‘*’, it’s an operator, pop two operands from stack, apply the * operator on operands, we get 3*1 which results in 3. We push the result ‘3’ to stack. Stack now becomes ‘2 3’. 5) Scan ‘+’, it’s an operator, pop two operands from stack, apply the + operator on operands, we get 3 + 2 which results in 5. We push the result ‘5’ to stack. Stack now becomes ‘5’. 6) Scan ‘9’, it’s a number, we push it to the stack. Stack now becomes ‘5 9’. 7) Scan ‘-‘, it’s an operator, pop two operands from stack, apply the – operator on operands, we get 5 – 9 which results in -4. We push the result ‘-4’ to stack. Stack now becomes ‘-4’. 8) There are no more elements to scan, we return the top element from stack (which is the only element left in stack). 4.3 EVALUATION OF PREFIX EXPRESSION Prefix and Postfix expressions can be evaluated faster than an infix expression. This is because we don’t need to process any brackets or follow operator precedence rule. In postfix and prefix expressions which ever operator comes before will be evaluated first, irrespective of its priority. Also, there are no brackets in these expressions. As long as we can guarantee that a valid prefix or postfix expression is used, it can be evaluated with correctness. We can convert infix to postfix and can covert infix to prefix. The method is similar to evaluating a postfix expression. Algorithm EVALUATE_POSTFIX(STRING) Step 1: Put a pointer P at the end of the end
  • 18. Step 2: If character at P is an operand push it to Stack Step 3: If the character at P is an operator pop two elements from the Stack. Operate on these elements according to the operator, and push the result back to the Stack Step 4: Decrement P by 1 and go to Step 2 as long as there are characters left to be scanned in the expression. Step 5: The Result is stored at the top of the Stack, return it Step 6: End Example to demonstrate working of the algorithm: Expression: +9*26 Character | Stack | Explanation Scanned | (Front to | | Back) | ------------------------------------------- 6 6 6 is an operand, push to Stack 2 6 2 2 is an operand, push to Stack * 12 (6*2) * is an operator, pop 6 and 2, multiply them and push result to Stack
  • 19. to Stack + 21 (12+9) + is an operator, pop 12 and 9 add them and push result to Stack Result: 21 Complexity: The algorithm has linear complexity since we scan the expression once and perform at most O(N) push and pop operations which take constant time. It can be also evaluated as follows: • Accept a prefix string from the user. say (-*+ABCD), let A=4, B=3, C=2, D=5 i.e. (-*+4325) is the input prefix string. • Start scanning the string from the right one character at a time. • If it is an operand, push it in stack. • If it is an operator, pop opnd1, opnd2 and perform the operation, specified by the operator. Push the result in the stack. • Repeat these steps until arr of input prefix strings ends.
  • 20. This algorithm works fine, if given prefix expressions are evaluated from left to right without considering precedence of operators, which will not give correct result in all the cases, where precedence rules of operators must be followed to get correct result. For example: Consider the following two prefix notations: (a) +*435 and (b) *+435 Infix equivalent of a is 4*3+5 and that of b is 4+3*5. Result of a is 12+5=17 and that of b is 7*5=35, which is not the desired result since the precedence of * operator is higher as compared to +. Result should be 4+3*5=4+15 = 19 or if the expression is (4+3)*5, then (7)*5=7*5=35. Thus precedence of operators and availability of brackets must be kept in mind for evaluating a given prefix string to result in a correct output. Therefore, correct result may only be achieved from a prefix string, if while converting from infix to prefix, due consideration is kept in mind for precedence of operators and that of brackets.
  • 21.
  • 22.
  • 23. 5.TOOLS/PLATFORM HARDWARE & SOFTWARE REQUIREMENTS 5.1 HARDWARE REQUIREMENTS • Processor : Dual core @ 1.60 GHz or more • RAM : 1 GB or more • Hard Disk Drive : 160 GB • Monitor : SVGA Color • Keyboard : Standard Keyboard • Mouse : Standard Mouse 5.2 SOFTWARE REQUIREMENTS • Operating System : Windows XP/07/08/10 • Coding : C++ 5.3 C++ C++ is general-purpose object-oriented programming (OOP) language, developed by Bjarne Stroustrup, and is an extension of the C language. It is therefore possible to code C++ in a "C style" or "object-oriented style." In certain scenarios, it can be coded in either way and is thus an effective example of a hybrid language. C++ is considered to be an intermediate-level language, as it encapsulates both high- and low-level language features. Initially, the language was called "C with classes" as it had all the properties of the C language with an additional concept of "classes." However, it was renamed C++ in 1983.It is pronounced "see-plus-plus."
  • 24. C++ is one of the most popular languages primarily utilized with system/application software, drivers, client-server applications and embedded firmware. The main highlight of C++ is a collection of predefined classes, which are data types that can be instantiated multiple times. The language also facilitates declaration ofuser-defined classes. Classes can further accommodate member functions to implement specific functionality. Multiple objects of a particular class can be defined to implement the functions within the class. Objects can be defined as instances created at run time. These classes can also be inherited by other new classes which take in the public and protected functionalities by default. C++ includes several operators such as comparison, arithmetic, bit manipulation and logical operators. One of the most attractive features of C++ is that it enables the overloading of certain operators such as addition. A few of the essential concepts within the C++ programming language include polymorphism, virtual and friend functions, templates, namespaces and pointers. Data Structure A Data structure is a Specific way to store and organize data in a computer's memory so that these data can be used efficiently later. Data may be arranged in many different ways such as the logical or mathematical model for a particular organization of data is termed as a data structure. The variety of a specific data model depends on the two factors – • Firstly, it must be loaded enough in structure to reflect the actual relationships of the data with the real world object. • Secondly, the formation should be simple enough so that anyone can efficiently process the data each time it is necessary. The data structure can be subdivided into major types: • Linear Data Structure
  • 25. • Non-linear Data Structure Linear Data Structure A data structure is said to be linear if its elements combine to form any specific order. There are two techniques of representing such linear structure within memory. • The first way is to provide the linear relationships among all the elements represented using linear memory location. These linear structures are termed as arrays. • The second technique is to provide the linear relationship among all the elements represented by using the concept of pointers or links. These linear structures are termed as linked lists. The common examples of the linear data structure are: • Arrays • Queues • Stacks • Linked lists Non-linear Data Structure This structure is mostly used for representing data that contains a hierarchical relationship among various elements. Examples of Non-Linear Data Structures are listed below: • Graphs • the family of trees and • table of contents Tree: In this case, data often contain a hierarchical relationship among various elements. The data structure that reflects this relationship is termed as a rooted tree graph or a tree.
  • 26. Graph: In this case, data sometimes hold a relationship between the pairs of elements which is not necessarily following the hierarchical structure. Such a data structure is termed as a Graph. Linked List • Linked List can be defined as collection of objects called nodes that are randomly stored in the memory. • A node contains two fields i.e. data stored at that particular address and the pointer which contains the address of the next node in the memory. • The last node of the list contains pointer to the null. Uses of Linked List • The list is not required to be contiguously present in the memory. The node can reside anywhere in the memory and linked together to make a list. This achieves optimized utilization of space. • List size is limited to the memory size and doesn't need to be declared in advance. • Empty node cannot be present in the linked list. • We can store values of primitive types or objects in the singly linked list. Singly Linked List Singly linked list can be defined as the collection of ordered set of elements. The number of elements may vary according to need of the program. A node in the singly linked list consists of two parts: data part and link part. Data part of the node stores actual information that is to be represented by the node while the link part of the node stores the address of its immediate successor. One way chain or singly linked list can be traversed only in one direction. In other words, we can say that each node contains only next pointer, therefore we cannot traverse the list in the reverse direction. Doubly Linked List
  • 27. Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as well as the next node in the sequence. Therefore, in a doubly linked list, a node consists of three parts: node data, pointer to the next node in sequence (next pointer) , pointer to the previous node (previous pointer). In a singly linked list, we could traverse only in one direction, because each node contains address of the next node and it doesn't have any record of its previous nodes. However, doubly linked list overcome this limitation of singly linked list. Due to the fact that, each node of the list contains the address of its previous node, we can find all the details about the previous node as well by using the previous address stored inside the previous part of each node. 6.SOURCE CODE #include<stdio.h> #include<iostream> #include<string.h> #include<queue> #include<stack> using namespace std;
  • 28. char exp[1000]; // Stack type struct Stack { int top; unsigned capacity; int *array; }; // Stack Operations struct Stack * createStack (unsigned capacity) { struct Stack *stack = (struct Stack *) malloc (sizeof (struct Stack)); if (!stack) return NULL; stack->top = -1; stack->capacity = capacity; stack->array = (int *) malloc (stack->capacity * sizeof (int)); if (!stack->array) return NULL; return stack; }
  • 29. int isEmpty (struct Stack *stack) { return stack->top == -1; } char peek (struct Stack *stack) { return stack->array[stack->top]; } char pop (struct Stack *stack) { if (!isEmpty (stack)) return stack->array[stack->top--]; return '$'; } void push (struct Stack *stack, char op) { stack->array[++stack->top] = op; } // The main function that returns value of a given postfix expression int evaluatePostfix (char *exp) { // Create a stack of capacity equal to expression size struct Stack *stack = createStack (strlen (exp));
  • 30. int i; // See if stack was created successfully if (!stack) return -1; // Scan all characters one by one for (i = 0; exp[i]; ++i) { // If the scanned character is an operand (number here), // push it to the stack. if (isdigit (exp[i])) push (stack, exp[i] - '0'); // If the scanned character is an operator, pop two // elements from stack apply the operator else { int val1 = pop (stack); int val2 = pop (stack); switch (exp[i]) { case '+':push (stack, val2 + val1); break; case '-':push (stack, val2 - val1); break; case '*':push (stack, val2 * val1); break;
  • 31. case '/':push (stack, val2 / val1); break; } } } return pop (stack); } bool isOperand (char c) { // If the character is a digit then it must // be an operand return isdigit (c); } double evaluatePrefix (string exprsn) { stack<double> Stack; for (int j = exprsn.size() - 1; j >= 0; j--) { // Push operand to Stack // To convert exprsn[j] to digit subtract
  • 32. // '0' from exprsn[j]. if (isOperand(exprsn[j])) Stack.push(exprsn[j] - '0'); else { // Operator encountered // Pop two elements from Stack double o1 = Stack.top(); Stack.pop(); double o2 = Stack.top(); Stack.pop(); // Use switch case to operate on o1 // and o2 and perform o1 O o2. switch (exprsn[j]) { case '+': Stack.push(o1 + o2); break; case '-': Stack.push(o1 - o2); break; case '*': Stack.push(o1 * o2); break;
  • 33. case '/': Stack.push(o1 / o2); break; } } } return Stack.top(); } // Driver program to test above functions int main () { char option, flag; do { std::cout << "**************** MENU *************" << std::endl; std::cout << "1. Prefix evaluation" << std::endl; std::cout << "2. Postfix evaluation" << std::endl; std::cout << "Enter your choice :" << std::endl; std::cin >> option; switch (option) { case '1':
  • 34. { std::cout << "Enter Prefix expression :" << std::endl; std::cin >> exp; cout << evaluatePrefix (exp) << endl; break; } case '2': { std::cout << "Enter Postfix expression :" << std::endl; std::cin >> exp; std::cout << evaluatePostfix (exp) << std::endl; break; } default:std::cout << "Invalid input" << std::endl; break; } std::cout << "Do you want to continue : Y/N ?" << std::endl; std::cin >> flag; } while (flag == 'y' || flag == 'Y'); return 0;
  • 35. }
  • 37.
  • 38.
  • 39. 8.CONCLUSION Both pre- and postfix have basically the same advantagesover infix notation. The most important of these are:  Much easier to translate to a format that is suitable for direct execution. Either format can trivially be turned into a tree for further processing, and postfix can be directly translated to code if you use a stack-based processor or virtual machine  Entirely unambiguous. Infix notation requires precedence and associativity rules to disambiguate it, or addition of extra parentheses that are not usually considered part of the notation. As long as the number of arguments to each operator are known in advance, both prefix and postfix notation are entirely unambiguous: "* + 5 6 3" is (5+6)*3, and cannot be interpreted as 5+(6*3), whereas parenthesis is required to achieve with infix.  Supports operators with different numbers of arguments without variation of syntax. "unary-op 5" and "ternary-op 1 2 3" both work fine, but need special syntax to make them work in infix.
  • 40. 9.REFERENCE BOOKS  Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, Clifford Stein  Data Structures by Seymour Lipschutz  "Data Structures and Algorithm Analysis in C++"by Mark Allen Weiss  Data Structures and Algorithms by Alfred V. Aho, Jeffrey D. Ullman, John E. Hopcroft  “Data Structures Using C++” by D S Malik  Łukasiewicz, Jan (1957). Aristotle's Syllogistic from the Standpoint of Modern Formal Logic. Oxford University Press. (Reprinted by Garland Publishing in 1987. ISBN 0-8240-6924-2)  Hamblin, Charles Leonard (1962). "Translation to and from Polish notation" . Computer Journal. 5 (3): 210–213. doi:10.1093/comjnl/5.3.210. WEBSITES • http://www.cplusplus.com/ • https://www.tutorialspoint.com/cplusplus/index.htm • https://www.mycplus.com/ • https://www.cprogramming.com/tutorial/c++-tutorial.html • http://www.learncpp.com/