SlideShare a Scribd company logo
1 of 11
Download to read offline
Write a program that converts an infix expression into an equivalent postfix expression. The
rules to convert an infix expression into an equivalent postfix expression are as follows (C++):
Initialize pfx to an empty expression and also initialize the stack.
Get the next symbol, sym, from infx.
If sym is an operand, append sym to pfx.
If sym is (, push sym into the stack.
If sym is ), pop and append all of the symbols from the stack until the most recent left
parentheses. Pop and discard the left parentheses.
If sym is an operator:
Pop and append all of the operators from the stack to pfx that are above the most recent left
parentheses and have precedence greater than or equal to sym.
Push sym onto the stack.
After processing infx, some operators might be left in the stack. Pop and append to pfx
everything from the stack.
In this program, you will consider the following (binary) arithmetic operators: +, -, *, and /.
You may assume that the expressions you will process are error free. Design a class that stores
the infix and postfix strings. The class must include the following operations:
getInfix: Stores the infix expression.
showInfix: Outputs the infix expression.
showPostfix: Outputs the postfix expression.
convertToPostfix: Converts the infix expression into a postfix expression. The resulting postfix
expression is stored in pfx.
precedence: Determines the precedence between two operators. If the first operator is of higher
or equal precedence than the second operator, it returns the value true; otherwise, it returns the
value false.
A + B - C;
(A + B ) * C;
(A + B) * (C - D);
A + ((B + C) * (E - F) - G) / (H - I);
A + B * (C + D ) - E / F * G + H;
Infix Expression: A+B-C;
Postfix Expression: AB+C-
Infix Expression: (A+B)*C;
Postfix Expression: AB+C*
Infix Expression: (A+B)*(C-D);
Postfix Expression: AB+CD-*
Infix Expression: A+((B+C)*(E-F)-G)/(H-I);
Postfix Expression: ABC+EF-*G-HI-/+
Infix Expression: A+B*(C+D)-E/F*G+H;
Postfix Expression: ABCD+*+EF/G*-H+
Turn in:
A UML diagram for your class.
The header file for your class.
The implementation file for your class.
The source code for your test program. (C++)
(Below already done code.)
//Header file: myStack.h
#ifndef H_StackType
#define H_StackType
#include
#include
#include "stackADT.h"
using namespace std;
template
class stackType: public stackADT
{
public:
const stackType& operator=(const stackType&);
//Overload the assignment operator.
void initializeStack();
//Function to initialize the stack to an empty state.
//Postcondition: stackTop = 0
bool isEmptyStack() const;
//Function to determine whether the stack is empty.
//Postcondition: Returns true if the stack is empty,
// otherwise returns false.
bool isFullStack() const;
//Function to determine whether the stack is full.
//Postcondition: Returns true if the stack is full,
// otherwise returns false.
void push(const Type& newItem);
//Function to add newItem to the stack.
//Precondition: The stack exists and is not full.
//Postcondition: The stack is changed and newItem
// is added to the top of the stack.
Type top() const;
//Function to return the top element of the stack.
//Precondition: The stack exists and is not empty.
//Postcondition: If the stack is empty, the program
// terminates; otherwise, the top element
// of the stack is returned.
void pop();
//Function to remove the top element of the stack.
//Precondition: The stack exists and is not empty.
//Postcondition: The stack is changed and the top
// element is removed from the stack.
stackType(int stackSize = 100);
//constructor
//Create an array of the size stackSize to hold
//the stack elements. The default stack size is 100.
//Postcondition: The variable list contains the base
// address of the array, stackTop = 0, and
// maxStackSize = stackSize.
stackType(const stackType& otherStack);
//copy constructor
~stackType();
//destructor
//Remove all the elements from the stack.
//Postcondition: The array (list) holding the stack
// elements is deleted.
private:
int maxStackSize; //variable to store the maximum stack size
int stackTop; //variable to point to the top of the stack
Type *list; //pointer to the array that holds the
//stack elements
void copyStack(const stackType& otherStack);
//Function to make a copy of otherStack.
//Postcondition: A copy of otherStack is created and
// assigned to this stack.
};
template
void stackType::initializeStack()
{
stackTop = 0;
}//end initializeStack
template
bool stackType::isEmptyStack() const
{
return(stackTop == 0);
}//end isEmptyStack
template
bool stackType::isFullStack() const
{
return(stackTop == maxStackSize);
} //end isFullStack
template
void stackType::push(const Type& newItem)
{
if (!isFullStack())
{
list[stackTop] = newItem; //add newItem to the
//top of the stack
stackTop++; //increment stackTop
}
else
cout << "Cannot add to a full stack." << endl;
}//end push
template
Type stackType::top() const
{
assert(stackTop != 0); //if stack is empty,
//terminate the program
return list[stackTop - 1]; //return the element of the
//stack indicated by
//stackTop - 1
}//end top
template
void stackType::pop()
{
if (!isEmptyStack())
stackTop--; //decrement stackTop
else
cout << "Cannot remove from an empty stack." << endl;
}//end pop
template
stackType::stackType(int stackSize)
{
if (stackSize <= 0)
{
cout << "Size of the array to hold the stack must "
<< "be positive." << endl;
cout << "Creating an array of size 100." << endl;
maxStackSize = 100;
}
else
maxStackSize = stackSize; //set the stack size to
//the value specified by
//the parameter stackSize
stackTop = 0; //set stackTop to 0
list = new Type[maxStackSize]; //create the array to
//hold the stack elements
}//end constructor
template
stackType::~stackType() //destructor
{
delete [] list; //deallocate the memory occupied
//by the array
}//end destructor
template
void stackType::copyStack(const stackType& otherStack)
{
delete [] list;
maxStackSize = otherStack.maxStackSize;
stackTop = otherStack.stackTop;
list = new Type[maxStackSize];
//copy otherStack into this stack
for (int j = 0; j < stackTop; j++)
list[j] = otherStack.list[j];
} //end copyStack
template
stackType::stackType(const stackType& otherStack)
{
list = NULL;
copyStack(otherStack);
}//end copy constructor
template
const stackType& stackType::operator=
(const stackType& otherStack)
{
if (this != &otherStack) //avoid self-copy
copyStack(otherStack);
return *this;
} //end operator=
#endif
/Header file: stackADT.h
#ifndef H_StackADT
#define H_StackADT
template
class stackADT
{
public:
virtual void initializeStack() = 0;
//Method to initialize the stack to an empty state.
//Postcondition: Stack is empty
virtual bool isEmptyStack() const = 0;
//Function to determine whether the stack is empty.
//Postcondition: Returns true if the stack is empty,
// otherwise returns false.
virtual bool isFullStack() const = 0;
//Function to determine whether the stack is full.
//Postcondition: Returns true if the stack is full,
// otherwise returns false.
virtual void push(const Type& newItem) = 0;
//Function to add newItem to the stack.
//Precondition: The stack exists and is not full.
//Postcondition: The stack is changed and newItem
// is added to the top of the stack.
virtual Type top() const = 0;
//Function to return the top element of the stack.
//Precondition: The stack exists and is not empty.
//Postcondition: If the stack is empty, the program
// terminates; otherwise, the top element
// of the stack is returned.
virtual void pop() = 0;
//Function to remove the top element of the stack.
//Precondition: The stack exists and is not empty.
//Postcondition: The stack is changed and the top
// element is removed from the stack.
};
#endif
Solution
#include
#include
#include
using namespace std;
// Function to convert Infix expression to postfix
string InfixToPostfix(string expression);
// Function to verify whether an operator has higher precedence over other
int HasHigherPrecedence(char operator1, char operator2);
// Function to verify whether a character is operator symbol or not.
bool IsOperator(char C);
// Function to verify whether a character is alphanumeric chanaracter (letter or numeric digit) or
not.
bool IsOperand(char C);
int main()
{
string expression;
cout<<"Enter Infix Expression  ";
getline(cin,expression);
string postfix = InfixToPostfix(expression);
cout<<"Output = "< S;
string postfix = ""; // Initialize postfix as empty string.
for(int i = 0;i< expression.length();i++) {
// Scanning each character from left.
// If character is a delimitter, move on.
if(expression[i] == ' ' || expression[i] == ',') continue;
// If character is operator, pop two elements from stack, perform operation and push the
result back.
else if(IsOperator(expression[i]))
{
while(!S.empty() && S.top() != '(' && HasHigherPrecedence(S.top(),expression[i]))
{
postfix+= S.top();
S.pop();
}
S.push(expression[i]);
}
// Else if character is an operand
else if(IsOperand(expression[i]))
{
postfix +=expression[i];
}
else if (expression[i] == '(')
{
S.push(expression[i]);
}
else if(expression[i] == ')')
{
while(!S.empty() && S.top() != '(') {
postfix += S.top();
S.pop();
}
S.pop();
}
}
while(!S.empty()) {
postfix += S.top();
S.pop();
}
return postfix;
}
// Function to verify whether a character is english letter or numeric digit.
// We are assuming in this solution that operand will be a single character
bool IsOperand(char C)
{
if(C >= '0' && C <= '9') return true;
if(C >= 'a' && C <= 'z') return true;
if(C >= 'A' && C <= 'Z') return true;
return false;
}
// Function to verify whether a character is operator symbol or not.
bool IsOperator(char C)
{
if(C == '+' || C == '-' || C == '*' || C == '/' || C== '$')
return true;
return false;
}
// Function to verify whether an operator is right associative or not.
int IsRightAssociative(char op)
{
if(op == '$') return true;
return false;
}
// Function to get weight of an operator. An operator with higher weight will have higher
precedence.
int GetOperatorWeight(char op)
{
int weight = -1;
switch(op)
{
case '+':
case '-':
weight = 1;
case '*':
case '/':
weight = 2;
case '$':
weight = 3;
}
return weight;
}
// Function to perform an operation and return output.
int HasHigherPrecedence(char op1, char op2)
{
int op1Weight = GetOperatorWeight(op1);
int op2Weight = GetOperatorWeight(op2);
// If operators have equal precedence, return true if they are left associative.
// return false, if right associative.
// if operator is left-associative, left one should be given priority.
if(op1Weight == op2Weight)
{
if(IsRightAssociative(op1)) return false;
else return true;
}
return op1Weight > op2Weight ? true: false;
}
OUTPUT:
a+b
ab+

More Related Content

Similar to Write a program that converts an infix expression into an equivalent.pdf

C++ QUICK REFERENCE.pdf
C++ QUICK REFERENCE.pdfC++ QUICK REFERENCE.pdf
C++ QUICK REFERENCE.pdffqerwqdfad
 
CppQuickRef.pdf
CppQuickRef.pdfCppQuickRef.pdf
CppQuickRef.pdfkurimaru1
 
Data structures stacks
Data structures   stacksData structures   stacks
Data structures stacksmaamir farooq
 
1- The design of a singly-linked list below is a picture of the functi (1).pdf
1- The design of a singly-linked list below is a picture of the functi (1).pdf1- The design of a singly-linked list below is a picture of the functi (1).pdf
1- The design of a singly-linked list below is a picture of the functi (1).pdfafgt2012
 
01 stack 20160908_jintaek_seo
01 stack 20160908_jintaek_seo01 stack 20160908_jintaek_seo
01 stack 20160908_jintaek_seoJinTaek Seo
 
@author Derek Harter @cwid 123 45 678 @class .docx
@author Derek Harter  @cwid   123 45 678  @class  .docx@author Derek Harter  @cwid   123 45 678  @class  .docx
@author Derek Harter @cwid 123 45 678 @class .docxadkinspaige22
 
Please need help on C++ language.Infix to Postfix) Write a program.pdf
Please need help on C++ language.Infix to Postfix) Write a program.pdfPlease need help on C++ language.Infix to Postfix) Write a program.pdf
Please need help on C++ language.Infix to Postfix) Write a program.pdfpristiegee
 
C++ Program It is only 1 rotation. Up-rotation of a stack. Write a.pdf
C++ Program It is only 1 rotation. Up-rotation of a stack.  Write a.pdfC++ Program It is only 1 rotation. Up-rotation of a stack.  Write a.pdf
C++ Program It is only 1 rotation. Up-rotation of a stack. Write a.pdfpallavi953613
 
streams and files
 streams and files streams and files
streams and filesMariam Butt
 

Similar to Write a program that converts an infix expression into an equivalent.pdf (20)

C++ QUICK REFERENCE.pdf
C++ QUICK REFERENCE.pdfC++ QUICK REFERENCE.pdf
C++ QUICK REFERENCE.pdf
 
CppQuickRef.pdf
CppQuickRef.pdfCppQuickRef.pdf
CppQuickRef.pdf
 
Stack
StackStack
Stack
 
Stack queue
Stack queueStack queue
Stack queue
 
Stack queue
Stack queueStack queue
Stack queue
 
Stack queue
Stack queueStack queue
Stack queue
 
Stack queue
Stack queueStack queue
Stack queue
 
Stack queue
Stack queueStack queue
Stack queue
 
Stack queue
Stack queueStack queue
Stack queue
 
Stack queue
Stack queueStack queue
Stack queue
 
Data structures stacks
Data structures   stacksData structures   stacks
Data structures stacks
 
1- The design of a singly-linked list below is a picture of the functi (1).pdf
1- The design of a singly-linked list below is a picture of the functi (1).pdf1- The design of a singly-linked list below is a picture of the functi (1).pdf
1- The design of a singly-linked list below is a picture of the functi (1).pdf
 
01 stack 20160908_jintaek_seo
01 stack 20160908_jintaek_seo01 stack 20160908_jintaek_seo
01 stack 20160908_jintaek_seo
 
Stacks
StacksStacks
Stacks
 
@author Derek Harter @cwid 123 45 678 @class .docx
@author Derek Harter  @cwid   123 45 678  @class  .docx@author Derek Harter  @cwid   123 45 678  @class  .docx
@author Derek Harter @cwid 123 45 678 @class .docx
 
Please need help on C++ language.Infix to Postfix) Write a program.pdf
Please need help on C++ language.Infix to Postfix) Write a program.pdfPlease need help on C++ language.Infix to Postfix) Write a program.pdf
Please need help on C++ language.Infix to Postfix) Write a program.pdf
 
C++ Program It is only 1 rotation. Up-rotation of a stack. Write a.pdf
C++ Program It is only 1 rotation. Up-rotation of a stack.  Write a.pdfC++ Program It is only 1 rotation. Up-rotation of a stack.  Write a.pdf
C++ Program It is only 1 rotation. Up-rotation of a stack. Write a.pdf
 
C++ Language
C++ LanguageC++ Language
C++ Language
 
Stack
StackStack
Stack
 
streams and files
 streams and files streams and files
streams and files
 

More from mohdjakirfb

Describe the stages of malaria and the site of protozoal activity on.pdf
Describe the stages of malaria and the site of protozoal activity on.pdfDescribe the stages of malaria and the site of protozoal activity on.pdf
Describe the stages of malaria and the site of protozoal activity on.pdfmohdjakirfb
 
Database problem. Design a realtional schema based on E-R Diagram. B.pdf
Database problem. Design a realtional schema based on E-R Diagram. B.pdfDatabase problem. Design a realtional schema based on E-R Diagram. B.pdf
Database problem. Design a realtional schema based on E-R Diagram. B.pdfmohdjakirfb
 
d. What types of information systems ru currently utilized at PVF Pr.pdf
d. What types of information systems ru currently utilized at PVF Pr.pdfd. What types of information systems ru currently utilized at PVF Pr.pdf
d. What types of information systems ru currently utilized at PVF Pr.pdfmohdjakirfb
 
Bacteria growthExplain a growth curve.Explain lag phase, exponen.pdf
Bacteria growthExplain a growth curve.Explain lag phase, exponen.pdfBacteria growthExplain a growth curve.Explain lag phase, exponen.pdf
Bacteria growthExplain a growth curve.Explain lag phase, exponen.pdfmohdjakirfb
 
An ovum has all the nutrients stored that required for embryonic d.pdf
An ovum has all the nutrients stored that required for embryonic d.pdfAn ovum has all the nutrients stored that required for embryonic d.pdf
An ovum has all the nutrients stored that required for embryonic d.pdfmohdjakirfb
 
A plant with either the PP or Pp genotype has purple flowers, while .pdf
A plant with either the PP or Pp genotype has purple flowers, while .pdfA plant with either the PP or Pp genotype has purple flowers, while .pdf
A plant with either the PP or Pp genotype has purple flowers, while .pdfmohdjakirfb
 
________ ANOVA relies on matched samples in a similar way to the mat.pdf
________ ANOVA relies on matched samples in a similar way to the mat.pdf________ ANOVA relies on matched samples in a similar way to the mat.pdf
________ ANOVA relies on matched samples in a similar way to the mat.pdfmohdjakirfb
 
Write a Java program that mimics the framework for an online movie i.pdf
Write a Java program that mimics the framework for an online movie i.pdfWrite a Java program that mimics the framework for an online movie i.pdf
Write a Java program that mimics the framework for an online movie i.pdfmohdjakirfb
 
Which microtubule (MT) population binds to chromosomes during mitosi.pdf
Which microtubule (MT) population binds to chromosomes during mitosi.pdfWhich microtubule (MT) population binds to chromosomes during mitosi.pdf
Which microtubule (MT) population binds to chromosomes during mitosi.pdfmohdjakirfb
 
React to the following statement Knowledge is the technology wh.pdf
React to the following statement Knowledge is the technology wh.pdfReact to the following statement Knowledge is the technology wh.pdf
React to the following statement Knowledge is the technology wh.pdfmohdjakirfb
 
what animals first evolved true skeletonswhat animals first .pdf
what animals first evolved true skeletonswhat animals first .pdfwhat animals first evolved true skeletonswhat animals first .pdf
what animals first evolved true skeletonswhat animals first .pdfmohdjakirfb
 
true or false Different parts of the genome evolve at different spe.pdf
true or false Different parts of the genome evolve at different spe.pdftrue or false Different parts of the genome evolve at different spe.pdf
true or false Different parts of the genome evolve at different spe.pdfmohdjakirfb
 
The brightness in the center of a Fresnel diffraction pattern. Is al.pdf
The brightness in the center of a Fresnel diffraction pattern.  Is al.pdfThe brightness in the center of a Fresnel diffraction pattern.  Is al.pdf
The brightness in the center of a Fresnel diffraction pattern. Is al.pdfmohdjakirfb
 
Should Linda’s history of past improprieties lead Maria to withdraw .pdf
Should Linda’s history of past improprieties lead Maria to withdraw .pdfShould Linda’s history of past improprieties lead Maria to withdraw .pdf
Should Linda’s history of past improprieties lead Maria to withdraw .pdfmohdjakirfb
 
Problem 4.Organisms are present in ballast water discharged from a.pdf
Problem 4.Organisms are present in ballast water discharged from a.pdfProblem 4.Organisms are present in ballast water discharged from a.pdf
Problem 4.Organisms are present in ballast water discharged from a.pdfmohdjakirfb
 
Q2. Does Application Engine Generate SQLs like Query ManagerQ7. C.pdf
Q2. Does Application Engine Generate SQLs like Query ManagerQ7. C.pdfQ2. Does Application Engine Generate SQLs like Query ManagerQ7. C.pdf
Q2. Does Application Engine Generate SQLs like Query ManagerQ7. C.pdfmohdjakirfb
 
QUESTION 6- Delay spread of optical pulses results on multimode fibe.pdf
QUESTION 6- Delay spread of optical pulses results on multimode fibe.pdfQUESTION 6- Delay spread of optical pulses results on multimode fibe.pdf
QUESTION 6- Delay spread of optical pulses results on multimode fibe.pdfmohdjakirfb
 
31.A Biased sample is one that ______a. Is too smallb. Will al.pdf
31.A Biased sample is one that ______a. Is too smallb. Will al.pdf31.A Biased sample is one that ______a. Is too smallb. Will al.pdf
31.A Biased sample is one that ______a. Is too smallb. Will al.pdfmohdjakirfb
 
Please help me Im very confused thanks Find sin 2x, cos 2x, and tan .pdf
Please help me Im very confused thanks Find sin 2x, cos 2x, and tan .pdfPlease help me Im very confused thanks Find sin 2x, cos 2x, and tan .pdf
Please help me Im very confused thanks Find sin 2x, cos 2x, and tan .pdfmohdjakirfb
 
please explain in detail What is the PCAOB Please explain what is t.pdf
please explain in detail What is the PCAOB Please explain what is t.pdfplease explain in detail What is the PCAOB Please explain what is t.pdf
please explain in detail What is the PCAOB Please explain what is t.pdfmohdjakirfb
 

More from mohdjakirfb (20)

Describe the stages of malaria and the site of protozoal activity on.pdf
Describe the stages of malaria and the site of protozoal activity on.pdfDescribe the stages of malaria and the site of protozoal activity on.pdf
Describe the stages of malaria and the site of protozoal activity on.pdf
 
Database problem. Design a realtional schema based on E-R Diagram. B.pdf
Database problem. Design a realtional schema based on E-R Diagram. B.pdfDatabase problem. Design a realtional schema based on E-R Diagram. B.pdf
Database problem. Design a realtional schema based on E-R Diagram. B.pdf
 
d. What types of information systems ru currently utilized at PVF Pr.pdf
d. What types of information systems ru currently utilized at PVF Pr.pdfd. What types of information systems ru currently utilized at PVF Pr.pdf
d. What types of information systems ru currently utilized at PVF Pr.pdf
 
Bacteria growthExplain a growth curve.Explain lag phase, exponen.pdf
Bacteria growthExplain a growth curve.Explain lag phase, exponen.pdfBacteria growthExplain a growth curve.Explain lag phase, exponen.pdf
Bacteria growthExplain a growth curve.Explain lag phase, exponen.pdf
 
An ovum has all the nutrients stored that required for embryonic d.pdf
An ovum has all the nutrients stored that required for embryonic d.pdfAn ovum has all the nutrients stored that required for embryonic d.pdf
An ovum has all the nutrients stored that required for embryonic d.pdf
 
A plant with either the PP or Pp genotype has purple flowers, while .pdf
A plant with either the PP or Pp genotype has purple flowers, while .pdfA plant with either the PP or Pp genotype has purple flowers, while .pdf
A plant with either the PP or Pp genotype has purple flowers, while .pdf
 
________ ANOVA relies on matched samples in a similar way to the mat.pdf
________ ANOVA relies on matched samples in a similar way to the mat.pdf________ ANOVA relies on matched samples in a similar way to the mat.pdf
________ ANOVA relies on matched samples in a similar way to the mat.pdf
 
Write a Java program that mimics the framework for an online movie i.pdf
Write a Java program that mimics the framework for an online movie i.pdfWrite a Java program that mimics the framework for an online movie i.pdf
Write a Java program that mimics the framework for an online movie i.pdf
 
Which microtubule (MT) population binds to chromosomes during mitosi.pdf
Which microtubule (MT) population binds to chromosomes during mitosi.pdfWhich microtubule (MT) population binds to chromosomes during mitosi.pdf
Which microtubule (MT) population binds to chromosomes during mitosi.pdf
 
React to the following statement Knowledge is the technology wh.pdf
React to the following statement Knowledge is the technology wh.pdfReact to the following statement Knowledge is the technology wh.pdf
React to the following statement Knowledge is the technology wh.pdf
 
what animals first evolved true skeletonswhat animals first .pdf
what animals first evolved true skeletonswhat animals first .pdfwhat animals first evolved true skeletonswhat animals first .pdf
what animals first evolved true skeletonswhat animals first .pdf
 
true or false Different parts of the genome evolve at different spe.pdf
true or false Different parts of the genome evolve at different spe.pdftrue or false Different parts of the genome evolve at different spe.pdf
true or false Different parts of the genome evolve at different spe.pdf
 
The brightness in the center of a Fresnel diffraction pattern. Is al.pdf
The brightness in the center of a Fresnel diffraction pattern.  Is al.pdfThe brightness in the center of a Fresnel diffraction pattern.  Is al.pdf
The brightness in the center of a Fresnel diffraction pattern. Is al.pdf
 
Should Linda’s history of past improprieties lead Maria to withdraw .pdf
Should Linda’s history of past improprieties lead Maria to withdraw .pdfShould Linda’s history of past improprieties lead Maria to withdraw .pdf
Should Linda’s history of past improprieties lead Maria to withdraw .pdf
 
Problem 4.Organisms are present in ballast water discharged from a.pdf
Problem 4.Organisms are present in ballast water discharged from a.pdfProblem 4.Organisms are present in ballast water discharged from a.pdf
Problem 4.Organisms are present in ballast water discharged from a.pdf
 
Q2. Does Application Engine Generate SQLs like Query ManagerQ7. C.pdf
Q2. Does Application Engine Generate SQLs like Query ManagerQ7. C.pdfQ2. Does Application Engine Generate SQLs like Query ManagerQ7. C.pdf
Q2. Does Application Engine Generate SQLs like Query ManagerQ7. C.pdf
 
QUESTION 6- Delay spread of optical pulses results on multimode fibe.pdf
QUESTION 6- Delay spread of optical pulses results on multimode fibe.pdfQUESTION 6- Delay spread of optical pulses results on multimode fibe.pdf
QUESTION 6- Delay spread of optical pulses results on multimode fibe.pdf
 
31.A Biased sample is one that ______a. Is too smallb. Will al.pdf
31.A Biased sample is one that ______a. Is too smallb. Will al.pdf31.A Biased sample is one that ______a. Is too smallb. Will al.pdf
31.A Biased sample is one that ______a. Is too smallb. Will al.pdf
 
Please help me Im very confused thanks Find sin 2x, cos 2x, and tan .pdf
Please help me Im very confused thanks Find sin 2x, cos 2x, and tan .pdfPlease help me Im very confused thanks Find sin 2x, cos 2x, and tan .pdf
Please help me Im very confused thanks Find sin 2x, cos 2x, and tan .pdf
 
please explain in detail What is the PCAOB Please explain what is t.pdf
please explain in detail What is the PCAOB Please explain what is t.pdfplease explain in detail What is the PCAOB Please explain what is t.pdf
please explain in detail What is the PCAOB Please explain what is t.pdf
 

Recently uploaded

Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitolTechU
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
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
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
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
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 

Recently uploaded (20)

Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptx
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
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
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
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
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 

Write a program that converts an infix expression into an equivalent.pdf

  • 1. Write a program that converts an infix expression into an equivalent postfix expression. The rules to convert an infix expression into an equivalent postfix expression are as follows (C++): Initialize pfx to an empty expression and also initialize the stack. Get the next symbol, sym, from infx. If sym is an operand, append sym to pfx. If sym is (, push sym into the stack. If sym is ), pop and append all of the symbols from the stack until the most recent left parentheses. Pop and discard the left parentheses. If sym is an operator: Pop and append all of the operators from the stack to pfx that are above the most recent left parentheses and have precedence greater than or equal to sym. Push sym onto the stack. After processing infx, some operators might be left in the stack. Pop and append to pfx everything from the stack. In this program, you will consider the following (binary) arithmetic operators: +, -, *, and /. You may assume that the expressions you will process are error free. Design a class that stores the infix and postfix strings. The class must include the following operations: getInfix: Stores the infix expression. showInfix: Outputs the infix expression. showPostfix: Outputs the postfix expression. convertToPostfix: Converts the infix expression into a postfix expression. The resulting postfix expression is stored in pfx. precedence: Determines the precedence between two operators. If the first operator is of higher or equal precedence than the second operator, it returns the value true; otherwise, it returns the value false. A + B - C; (A + B ) * C; (A + B) * (C - D); A + ((B + C) * (E - F) - G) / (H - I); A + B * (C + D ) - E / F * G + H; Infix Expression: A+B-C; Postfix Expression: AB+C- Infix Expression: (A+B)*C;
  • 2. Postfix Expression: AB+C* Infix Expression: (A+B)*(C-D); Postfix Expression: AB+CD-* Infix Expression: A+((B+C)*(E-F)-G)/(H-I); Postfix Expression: ABC+EF-*G-HI-/+ Infix Expression: A+B*(C+D)-E/F*G+H; Postfix Expression: ABCD+*+EF/G*-H+ Turn in: A UML diagram for your class. The header file for your class. The implementation file for your class. The source code for your test program. (C++) (Below already done code.) //Header file: myStack.h #ifndef H_StackType #define H_StackType #include #include #include "stackADT.h" using namespace std; template class stackType: public stackADT { public: const stackType& operator=(const stackType&); //Overload the assignment operator. void initializeStack(); //Function to initialize the stack to an empty state. //Postcondition: stackTop = 0 bool isEmptyStack() const; //Function to determine whether the stack is empty.
  • 3. //Postcondition: Returns true if the stack is empty, // otherwise returns false. bool isFullStack() const; //Function to determine whether the stack is full. //Postcondition: Returns true if the stack is full, // otherwise returns false. void push(const Type& newItem); //Function to add newItem to the stack. //Precondition: The stack exists and is not full. //Postcondition: The stack is changed and newItem // is added to the top of the stack. Type top() const; //Function to return the top element of the stack. //Precondition: The stack exists and is not empty. //Postcondition: If the stack is empty, the program // terminates; otherwise, the top element // of the stack is returned. void pop(); //Function to remove the top element of the stack. //Precondition: The stack exists and is not empty. //Postcondition: The stack is changed and the top // element is removed from the stack. stackType(int stackSize = 100); //constructor //Create an array of the size stackSize to hold //the stack elements. The default stack size is 100. //Postcondition: The variable list contains the base // address of the array, stackTop = 0, and // maxStackSize = stackSize. stackType(const stackType& otherStack); //copy constructor ~stackType(); //destructor //Remove all the elements from the stack. //Postcondition: The array (list) holding the stack // elements is deleted.
  • 4. private: int maxStackSize; //variable to store the maximum stack size int stackTop; //variable to point to the top of the stack Type *list; //pointer to the array that holds the //stack elements void copyStack(const stackType& otherStack); //Function to make a copy of otherStack. //Postcondition: A copy of otherStack is created and // assigned to this stack. }; template void stackType::initializeStack() { stackTop = 0; }//end initializeStack template bool stackType::isEmptyStack() const { return(stackTop == 0); }//end isEmptyStack template bool stackType::isFullStack() const { return(stackTop == maxStackSize); } //end isFullStack template void stackType::push(const Type& newItem) { if (!isFullStack()) { list[stackTop] = newItem; //add newItem to the //top of the stack stackTop++; //increment stackTop } else
  • 5. cout << "Cannot add to a full stack." << endl; }//end push template Type stackType::top() const { assert(stackTop != 0); //if stack is empty, //terminate the program return list[stackTop - 1]; //return the element of the //stack indicated by //stackTop - 1 }//end top template void stackType::pop() { if (!isEmptyStack()) stackTop--; //decrement stackTop else cout << "Cannot remove from an empty stack." << endl; }//end pop template stackType::stackType(int stackSize) { if (stackSize <= 0) { cout << "Size of the array to hold the stack must " << "be positive." << endl; cout << "Creating an array of size 100." << endl; maxStackSize = 100; } else maxStackSize = stackSize; //set the stack size to //the value specified by //the parameter stackSize stackTop = 0; //set stackTop to 0 list = new Type[maxStackSize]; //create the array to //hold the stack elements
  • 6. }//end constructor template stackType::~stackType() //destructor { delete [] list; //deallocate the memory occupied //by the array }//end destructor template void stackType::copyStack(const stackType& otherStack) { delete [] list; maxStackSize = otherStack.maxStackSize; stackTop = otherStack.stackTop; list = new Type[maxStackSize]; //copy otherStack into this stack for (int j = 0; j < stackTop; j++) list[j] = otherStack.list[j]; } //end copyStack template stackType::stackType(const stackType& otherStack) { list = NULL; copyStack(otherStack); }//end copy constructor template const stackType& stackType::operator= (const stackType& otherStack) { if (this != &otherStack) //avoid self-copy copyStack(otherStack); return *this; } //end operator= #endif /Header file: stackADT.h
  • 7. #ifndef H_StackADT #define H_StackADT template class stackADT { public: virtual void initializeStack() = 0; //Method to initialize the stack to an empty state. //Postcondition: Stack is empty virtual bool isEmptyStack() const = 0; //Function to determine whether the stack is empty. //Postcondition: Returns true if the stack is empty, // otherwise returns false. virtual bool isFullStack() const = 0; //Function to determine whether the stack is full. //Postcondition: Returns true if the stack is full, // otherwise returns false. virtual void push(const Type& newItem) = 0; //Function to add newItem to the stack. //Precondition: The stack exists and is not full. //Postcondition: The stack is changed and newItem // is added to the top of the stack. virtual Type top() const = 0; //Function to return the top element of the stack. //Precondition: The stack exists and is not empty. //Postcondition: If the stack is empty, the program // terminates; otherwise, the top element // of the stack is returned. virtual void pop() = 0; //Function to remove the top element of the stack. //Precondition: The stack exists and is not empty. //Postcondition: The stack is changed and the top // element is removed from the stack. };
  • 8. #endif Solution #include #include #include using namespace std; // Function to convert Infix expression to postfix string InfixToPostfix(string expression); // Function to verify whether an operator has higher precedence over other int HasHigherPrecedence(char operator1, char operator2); // Function to verify whether a character is operator symbol or not. bool IsOperator(char C); // Function to verify whether a character is alphanumeric chanaracter (letter or numeric digit) or not. bool IsOperand(char C); int main() { string expression; cout<<"Enter Infix Expression "; getline(cin,expression); string postfix = InfixToPostfix(expression); cout<<"Output = "< S; string postfix = ""; // Initialize postfix as empty string. for(int i = 0;i< expression.length();i++) { // Scanning each character from left. // If character is a delimitter, move on. if(expression[i] == ' ' || expression[i] == ',') continue; // If character is operator, pop two elements from stack, perform operation and push the result back. else if(IsOperator(expression[i])) { while(!S.empty() && S.top() != '(' && HasHigherPrecedence(S.top(),expression[i])) { postfix+= S.top();
  • 9. S.pop(); } S.push(expression[i]); } // Else if character is an operand else if(IsOperand(expression[i])) { postfix +=expression[i]; } else if (expression[i] == '(') { S.push(expression[i]); } else if(expression[i] == ')') { while(!S.empty() && S.top() != '(') { postfix += S.top(); S.pop(); } S.pop(); } } while(!S.empty()) { postfix += S.top(); S.pop(); } return postfix; } // Function to verify whether a character is english letter or numeric digit. // We are assuming in this solution that operand will be a single character bool IsOperand(char C) { if(C >= '0' && C <= '9') return true; if(C >= 'a' && C <= 'z') return true; if(C >= 'A' && C <= 'Z') return true; return false;
  • 10. } // Function to verify whether a character is operator symbol or not. bool IsOperator(char C) { if(C == '+' || C == '-' || C == '*' || C == '/' || C== '$') return true; return false; } // Function to verify whether an operator is right associative or not. int IsRightAssociative(char op) { if(op == '$') return true; return false; } // Function to get weight of an operator. An operator with higher weight will have higher precedence. int GetOperatorWeight(char op) { int weight = -1; switch(op) { case '+': case '-': weight = 1; case '*': case '/': weight = 2; case '$': weight = 3; } return weight; } // Function to perform an operation and return output. int HasHigherPrecedence(char op1, char op2) { int op1Weight = GetOperatorWeight(op1);
  • 11. int op2Weight = GetOperatorWeight(op2); // If operators have equal precedence, return true if they are left associative. // return false, if right associative. // if operator is left-associative, left one should be given priority. if(op1Weight == op2Weight) { if(IsRightAssociative(op1)) return false; else return true; } return op1Weight > op2Weight ? true: false; } OUTPUT: a+b ab+