SlideShare a Scribd company logo
1 of 9
Download to read offline
Write a program that accepts an arithmetic expression of unsigned integers in postfix notation
and builds the arithmetic expression tree that represents that expression. From that tree, the
corresponding fully parenthesized infix expression should be displayed and a file should be
generated that contains the three address format instructions. This topic is discussed in the week
4 reading in module 2, section II-B. The main class should create the GUI shown below:
Pressing the Construct Tree button should cause the tree to be constructed and using that tree, the
corresponding infix expression should be displayed and the three address instruction file should
be generated. The postfix expression input should not be required to have spaces between every
token. Note in the above example that 9+- are not separated by spaces. The above example
should produce the following output file containing the three address instructions:
Add R0 5 9
Sub R1 3
R0 Mul R2 2 3
Div R3 R1 R2
Inheritance should be used to define the arithmetic expression tree. At a minimum, it should
involve three classes: an abstract class for the tree nodes and two derived classes, one for
operand nodes and another for operator nodes. Other classes should be included as needed to
accomplish good object-oriented design. All instance data must be declared as private.
You may assume that the expression is syntactically correct with regard to the order of operators
and operands, but you should check for invalid tokens, such as characters that are not valid
operators or operands such as 2a, which are not valid integers. If an invalid token is detected a
RuntimeException should be thrown and caught by the main class and an appropriate error
message should be displayed. Three Adddress Generator Enter Postfix Expression 359 2 3
Construct Tree Infix Expression ((3-(5 9))/ (2* 3
Solution
#include
#include
#include
#include
#include
struct TREE //Structure to represent a tree
{
char data;
struct TREE *right,*left,*root;
};
typedef TREE tree; /* Stack Using Linked List */
struct Stack //Structure to represent Stack
{
struct TREE *data;
struct Stack *next,*head,*top; //Pointers to next node,head and top
};
typedef struct Stack node;
node *Nw; //Global Variable to represent node
void initialize(node *&n)
{
n = new node;
n -> next = n -> head = n -> top = NULL;
}
void create(node *n)
{
Nw = new node; //Create a new node
Nw -> next = NULL; //Initialize next pointer field
if(n -> head == NULL) //if first node
{
n -> head = Nw; //Initialize head
n -> top = Nw; //Update top
}
}
void push(node *n,tree *ITEM)
{
node *temp = n -> head;
if(n -> head == NULL) //if First Item is Pushed to Stack
{
create(n); //Create a Node
n -> head -> data = ITEM; //Insert Item to head of List
n -> head = Nw;
return; //Exit from Function
}
create(n); //Create a new Node
Nw -> data = ITEM; //Insert Item
while(temp -> next != NULL)
temp = temp -> next; //Go to Last Node
temp -> next = Nw; //Point New node
n -> top = Nw; //Update top
}
node* pop(node *n)
{
node *temp = n -> head,*deleted;
if(n -> top == NULL) //If the Stack is Empty
{
return NULL;
}
if(n -> top == n -> head) //If only one Item
{
deleted = n -> head;
n -> head = n -> top = NULL; //Set head and top to Null
return deleted; //Return deleted node
}
while(temp -> next != n -> top)
temp = temp -> next; //move pointer temp to second last
node
temp -> next = NULL; //Second last node points to
NULL
deleted = n -> top; //Save topmost node
n -> top = temp; //Update top
return deleted; //Return deleted node
}
int Empty(node *nd) //function to check if the stack is
empty or not
{
if(nd -> top == NULL)
return 1; //empty
else
return 0;
}
/*Tree Section */
tree *New;
void create() //Function to create a node of a tree
{
New = new tree;
New -> left = NULL;
New -> right = NULL;
}
void insert(tree *&t,char Item,int pass) //Function to insert item on a
tree
{
if(t == NULL) //If tree doesn't exist
{
t = new tree; //make a node
t -> data = Item; //insert item
t -> left = NULL; //initialize left pointer
t -> right = NULL; //initialize right pointer
if(pass)
t -> root = t; //initialize root
return; //return from function
}
create();
New -> data = Item;
}
void preorder(tree *t) //Function to print tree in preorder
{
if(t != NULL)
{
cout << t -> data << ' ';
preorder(t -> left);
preorder(t -> right);
}
}
void inorder(tree *t) //Function to print tree in inorder
{
if(t != NULL)
{
inorder(t -> left);
cout << t -> data << ' ';
inorder(t -> right);
}
}
int isOperator(char ch) /* Main Program */
{
if(ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '$')
return 1;
else
return 0;
}
bool check(node *nd)
{
if(nd != NULL)
return true;
else
return false;
}
float calculate(float opr1,float opr2,char oprator)
{
float value;
if(oprator == '+')
value = opr1 + opr2;
if(oprator == '-')
value = opr1 - opr2;
if(oprator == '*')
value = opr1 * opr2;
if(oprator == '/')
if(opr2 != 0)
value = opr1 / opr2;
if(oprator == '$')
value = pow(opr1,opr2);
return value;
}
float evaluate(tree *t)
{
float x,y,result;
char ch[3];
if(t != NULL)
{
if(isOperator(t -> data))
{
x = evaluate(t -> left); //go to left
y = evaluate(t -> right); //go to right
result = calculate(x,y,t -> data); //calculate
return result;
}
else
{
ch[0] = t -> data;
ch[1] = '0';
result = atof(ch); //convert to float
return result;
}
}
}
int main()
{
char postfix[60];
cout << "Enter a valid Postfix Expression ";
cout << "(in a single line, without spaces) ";
int i = 0;
while(postfix[i - 1] != ' ')
postfix[i++] = getchar();
int len = i - 1,pass = true,valid = true;
node *stk,*nd; //create a stack
initialize(stk);
tree *tr = NULL,*value;
i = 0;
while(i < len) //while there is data
{
if(!isOperator(postfix[i])) //if operand
{
create();
New -> data = postfix[i];
push(stk,New); //push address of tree node to stack
}
else //if operator
{
insert(tr,postfix[i],pass); //create a node of tree and insert operator
if(pass) //if first pass
{
nd = pop(stk);
valid = check(nd);
if(!valid)
break;
value = nd -> data; //pop address
tr -> right = value; //assign to left child
nd = pop(stk);
valid = check(nd);
if(!valid)
break;
value = nd -> data; //pop address
tr -> left = value; //assign to right child
pass = false; //reset pass
push(stk,tr); //push address to stack
}
else
{
nd = pop(stk);
valid = check(nd);
if(!valid)
break;
value = nd -> data; //pop address
New -> right = value; //assign to left child
nd = pop(stk);
valid = check(nd);
if(!valid)
break;
value = nd -> data; //pop stack
New -> left = value; //assign to right child
push(stk,New); //push address to stack
}
}
i++; //update i
}
if(!Empty(stk))
{
tr -> root = pop(stk) -> data; //Last data of stack is root of tree
tr = tr -> root;
}
if(!Empty(stk)) //if stack is not empty
valid = false;
if(!valid)
{
cout << " The Given Postfix Expression is not Valid";
cout << " Check above Expression and try again...";
getch();
return 0; //exit from program
}
cout << " Infix : ";
inorder(tr); //Inorder traversal gives Infix of expression
cout << "  Prefix : ";
preorder(tr); //Postorder traversal gives Postfix of expression
float result = evaluate(tr);
cout << endl << "

More Related Content

Similar to Write a program that accepts an arithmetic expression of unsigned in.pdf

Please read the comment ins codeExpressionTree.java-------------.pdf
Please read the comment ins codeExpressionTree.java-------------.pdfPlease read the comment ins codeExpressionTree.java-------------.pdf
Please read the comment ins codeExpressionTree.java-------------.pdfshanki7
 
MAINCPP include ltiostreamgt include ltstringgt u.pdf
MAINCPP include ltiostreamgt include ltstringgt u.pdfMAINCPP include ltiostreamgt include ltstringgt u.pdf
MAINCPP include ltiostreamgt include ltstringgt u.pdfadityastores21
 
A)B) C++ program to create a Complete Binary tree from its Lin.pdf
A)B) C++ program to create a Complete Binary tree from its Lin.pdfA)B) C++ program to create a Complete Binary tree from its Lin.pdf
A)B) C++ program to create a Complete Binary tree from its Lin.pdfanton291
 
Assignment isPage 349-350 #4 and #5 Use the Linked List lab.pdf
Assignment isPage 349-350 #4 and #5 Use the Linked List lab.pdfAssignment isPage 349-350 #4 and #5 Use the Linked List lab.pdf
Assignment isPage 349-350 #4 and #5 Use the Linked List lab.pdffortmdu
 
Program to insert in a sorted list #includestdio.h#include.pdf
 Program to insert in a sorted list #includestdio.h#include.pdf Program to insert in a sorted list #includestdio.h#include.pdf
Program to insert in a sorted list #includestdio.h#include.pdfsudhirchourasia86
 
Tree Traversals A tree traversal is the process of visiting.pdf
Tree Traversals A tree traversal is the process of visiting.pdfTree Traversals A tree traversal is the process of visiting.pdf
Tree Traversals A tree traversal is the process of visiting.pdfajayadinathcomputers
 
C++ Please write the whole code that is needed for this assignment- wr.docx
C++ Please write the whole code that is needed for this assignment- wr.docxC++ Please write the whole code that is needed for this assignment- wr.docx
C++ Please write the whole code that is needed for this assignment- wr.docxBrianGHiNewmanv
 
Using the provided table interface table.h and the sample linked lis.pdf
Using the provided table interface table.h and the sample linked lis.pdfUsing the provided table interface table.h and the sample linked lis.pdf
Using the provided table interface table.h and the sample linked lis.pdfconnellalykshamesb60
 
C program to insert a node in doubly linked list
C program to insert a node in doubly linked listC program to insert a node in doubly linked list
C program to insert a node in doubly linked listSourav Gayen
 
coding in C- Create a function called reverseList that takes the head.docx
coding in C- Create a function called reverseList that takes the head.docxcoding in C- Create a function called reverseList that takes the head.docx
coding in C- Create a function called reverseList that takes the head.docxtienlivick
 
Binary Tree in C++ coding in the data structure
Binary Tree in C++ coding in the data structureBinary Tree in C++ coding in the data structure
Binary Tree in C++ coding in the data structureZarghamullahShah
 
How to do insertion sort on a singly linked list with no header usin.pdf
How to do insertion sort on a singly linked list with no header usin.pdfHow to do insertion sort on a singly linked list with no header usin.pdf
How to do insertion sort on a singly linked list with no header usin.pdfarihantelehyb
 
hi i have to write a java program involving link lists. i have a pro.pdf
hi i have to write a java program involving link lists. i have a pro.pdfhi i have to write a java program involving link lists. i have a pro.pdf
hi i have to write a java program involving link lists. i have a pro.pdfarchgeetsenterprises
 
mainpublic class AssignmentThree {    public static void ma.pdf
mainpublic class AssignmentThree {    public static void ma.pdfmainpublic class AssignmentThree {    public static void ma.pdf
mainpublic class AssignmentThree {    public static void ma.pdffathimafancyjeweller
 
#include iostream using namespace std; const int nil = 0; cl.docx
#include iostream using namespace std; const int nil = 0; cl.docx#include iostream using namespace std; const int nil = 0; cl.docx
#include iostream using namespace std; const int nil = 0; cl.docxajoy21
 
Please help solve this in C++ So the program is working fin.pdf
Please help solve this in C++ So the program is working fin.pdfPlease help solve this in C++ So the program is working fin.pdf
Please help solve this in C++ So the program is working fin.pdfankit11134
 
Doublylinklist
DoublylinklistDoublylinklist
Doublylinklistritu1806
 

Similar to Write a program that accepts an arithmetic expression of unsigned in.pdf (20)

Please read the comment ins codeExpressionTree.java-------------.pdf
Please read the comment ins codeExpressionTree.java-------------.pdfPlease read the comment ins codeExpressionTree.java-------------.pdf
Please read the comment ins codeExpressionTree.java-------------.pdf
 
MAINCPP include ltiostreamgt include ltstringgt u.pdf
MAINCPP include ltiostreamgt include ltstringgt u.pdfMAINCPP include ltiostreamgt include ltstringgt u.pdf
MAINCPP include ltiostreamgt include ltstringgt u.pdf
 
A)B) C++ program to create a Complete Binary tree from its Lin.pdf
A)B) C++ program to create a Complete Binary tree from its Lin.pdfA)B) C++ program to create a Complete Binary tree from its Lin.pdf
A)B) C++ program to create a Complete Binary tree from its Lin.pdf
 
Assignment isPage 349-350 #4 and #5 Use the Linked List lab.pdf
Assignment isPage 349-350 #4 and #5 Use the Linked List lab.pdfAssignment isPage 349-350 #4 and #5 Use the Linked List lab.pdf
Assignment isPage 349-350 #4 and #5 Use the Linked List lab.pdf
 
Lab-2.4 101.pdf
Lab-2.4 101.pdfLab-2.4 101.pdf
Lab-2.4 101.pdf
 
Program to insert in a sorted list #includestdio.h#include.pdf
 Program to insert in a sorted list #includestdio.h#include.pdf Program to insert in a sorted list #includestdio.h#include.pdf
Program to insert in a sorted list #includestdio.h#include.pdf
 
Tree Traversals A tree traversal is the process of visiting.pdf
Tree Traversals A tree traversal is the process of visiting.pdfTree Traversals A tree traversal is the process of visiting.pdf
Tree Traversals A tree traversal is the process of visiting.pdf
 
C++ Please write the whole code that is needed for this assignment- wr.docx
C++ Please write the whole code that is needed for this assignment- wr.docxC++ Please write the whole code that is needed for this assignment- wr.docx
C++ Please write the whole code that is needed for this assignment- wr.docx
 
Using the provided table interface table.h and the sample linked lis.pdf
Using the provided table interface table.h and the sample linked lis.pdfUsing the provided table interface table.h and the sample linked lis.pdf
Using the provided table interface table.h and the sample linked lis.pdf
 
C program to insert a node in doubly linked list
C program to insert a node in doubly linked listC program to insert a node in doubly linked list
C program to insert a node in doubly linked list
 
coding in C- Create a function called reverseList that takes the head.docx
coding in C- Create a function called reverseList that takes the head.docxcoding in C- Create a function called reverseList that takes the head.docx
coding in C- Create a function called reverseList that takes the head.docx
 
Binary Tree in C++ coding in the data structure
Binary Tree in C++ coding in the data structureBinary Tree in C++ coding in the data structure
Binary Tree in C++ coding in the data structure
 
How to do insertion sort on a singly linked list with no header usin.pdf
How to do insertion sort on a singly linked list with no header usin.pdfHow to do insertion sort on a singly linked list with no header usin.pdf
How to do insertion sort on a singly linked list with no header usin.pdf
 
hi i have to write a java program involving link lists. i have a pro.pdf
hi i have to write a java program involving link lists. i have a pro.pdfhi i have to write a java program involving link lists. i have a pro.pdf
hi i have to write a java program involving link lists. i have a pro.pdf
 
mainpublic class AssignmentThree {    public static void ma.pdf
mainpublic class AssignmentThree {    public static void ma.pdfmainpublic class AssignmentThree {    public static void ma.pdf
mainpublic class AssignmentThree {    public static void ma.pdf
 
Unit7 C
Unit7 CUnit7 C
Unit7 C
 
#include iostream using namespace std; const int nil = 0; cl.docx
#include iostream using namespace std; const int nil = 0; cl.docx#include iostream using namespace std; const int nil = 0; cl.docx
#include iostream using namespace std; const int nil = 0; cl.docx
 
Please help solve this in C++ So the program is working fin.pdf
Please help solve this in C++ So the program is working fin.pdfPlease help solve this in C++ So the program is working fin.pdf
Please help solve this in C++ So the program is working fin.pdf
 
DSA(1).pptx
DSA(1).pptxDSA(1).pptx
DSA(1).pptx
 
Doublylinklist
DoublylinklistDoublylinklist
Doublylinklist
 

More from JUSTSTYLISH3B2MOHALI

In a business projects What material is typically contained in a pro.pdf
In a business projects What material is typically contained in a pro.pdfIn a business projects What material is typically contained in a pro.pdf
In a business projects What material is typically contained in a pro.pdfJUSTSTYLISH3B2MOHALI
 
Implement the following flowchart in java. Start Request integer k f.pdf
Implement the following flowchart in java. Start Request integer k f.pdfImplement the following flowchart in java. Start Request integer k f.pdf
Implement the following flowchart in java. Start Request integer k f.pdfJUSTSTYLISH3B2MOHALI
 
If no chiasma forms between homologous chromosomes, what happens Th.pdf
If no chiasma forms between homologous chromosomes, what happens  Th.pdfIf no chiasma forms between homologous chromosomes, what happens  Th.pdf
If no chiasma forms between homologous chromosomes, what happens Th.pdfJUSTSTYLISH3B2MOHALI
 
If two organims form a symbiotic realtionship where they share t.pdf
If two organims form a symbiotic realtionship where they share t.pdfIf two organims form a symbiotic realtionship where they share t.pdf
If two organims form a symbiotic realtionship where they share t.pdfJUSTSTYLISH3B2MOHALI
 
I would appreciate help with these 4 questions. Thank You.1) Expla.pdf
I would appreciate help with these 4 questions. Thank You.1) Expla.pdfI would appreciate help with these 4 questions. Thank You.1) Expla.pdf
I would appreciate help with these 4 questions. Thank You.1) Expla.pdfJUSTSTYLISH3B2MOHALI
 
How do I know when to use the sin^2+cos^2=1 identity....12 angle id.pdf
How do I know when to use the sin^2+cos^2=1 identity....12 angle id.pdfHow do I know when to use the sin^2+cos^2=1 identity....12 angle id.pdf
How do I know when to use the sin^2+cos^2=1 identity....12 angle id.pdfJUSTSTYLISH3B2MOHALI
 
I have a stack in Java populated with integers. Im trying to compa.pdf
I have a stack in Java populated with integers. Im trying to compa.pdfI have a stack in Java populated with integers. Im trying to compa.pdf
I have a stack in Java populated with integers. Im trying to compa.pdfJUSTSTYLISH3B2MOHALI
 
Hint List of commands to read and use use of wild card characters .pdf
Hint List of commands to read and use use of wild card characters .pdfHint List of commands to read and use use of wild card characters .pdf
Hint List of commands to read and use use of wild card characters .pdfJUSTSTYLISH3B2MOHALI
 
Explain in Detail DTE-DCE TransmissionSolutionFirstly the DTE-.pdf
Explain in Detail DTE-DCE TransmissionSolutionFirstly the DTE-.pdfExplain in Detail DTE-DCE TransmissionSolutionFirstly the DTE-.pdf
Explain in Detail DTE-DCE TransmissionSolutionFirstly the DTE-.pdfJUSTSTYLISH3B2MOHALI
 
Explain the data component of social media information systems (SMIS).pdf
Explain the data component of social media information systems (SMIS).pdfExplain the data component of social media information systems (SMIS).pdf
Explain the data component of social media information systems (SMIS).pdfJUSTSTYLISH3B2MOHALI
 
Figure CWhich structure in the cell shown in Figure C above stores.pdf
Figure CWhich structure in the cell shown in Figure C above stores.pdfFigure CWhich structure in the cell shown in Figure C above stores.pdf
Figure CWhich structure in the cell shown in Figure C above stores.pdfJUSTSTYLISH3B2MOHALI
 
Coral reefs. How sensitive to changes in water temperature are coral .pdf
Coral reefs. How sensitive to changes in water temperature are coral .pdfCoral reefs. How sensitive to changes in water temperature are coral .pdf
Coral reefs. How sensitive to changes in water temperature are coral .pdfJUSTSTYLISH3B2MOHALI
 
•0.336 moles of a weak, monoproticacid added to a final volume of 2..pdf
•0.336 moles of a weak, monoproticacid added to a final volume of 2..pdf•0.336 moles of a weak, monoproticacid added to a final volume of 2..pdf
•0.336 moles of a weak, monoproticacid added to a final volume of 2..pdfJUSTSTYLISH3B2MOHALI
 
You are to simulate a dispatcher using a priority queue system in C+.pdf
You are to simulate a dispatcher using a priority queue system in C+.pdfYou are to simulate a dispatcher using a priority queue system in C+.pdf
You are to simulate a dispatcher using a priority queue system in C+.pdfJUSTSTYLISH3B2MOHALI
 
Why was the knowledge of macromolecules “structure” very important i.pdf
Why was the knowledge of macromolecules “structure” very important i.pdfWhy was the knowledge of macromolecules “structure” very important i.pdf
Why was the knowledge of macromolecules “structure” very important i.pdfJUSTSTYLISH3B2MOHALI
 
Why did the sovereign debt problem of Greece a country that accounts.pdf
Why did the sovereign debt problem of Greece a country that accounts.pdfWhy did the sovereign debt problem of Greece a country that accounts.pdf
Why did the sovereign debt problem of Greece a country that accounts.pdfJUSTSTYLISH3B2MOHALI
 
Which of the following could be the most likely cause of a superi.pdf
Which of the following could be the most likely cause of a superi.pdfWhich of the following could be the most likely cause of a superi.pdf
Which of the following could be the most likely cause of a superi.pdfJUSTSTYLISH3B2MOHALI
 
What is the theory of public debt managementSolution1. Sove.pdf
What is the theory of public debt managementSolution1. Sove.pdfWhat is the theory of public debt managementSolution1. Sove.pdf
What is the theory of public debt managementSolution1. Sove.pdfJUSTSTYLISH3B2MOHALI
 
This is a three part question. For each part the answer requires ide.pdf
This is a three part question. For each part the answer requires ide.pdfThis is a three part question. For each part the answer requires ide.pdf
This is a three part question. For each part the answer requires ide.pdfJUSTSTYLISH3B2MOHALI
 
Complete a personal SWOT analysis evaluating your understanding and .pdf
Complete a personal SWOT analysis evaluating your understanding and .pdfComplete a personal SWOT analysis evaluating your understanding and .pdf
Complete a personal SWOT analysis evaluating your understanding and .pdfJUSTSTYLISH3B2MOHALI
 

More from JUSTSTYLISH3B2MOHALI (20)

In a business projects What material is typically contained in a pro.pdf
In a business projects What material is typically contained in a pro.pdfIn a business projects What material is typically contained in a pro.pdf
In a business projects What material is typically contained in a pro.pdf
 
Implement the following flowchart in java. Start Request integer k f.pdf
Implement the following flowchart in java. Start Request integer k f.pdfImplement the following flowchart in java. Start Request integer k f.pdf
Implement the following flowchart in java. Start Request integer k f.pdf
 
If no chiasma forms between homologous chromosomes, what happens Th.pdf
If no chiasma forms between homologous chromosomes, what happens  Th.pdfIf no chiasma forms between homologous chromosomes, what happens  Th.pdf
If no chiasma forms between homologous chromosomes, what happens Th.pdf
 
If two organims form a symbiotic realtionship where they share t.pdf
If two organims form a symbiotic realtionship where they share t.pdfIf two organims form a symbiotic realtionship where they share t.pdf
If two organims form a symbiotic realtionship where they share t.pdf
 
I would appreciate help with these 4 questions. Thank You.1) Expla.pdf
I would appreciate help with these 4 questions. Thank You.1) Expla.pdfI would appreciate help with these 4 questions. Thank You.1) Expla.pdf
I would appreciate help with these 4 questions. Thank You.1) Expla.pdf
 
How do I know when to use the sin^2+cos^2=1 identity....12 angle id.pdf
How do I know when to use the sin^2+cos^2=1 identity....12 angle id.pdfHow do I know when to use the sin^2+cos^2=1 identity....12 angle id.pdf
How do I know when to use the sin^2+cos^2=1 identity....12 angle id.pdf
 
I have a stack in Java populated with integers. Im trying to compa.pdf
I have a stack in Java populated with integers. Im trying to compa.pdfI have a stack in Java populated with integers. Im trying to compa.pdf
I have a stack in Java populated with integers. Im trying to compa.pdf
 
Hint List of commands to read and use use of wild card characters .pdf
Hint List of commands to read and use use of wild card characters .pdfHint List of commands to read and use use of wild card characters .pdf
Hint List of commands to read and use use of wild card characters .pdf
 
Explain in Detail DTE-DCE TransmissionSolutionFirstly the DTE-.pdf
Explain in Detail DTE-DCE TransmissionSolutionFirstly the DTE-.pdfExplain in Detail DTE-DCE TransmissionSolutionFirstly the DTE-.pdf
Explain in Detail DTE-DCE TransmissionSolutionFirstly the DTE-.pdf
 
Explain the data component of social media information systems (SMIS).pdf
Explain the data component of social media information systems (SMIS).pdfExplain the data component of social media information systems (SMIS).pdf
Explain the data component of social media information systems (SMIS).pdf
 
Figure CWhich structure in the cell shown in Figure C above stores.pdf
Figure CWhich structure in the cell shown in Figure C above stores.pdfFigure CWhich structure in the cell shown in Figure C above stores.pdf
Figure CWhich structure in the cell shown in Figure C above stores.pdf
 
Coral reefs. How sensitive to changes in water temperature are coral .pdf
Coral reefs. How sensitive to changes in water temperature are coral .pdfCoral reefs. How sensitive to changes in water temperature are coral .pdf
Coral reefs. How sensitive to changes in water temperature are coral .pdf
 
•0.336 moles of a weak, monoproticacid added to a final volume of 2..pdf
•0.336 moles of a weak, monoproticacid added to a final volume of 2..pdf•0.336 moles of a weak, monoproticacid added to a final volume of 2..pdf
•0.336 moles of a weak, monoproticacid added to a final volume of 2..pdf
 
You are to simulate a dispatcher using a priority queue system in C+.pdf
You are to simulate a dispatcher using a priority queue system in C+.pdfYou are to simulate a dispatcher using a priority queue system in C+.pdf
You are to simulate a dispatcher using a priority queue system in C+.pdf
 
Why was the knowledge of macromolecules “structure” very important i.pdf
Why was the knowledge of macromolecules “structure” very important i.pdfWhy was the knowledge of macromolecules “structure” very important i.pdf
Why was the knowledge of macromolecules “structure” very important i.pdf
 
Why did the sovereign debt problem of Greece a country that accounts.pdf
Why did the sovereign debt problem of Greece a country that accounts.pdfWhy did the sovereign debt problem of Greece a country that accounts.pdf
Why did the sovereign debt problem of Greece a country that accounts.pdf
 
Which of the following could be the most likely cause of a superi.pdf
Which of the following could be the most likely cause of a superi.pdfWhich of the following could be the most likely cause of a superi.pdf
Which of the following could be the most likely cause of a superi.pdf
 
What is the theory of public debt managementSolution1. Sove.pdf
What is the theory of public debt managementSolution1. Sove.pdfWhat is the theory of public debt managementSolution1. Sove.pdf
What is the theory of public debt managementSolution1. Sove.pdf
 
This is a three part question. For each part the answer requires ide.pdf
This is a three part question. For each part the answer requires ide.pdfThis is a three part question. For each part the answer requires ide.pdf
This is a three part question. For each part the answer requires ide.pdf
 
Complete a personal SWOT analysis evaluating your understanding and .pdf
Complete a personal SWOT analysis evaluating your understanding and .pdfComplete a personal SWOT analysis evaluating your understanding and .pdf
Complete a personal SWOT analysis evaluating your understanding and .pdf
 

Recently uploaded

Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
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
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.arsicmarija21
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationAadityaSharma884161
 
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
 
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
 
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
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxsqpmdrvczh
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
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
 

Recently uploaded (20)

Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
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 🔝✔️✔️
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint Presentation
 
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
 
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
 
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
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptx
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
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
 

Write a program that accepts an arithmetic expression of unsigned in.pdf

  • 1. Write a program that accepts an arithmetic expression of unsigned integers in postfix notation and builds the arithmetic expression tree that represents that expression. From that tree, the corresponding fully parenthesized infix expression should be displayed and a file should be generated that contains the three address format instructions. This topic is discussed in the week 4 reading in module 2, section II-B. The main class should create the GUI shown below: Pressing the Construct Tree button should cause the tree to be constructed and using that tree, the corresponding infix expression should be displayed and the three address instruction file should be generated. The postfix expression input should not be required to have spaces between every token. Note in the above example that 9+- are not separated by spaces. The above example should produce the following output file containing the three address instructions: Add R0 5 9 Sub R1 3 R0 Mul R2 2 3 Div R3 R1 R2 Inheritance should be used to define the arithmetic expression tree. At a minimum, it should involve three classes: an abstract class for the tree nodes and two derived classes, one for operand nodes and another for operator nodes. Other classes should be included as needed to accomplish good object-oriented design. All instance data must be declared as private. You may assume that the expression is syntactically correct with regard to the order of operators and operands, but you should check for invalid tokens, such as characters that are not valid operators or operands such as 2a, which are not valid integers. If an invalid token is detected a RuntimeException should be thrown and caught by the main class and an appropriate error message should be displayed. Three Adddress Generator Enter Postfix Expression 359 2 3 Construct Tree Infix Expression ((3-(5 9))/ (2* 3 Solution #include #include #include #include #include struct TREE //Structure to represent a tree {
  • 2. char data; struct TREE *right,*left,*root; }; typedef TREE tree; /* Stack Using Linked List */ struct Stack //Structure to represent Stack { struct TREE *data; struct Stack *next,*head,*top; //Pointers to next node,head and top }; typedef struct Stack node; node *Nw; //Global Variable to represent node void initialize(node *&n) { n = new node; n -> next = n -> head = n -> top = NULL; } void create(node *n) { Nw = new node; //Create a new node Nw -> next = NULL; //Initialize next pointer field if(n -> head == NULL) //if first node { n -> head = Nw; //Initialize head n -> top = Nw; //Update top } } void push(node *n,tree *ITEM) { node *temp = n -> head;
  • 3. if(n -> head == NULL) //if First Item is Pushed to Stack { create(n); //Create a Node n -> head -> data = ITEM; //Insert Item to head of List n -> head = Nw; return; //Exit from Function } create(n); //Create a new Node Nw -> data = ITEM; //Insert Item while(temp -> next != NULL) temp = temp -> next; //Go to Last Node temp -> next = Nw; //Point New node n -> top = Nw; //Update top } node* pop(node *n) { node *temp = n -> head,*deleted; if(n -> top == NULL) //If the Stack is Empty { return NULL; } if(n -> top == n -> head) //If only one Item { deleted = n -> head; n -> head = n -> top = NULL; //Set head and top to Null return deleted; //Return deleted node } while(temp -> next != n -> top) temp = temp -> next; //move pointer temp to second last node
  • 4. temp -> next = NULL; //Second last node points to NULL deleted = n -> top; //Save topmost node n -> top = temp; //Update top return deleted; //Return deleted node } int Empty(node *nd) //function to check if the stack is empty or not { if(nd -> top == NULL) return 1; //empty else return 0; } /*Tree Section */ tree *New; void create() //Function to create a node of a tree { New = new tree; New -> left = NULL; New -> right = NULL; } void insert(tree *&t,char Item,int pass) //Function to insert item on a tree { if(t == NULL) //If tree doesn't exist { t = new tree; //make a node t -> data = Item; //insert item t -> left = NULL; //initialize left pointer t -> right = NULL; //initialize right pointer if(pass)
  • 5. t -> root = t; //initialize root return; //return from function } create(); New -> data = Item; } void preorder(tree *t) //Function to print tree in preorder { if(t != NULL) { cout << t -> data << ' '; preorder(t -> left); preorder(t -> right); } } void inorder(tree *t) //Function to print tree in inorder { if(t != NULL) { inorder(t -> left); cout << t -> data << ' '; inorder(t -> right); } } int isOperator(char ch) /* Main Program */ { if(ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '$') return 1; else return 0; } bool check(node *nd)
  • 6. { if(nd != NULL) return true; else return false; } float calculate(float opr1,float opr2,char oprator) { float value; if(oprator == '+') value = opr1 + opr2; if(oprator == '-') value = opr1 - opr2; if(oprator == '*') value = opr1 * opr2; if(oprator == '/') if(opr2 != 0) value = opr1 / opr2; if(oprator == '$') value = pow(opr1,opr2); return value; } float evaluate(tree *t) { float x,y,result; char ch[3]; if(t != NULL) { if(isOperator(t -> data)) { x = evaluate(t -> left); //go to left y = evaluate(t -> right); //go to right result = calculate(x,y,t -> data); //calculate
  • 7. return result; } else { ch[0] = t -> data; ch[1] = '0'; result = atof(ch); //convert to float return result; } } } int main() { char postfix[60]; cout << "Enter a valid Postfix Expression "; cout << "(in a single line, without spaces) "; int i = 0; while(postfix[i - 1] != ' ') postfix[i++] = getchar(); int len = i - 1,pass = true,valid = true; node *stk,*nd; //create a stack initialize(stk); tree *tr = NULL,*value; i = 0; while(i < len) //while there is data { if(!isOperator(postfix[i])) //if operand { create(); New -> data = postfix[i]; push(stk,New); //push address of tree node to stack }
  • 8. else //if operator { insert(tr,postfix[i],pass); //create a node of tree and insert operator if(pass) //if first pass { nd = pop(stk); valid = check(nd); if(!valid) break; value = nd -> data; //pop address tr -> right = value; //assign to left child nd = pop(stk); valid = check(nd); if(!valid) break; value = nd -> data; //pop address tr -> left = value; //assign to right child pass = false; //reset pass push(stk,tr); //push address to stack } else { nd = pop(stk); valid = check(nd); if(!valid) break; value = nd -> data; //pop address New -> right = value; //assign to left child nd = pop(stk); valid = check(nd); if(!valid) break; value = nd -> data; //pop stack New -> left = value; //assign to right child
  • 9. push(stk,New); //push address to stack } } i++; //update i } if(!Empty(stk)) { tr -> root = pop(stk) -> data; //Last data of stack is root of tree tr = tr -> root; } if(!Empty(stk)) //if stack is not empty valid = false; if(!valid) { cout << " The Given Postfix Expression is not Valid"; cout << " Check above Expression and try again..."; getch(); return 0; //exit from program } cout << " Infix : "; inorder(tr); //Inorder traversal gives Infix of expression cout << " Prefix : "; preorder(tr); //Postorder traversal gives Postfix of expression float result = evaluate(tr); cout << endl << "