Question

This code in c evaluates a mathematical expression and checks that it is correctly balanced, then...

This code in c evaluates a mathematical expression and checks that it is correctly balanced, then converts the expression to its postfix form (This part works). Now I need to evaluate the postfix expression with a function. I've been compiling it using dev c ++.

#include
#include
#define SIZE 20
#include
int profundidad(char expresion[]);
int prec(char op1, char op2);
void postfijo(char expresion[]);
char funcion[SIZE];
float convierte(char car);
float resultado(float opnd1, char symb, float opnd2);
float evaluar(char expresion[]);
#define SIZE 20

char dato;

struct Nodo
{
char info;
struct Nodo* sig;
};

typedef struct Nodo nodo;
nodo* raiz = NULL;

int isEmpty()
{
if (raiz == NULL)
return 1;
else
return 0;
}

void push(char dato)
{
nodo* nuevo = NULL;
if (isEmpty())
{
nodo* nuevo = NULL;
nuevo = (nodo*)malloc(sizeof(nodo));
nuevo->info = dato;
nuevo->sig = NULL;
raiz = nuevo;
}

else
{
nuevo = (nodo*)malloc(sizeof(nodo));
nuevo->info = dato;
nuevo->sig = raiz;
raiz = nuevo;
}


}


char pop(void) {

nodo* recorre = NULL, * elimina = NULL;
char dato;
if (!isEmpty())
{
elimina = raiz;
dato = elimina->info;
raiz = raiz->sig;
free(elimina);
}
return dato;
}

char stackTop()
{
return raiz->info;
}

void imprimePila()
{
nodo* recorre = raiz;
while (recorre != NULL)
{
printf("%c, ", recorre->info);
recorre = recorre->sig;
}
printf("\n");
}

int main()
{

printf("enter a mathematical expression: \n");
gets(funcion);

if (profundidad(funcion) == 1)
{
printf("the expression is balanced\n");
printf("infix: %s\n", funcion);
postfijo(funcion);
printf("the function evaluated is:%f\n", evaluar(funcion));


}
else
{
printf("the expression is not balanced\n");
}


system("pause");
return 0;

}

int profundidad(char expresion[])
{
char symb, temp;
int i = 0;

while (expresion[i] != '\0')
{
symb = expresion[i];

if (symb == '(' || symb == '[' || symb == '{')
{
push(symb);
}
if (symb == ')' || symb == ']' || symb == '}')
{
if (isEmpty())
{
return 0;
}

else
{
temp = pop();

if (temp == '(')
{
if (symb != ')')
{
return 0;
}
}
else if (temp == '{')
{
if (symb != '}')
{
return 0;
}
}

else if (temp == '[')
{
if (symb != ']')
{
return 0;
}
}
}
}
i++;
}

if (!isEmpty())
{
return 0;
}
else
{
return 1;
}

}


int prec(char op1, char op2) {

int jer1 = 0;
int jer2 = 0;
switch (op1) {

case '(':
jer1 = 0;
break;
case '{':
break;
jer1 = 0;
break;
case '[':
jer1 = 0;
break;
case ')':
jer1 = 3;
break;
case '}':
jer1 = 3;
break;
case ']':
jer1 = 3;
break;
case '^':
jer1 = 3;
break;
case '*':
jer1 = 2;
break;
case '/':
jer1 = 2;
break;
case '+':
jer1 = 1;
break;
case '-':
jer1 = 1;
break;
default:
break;
}
switch (op2)
{
case '(':
jer2 = 3;
break;
case '[':
jer2 = 3;
break;
case '{':
break;
jer2 = 3;
break;
case ')':
jer2 = 1;
break;
case '}':
jer2 = 1;
break;
case ']':
jer2 = 1;
break;
case '^':
jer2 = 3;
break;
case '*':
jer2 = 2;
break;
case '/':
jer2 = 2;
break;
case '+':
jer2 = 1;
break;
case '-':
jer2 = 1;
break;
default:
break;
}
if (jer1 >= jer2)
{
return 1;
}
else
{
return 0;
}
}

void postfijo(char expresion[])
{
int i = 0, j = 0;
char symb = '\0', topsymb = '\0';
char postfijo[SIZE];
while (expresion[i] != '\0')
{
symb = expresion[i];
if ((symb != '+') && (symb != '-') && (symb != '*') && (symb != '/') && (symb != '^') && (symb != '(') && (symb != ')') && (symb != '[') && (symb != ']') && (symb != '{') && (symb != '}'))
{
postfijo[j] = symb;
j++;
}
else
{
while (!isEmpty() && prec(stackTop(), symb))
{
topsymb = pop();
postfijo[j] = topsymb;
j++;
}
if (isEmpty() || (symb != ')' && symb != '}' && symb != ']'))
{
push(symb);
}
else
{
topsymb = pop();
}

}
i++;
}
while (!isEmpty())
{
topsymb = pop();
postfijo[j] = topsymb;
j++;
}

printf("Postfix: %s\n", postfijo);
}

I need to create a function to evaluate the postfix expression

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

Function To Evaluate Postfix Expression

 struct Stack { int top; unsigned capacity; int* array; }; // Stack Operations struct Stack* createStack( unsigned capacity ) { struct Stack* stack = (struct Stack*) malloc(sizeof(struct Stack)); if (!stack) return NULL; stack->top = -1; stack->capacity = capacity; stack->array = (int*) malloc(stack->capacity * sizeof(int)); if (!stack->array) return NULL; return stack; } int isEmpty(struct Stack* stack) { return stack->top == -1 ; } char peek(struct Stack* stack) { return stack->array[stack->top]; } char pop(struct Stack* stack) { if (!isEmpty(stack)) return stack->array[stack->top--] ; return '$'; } void push(struct Stack* stack, char op) { stack->array[++stack->top] = op; } // The main function that returns value of a given postfix expression int evaluatePostfix(char* exp) { // Create a stack of capacity equal to expression size struct Stack* stack = createStack(strlen(exp)); int i; // See if stack was created successfully if (!stack) return -1; // Scan all characters one by one for (i = 0; exp[i]; ++i) { // If the scanned character is an operand (number here), // push it to the stack. if (isdigit(exp[i])) push(stack, exp[i] - '0'); // If the scanned character is an operator, pop two // elements from stack apply the operator else { int val1 = pop(stack); int val2 = pop(stack); switch (exp[i]) { case '+': push(stack, val2 + val1); break; case '-': push(stack, val2 - val1); break; case '*': push(stack, val2 * val1); break; case '/': push(stack, val2/val1); break; } } } return pop(stack); } 

Int this Function You will Pass Your Character String to evaluatePostfix and it will return You the evaluated Result.

Add a comment
Know the answer?
Add Answer to:
This code in c evaluates a mathematical expression and checks that it is correctly balanced, then...
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 '(':...

  • 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...

  • 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...

  • Given the following C code. Develop a evaluate post fix function that calculates the converted post...

    Given the following C code. Develop a evaluate post fix function that calculates the converted post fix. #include <stdio.h> #include <ctype.h> #define max 10 char s[100]; int top=-1; void push(char); char pop(); int precede(char); main(){    char infix[100],postfix[100],ch;    int i=0,j=0;    // Read infix expression from user    printf("Enter infix expression:");    scanf("%s",infix);    // evaluate each char in infix expression    while((ch=infix[i++])!='\0'){        // if it is number, add it to postfix expression        if(isalnum(ch)){   ...

  • Convert infix to postfix, and evaluate postfix using custom Stack created using a singly linked list....

    Convert infix to postfix, and evaluate postfix using custom Stack created using a singly linked list. This is only supposed to use THAT method, calling a normal Stack will give me a zero. I do have the conversion to postfix, but there may be error in there. But the main problem currently is the evaluation of postfix. I keep getting an error that I made for an empty stack, which I will include. For testing it is only supposed to...

  • 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 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;...

  • 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>? ________...

    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...

  • Fix the errors in C code #include <stdio.h> #include <stdlib.h> void insertAt(int *, int); void Delete(int...

    Fix the errors in C code #include <stdio.h> #include <stdlib.h> void insertAt(int *, int); void Delete(int *); void replaceAt(int *, int, int); int isEmpty(int *, int); int isFull(int *, int); void removeAt(int *, int); void printList(int *, int); int main() { int *a; int arraySize=0,l=0,loc=0; int choice; while(1) { printf("\n Main Menu"); printf("\n 1.Create list\n 2.Insert element at particular position\n 3.Delete list.\n4. Remove an element at given position \n 5.Replace an element at given position\n 6. Check the size of...

  • URGENT. Need help editing some C code. I have done most of the code it just...

    URGENT. Need help editing some C code. I have done most of the code it just needs the following added: takes an input file name from the command line; opens that file if possible; declares a C struct with three variables; these will have data types that correspond to the data types read from the file (i.e. string, int, float); declares an array of C structs (i.e. the same struct type declared in point c); reads a record from the...

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