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 '(':...

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

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

  • In C programming Language Write a version of the infix-to-postfix conversion algorithm. Write a program that converts an...

    In C programming Language Write a version of the infix-to-postfix conversion algorithm. Write a program that converts an ordinary infix arithmetic expression (assume a valid expression is entered) with single-digit integers For Example: Infix expression (6 + 2) * 5 - 8 / 4 to a postfix expression is  62+5*84/- The program should read the expression into character array infix and use the stack functions implemented in this chapter to help create the postfix expression in character array postfix. The...

  • Write a java code to implement the infix to postfix algorithm as described below: Algorithm convertTo...

    Write a java code to implement the infix to postfix algorithm as described below: Algorithm convertTo Post fix ( infix) // Converts an infix expression to an equivalent postfix expression operatorStack = a new empty stack postfix = anew empty string while (infix has characters left to parse) nextCharacter =next nonblank character of infix switch (nextCharacter) { case variable: Append nextCharacter to postfix break case 'A' operatorStack.push (nextCharacter) break case '+ case '-' : case '*' : case '/' while...

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

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