Question

I need assistance with this code. Is there any way I can create this stack class (dealing with infix to postfix then postfix evaluation) without utilizing <stdio.h> and <math.h>?

____________________________________________________________________________________________

C++ Program:

#include <iostream>
#include <string>
#include <stdio.h>
#include <math.h>

using namespace std;

//Stack class
class STACK
{
private:
char *str;
int N;

public:
//Constructor
STACK(int maxN)
{
str = new char[maxN];
N = -1;
}

//Function that checks for empty
int empty()
{
return (N == -1);
}

//Push operation
void push(char val)
{
N = N + 1;
str[N] = val;
}

//Pop Operation
char pop()
{
char val;
val = str[N];
N = N-1;
return val;
}

char top()
{
return str[N];
}
};

int preced(char ch)
{
if(ch == '+' || ch == '-')
{
return 1;
}
else if(ch == '*' || ch == '/')
{
return 2;
}
else if(ch == '^')
{
return 3;
}
else
{
return 0;
}
}

//Function that converts infix to postfix
char* InfixToPostfix(string expr, int len)
{
int i, j;

char *postfix;

//Stack object
STACK postfixStack(len);

//Allocating memory
postfix = (char*)malloc(sizeof(char)*len);

//Set j to 0
j = 0;

//Iterating over string
for (i = 0; i < len; i++)
{
//If closing braces is encountered
if (expr[i] == ')')
{
//Popping element
postfix[j] = postfixStack.pop();
j++;
}

//If operator
else if ((expr[i] == '+') || (expr[i] == '*') || (expr[i] == '^') || (expr[i] == '-') || (expr[i] == '/'))
{
if((preced(expr[i]) > preced(postfixStack.top())))
{
postfixStack.push(expr[i]);
}
else
{
while( (!postfixStack.empty()) && (preced(expr[i]) <= preced(postfixStack.top())) )
{
//Placing operand on postfix expression string
postfix[j] = postfixStack.pop();
j++;
}
postfixStack.push(expr[i]);
}
}

//If Operand
else if ((expr[i] >= '0') && (expr[i] <= '9'))
{
//Placing operand on postfix expression string
postfix[j] = expr[i];
j++;
}
}

//Popping all elements from stack
while(!postfixStack.empty())
{
//Writing to postfix expression
postfix[j] = postfixStack.pop();
j++;
}

//Set string termination character
postfix[j]='\0';

return postfix;
}

//Function that evaluates postfix expression
double evaluatePostFix(char* postfix)
{
//Finding length
int len = strlen(postfix);
int a, b;

//Stack to evaluate postfix expression
STACK postfixStack(len);

//Iterating over expression
for (int i = 0; i < len; i++)
{
//If operator
if (postfix[i] == '+' || postfix[i] == '^' || postfix[i] == '-' || postfix[i] == '*' || postfix[i] == '/')
{
//Popping two operands
a = (postfixStack.pop()) - '0';
b = (postfixStack.pop()) - '0';

//Calculating corresponding operation
switch(postfix[i])
{
case '+': postfixStack.push((a+b) + '0'); break;
case '-': postfixStack.push((a-b) + '0'); break;
case '*': postfixStack.push((a*b) + '0'); break;
case '/': postfixStack.push((a/b) + '0'); break;
case '^': postfixStack.push((pow(double(a), double(b))) + '0'); break;
}
}

//If operand
else if ((postfix[i] >= '0') && (postfix[i] <= '9'))
{
//Storing operand into stack
postfixStack.push(postfix[i]);
}
}

//Returning result
return (postfixStack.pop()) - '0';
}


//Main function
int main()
{
double result;
int len;
string expr;
char* postfix;

//Reading expression
cout<<"\n Input Infix expression: ";
getline(cin, expr);

//Finding length
len = strlen(expr.c_str());

//Allocating memory
postfix = (char*)malloc(sizeof(char)*len);

//Converting Infix to Postfix expression
postfix = InfixToPostfix(expr, len);

//Printing postfix expression
cout<< "\n Postfix Expression: " << postfix << " \n";

//Evaluating postfix expression
result = evaluatePostFix(postfix);

cout << "\n Result: " << result << " \n\n";

return 0;
}

____________________________________________________________________________________________

Sample Run:

CTClinfixPostfix)bin\DebuginfixPostfix.exe Input Infix expression: 5*2+3 Postfix Expression: 52*3+ Result: 13 Process returne

0 0
Add a comment Improve this question Transcribed image text
Answer #1

C++ Code to Convert Infix expression to Postfix expression using Stack and Evaluate Postfix expression

CODE:

#include<iostream>
#include<stack>
#include<string>
#include<cmath>


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 has higher precedence(char operator1, char operator2);

// Function to verify whether a character is an 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);

float scanNum(char ch) {
int value;
value = ch;
return float(value-'0'); //return float from character
}
int isOperator(char ch) {
if(ch == '+'|| ch == '-'|| ch == '*'|| ch == '/' || ch == '^')
return 1; //character is an operator
return -1; //not an operator
}
int isOperand(char ch) {
if(ch >= '0' && ch <= '9')
return 1; //character is an operand
return -1; //not an operand
}
float operation(int a, int b, char op) {
//Perform operation
if(op == '+')
return b+a;
else if(op == '-')
return b-a;
else if(op == '*')
return b*a;
else if(op == '/')
return b/a;
else if(op == '^')
return pow(b,a); //find b^a
else
return 0; //return negative infinity
}
float postfixEval(string postfix) {
int a, b;
stack<float> stk; // Declaring a Stack
string::iterator it;
for(it=postfix.begin(); it!=postfix.end(); it++) {
//read elements and perform postfix evaluation
if(isOperator(*it) != -1) {
a = stk.top();
stk.pop();
b = stk.top();
stk.pop();
stk.push(operation(a, b, *it));
}else if(isOperand(*it) > 0) {
stk.push(scanNum(*it));
}
}
return stk.top();
}

int main()
{
string expression;
cout<<"\nEnter Infix Expression: ";
getline(cin,expression);
cout<<"\n";
string postfix = InfixToPostfix(expression);
cout<<"PostFixExpression = "<<postfix <<" \n";
cout<<"\n";
cout << "The result is: "<<postfixEval(postfix);
}

// Function to evaluate Postfix expression and return output
string InfixToPostfix(string expression)
{
// Declaring a Stack from Standard template library in C++.
stack<char> 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 an english letter or a 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 an 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 a weight of an operator. An operator with a 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:

Enter Infix Expression: 5*2+3 PostFixExpression52+3+ The result is: 13

Please give Thumbsup...

Add a comment
Know the answer?
Add Answer to:
I need assistance with this code. Is there any way I can create this stack class (dealing with infix to postfix then postfix evaluation) without utilizing <stdio.h> and <math.h>? ________...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • This code in C converts infix to postfix and evaluates it. The problem is that it...

    This code in C converts infix to postfix and evaluates it. The problem is that it only evaluates one digit expressions. I need to fix it so that it can evaluate 2 digits expressions as well. #include <stdio.h> #include <ctype.h> #include <string.h> #include <math.h> #define SIZE 100 char s[SIZE]; int top=-1; void infixToPostfix(char *infix, char *postfix); void postfixEvaluation(char *postfix); void push(char elem){ s[++top]=elem; } char pop(){ return(s[top--]); } int pr(char elem){ // Order of precedence switch (elem) { case '(':...

  • Help me to fix this code in C language. This code converts infix expressions to postfix and then evaluate the expression...

    Help me to fix this code in C language. This code converts infix expressions to postfix and then evaluate the expression. Right now, it works with single digits. I need to modify it so that it can evaluate expressions with also 2 digits, example: (60+82)%72. Additionally I need to display an error when the parenthesis don't match like (89+8(. I have muted some line that would print the postfix expression with a space like: 22 8 + when the input...

  • Finish function to complete code. #include <stdio.h> #include <stdlib.h> #include<string.h> #define Max_Size 20 void push(char S[],...

    Finish function to complete code. #include <stdio.h> #include <stdlib.h> #include<string.h> #define Max_Size 20 void push(char S[], int *p_top, char value); char pop(char S[], int *p_top); void printCurrentStack(char S[], int *p_top); int validation(char infix[], char S[], int *p_top); char *infix2postfix(char infix[], char postfix[], char S[], int *p_top); int precedence(char symbol); int main() { // int choice; int top1=0; //top for S1 stack int top2=0; //top for S2 stack int *p_top1=&top1; int *p_top2=&top2; char infix[]="(2+3)*(4-3)"; //Stores infix string int n=strlen(infix); //length of...

  • i want similar for this code to solve two questions : 1- Write a program to...

    i want similar for this code to solve two questions : 1- Write a program to convert a postfix expression to infix expression 2-Write a program to convert an infix expression to prefix expression each question in separate code ( so will be two codes ) #include <iostream> #include <string> #define SIZE 50 using namespace std; // structure to represent a stack struct Stack {   char s[SIZE];   int top; }; void push(Stack *st, char c) {   st->top++;   st->s[st->top] = c;...

  • Help with c++ program. The following code takes an infix expression and converts it to postfix....

    Help with c++ program. The following code takes an infix expression and converts it to postfix. When I compile the code it returns "Segmentation fault". However I don't know what causes this. #include #include #include using namespace std; template class Stack { public: Stack();//creates the stack bool isempty(); // returns true if the stack is empty T gettop();//returns the front of the list void push(T entry);//add entry to the top of the stack void pop();//remove the top of the stack...

  • Im writing a method to evaluate a postfix expression. Using my own stack class. Here is my code but I keep getting a classcastexception where it says java.lang.Character cannot be cast to java.lang,In...

    Im writing a method to evaluate a postfix expression. Using my own stack class. Here is my code but I keep getting a classcastexception where it says java.lang.Character cannot be cast to java.lang,Integer. Im not sure how to fix this. public class Evaluator { public static void evaluatePost(String postFix)    {        LinkedStack stack2 = new LinkedStack();        int val1;        int val2;        int result;        for(int i = 0; i < postFix.length(); i++)        {            char m = postFix.charAt(i);            if(Character.isDigit(m))            {                stack2.push(m);            }            else            {               ...

  • I'm getting errors that i can't figure out. I need help fixing them. particularly focus on...

    I'm getting errors that i can't figure out. I need help fixing them. particularly focus on the errors they are highlighted in bold on the list code: #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <ctype.h> #include "stack.h" #include "booleanEvaluation.h" #include "booleanWithError.h" /* evaluatePostfix * input: a postfix expression * output: T, F, or E * * Uses a stack to evaluates the postfix expression and returns the result as a string where "T" denotes true and "F" denotes...

  • Return a method as an expression tree Hi guys. I need to return a method as...

    Return a method as an expression tree Hi guys. I need to return a method as an expression tree, it's currently returning null. public static ExpressionTree getExpressionTree(String expression) throws Exception {       char[] charArray = expression.toCharArray(); Node root = et.constructTree(charArray); System.out.println("infix expression is"); et.inorder(root); return et; } In the above method, et needs to have a value. -- Take a look at the complete class below. Kindly assist. ; public class ExpressionTree extends BinaryTree { private static final String DELIMITERS...

  • Infix Expression Evaluator For this project, write a C program that will evaluate an infix expression. The algorithm REQ...

    Infix Expression Evaluator For this project, write a C program that will evaluate an infix expression. The algorithm REQUIRED for this program will use two stacks, an operator stack and a value stack. Both stacks MUST be implemented using a linked list. For this program, you are to write functions for the linked list stacks with the following names: int isEmpty (stack); void push (stack, data); data top (stack); void pop (stack); // return TRUE if the stack has no...

  • Infix Expression Evaluator For this project, write a C program that will evaluate an infix expression. The algorithm REQ...

    Infix Expression Evaluator For this project, write a C program that will evaluate an infix expression. The algorithm REQUIRED for this program will use two stacks, an operator stack and a value stack. Both stacks MUST be implemented using a linked list. For this program, you are to write functions for the linked list stacks with the following names: int isEmpty (stack); void push (stack, data); data top (stack); void pop (stack); // return TRUE if the stack has no...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT