Question

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 would have been (22+8). The problem is when I unmuted these lines, the evaluation doesn't work.

I'm using this online compiler: https://www.onlinegdb.com/online_c_compiler

#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 '(': return 1;

case '+': return 2;

case '-': return 2;

case '*': return 3;

case '/': return 3;

case '%': return 3; //modulo

case '^': return 4; //exponent

}

return -1;

}

int main ()

{

char infix[50];

  

printf("\nEnter an infix expression:\n");

scanf("%s", infix);

push('=');

  

char postfix[50];

infixToPostfix(infix, postfix);

  

postfixEvaluation(postfix);

  

return 0;

}

void infixToPostfix(char *infix, char *postfix){

  

char ch, elem;

int i=0, j=0;

  

for (i=0; infix[i] !='\0'; i++)

{

if (infix[i] == '(')

push(infix[i]);

  

else if (isalnum(infix[i]))

{

postfix[j++]=infix[i];

  

// if (infix[i+1] != '\0' && isalnum(infix[i+1]) !=0){ //This line check if there's another number aside

// postfix[j++]=infix[++i];

// }

// postfix[j++]=' '; //this line add an extra space

}

else if (infix[i] == ')')

{

while( s[top] != '(')

{

postfix[j++] = pop();

}

elem=pop();

}

else

{

while( pr(s[top]) >= pr(infix[i]) ){

postfix[j++] = pop();

}

push(infix[i]);

  

// postfix[j++]=' '; //This line separate the operators from operand

}

}

while ( s[top] != '=')

postfix[j++]=pop();

postfix[j]='\0';

  

printf("\n%s = %s", infix, postfix);

}

void postfixEvaluation(char *postfix){

  

int i=0, j=0, postfix_int[50];

  

while (top != -1)

pop();

  

int value=0, op1, op2;

  

for (i=0; postfix[i] != '\0'; i++)

{

  

if (isdigit(postfix[i]))

push(postfix[i]);

  

else {

op1 = pop() - '0';

op2 = pop() - '0';

switch (postfix[i]) {

case '+':

value = op2 + op1;

break;

case '-':

value = op2 - op1;

break;

case '*':

value = op2 * op1;

break;

case '/':

value = op2 / op1;

break;

case '%':

value = op2 % op1;

break;

case '^':

value = pow(op2, op1); // exponet math library

break;

}

push(value + '0');

}

}

printf(" = %d", pop() - '0');

}

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

PROBLEM IN THE CODE:

1.You have used a single dimensional char array and hence you can only store one char per a block in the array.

2.So,this requires including white spaces to differentiate multi digit numbers.But the problem in doing so is when we are creating a post fix expression,some times we pop operators out and again push another operator and sometimes we need to pop everything out until we get to a open bracket when we encounter a close bracket. In either of the cases,the spaces we used might get deleted and it is impossible to maintain uniformity in spaces in such cases.

3.So,using spaces is not helpful. Moreover,the code given doesn't work whenever it encounter a 3 digit number.So,it even does not work for single digit numbers. Eg: (9*9*9-7) gives an answer of -46 because 729 cannot simply be converted into a character by adding '0' as per the code.So,it does not work for such cases.

ALTERNATE SOLUTION:

1.Create an array of strings or create a 2 dimensional character array.and hence you can store each digit or operator in each line of 2 dimensional array or in each string of the string array.So,you don't need to use spaces and the rest process is same as the given code.And you can use the below code to convert a string to integer. Eg:'234' can be converted to 234.

int convert_int(char a[]) {
int c, sign, offset, n;

if (a[0] == '-') {
sign = -1;
}

if (sign == -1) {  
offset = 1;
}
else {
offset = 0;
}

n = 0;

for (c = offset; a[c] != '\0'; c++) {
n = n * 10 + a[c] - '0';
}

if (sign == -1) {
n = -n;
}

return n;
}

2.Create a data structure that consists of a string,a integer, a flag.

struct ele{
int no;
string value;
int flag;
};

and create a array of these structure.Use flag =0 to denote it is a integer and flag=1 to denote it is a character(for cases like +,-,*).In this way,you can simply do the required code.

And you can use the below code to take multiple digit input from a infix expression.The below code works in this way:

when it encounters a numbers it goes on until a non numerical character is encountered and store it in input and suing the above function it converts it to integer.Use the below code inside the for loop in your code.

char input[100];
int count1=0;
while(isalnum(infix[i+count1])){
input[count1]=infix[i+count1];
count1++;
}
i=i+count1-1;
input[count1]='\0';
printf("%s ",input);
int con_int=convert_int(input);
printf("%d\n",con_int);

To find error in matching brackets:This is simple.,use a for loop to go through the input and use a variable count(initially 0)and add 1 .whenever '(' is encountered and subtract by 1 if ')' is encountered.If the result is not 0,then there is an error.

Add a comment
Know the answer?
Add Answer to:
Help me to fix this code in C language. This code converts infix expressions to postfix and then evaluate the expression...
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 '(':...

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

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

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

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

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

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

  • 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