Question

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

Dear student,

The way you have implemented this program it wont work for 2 or more digit numbers.

You can use any of the below two code both are written by me.

i would recommend you to use Code 1

Code 1

#include<stdio.h>
#include<string.h>
#include<math.h>
#include<stdlib.h>
#include<ctype.h>
#define SPACE ' '
#define TAB '\t'
#define MAX 100
char infix[MAX], postfix[MAX];
int stack[MAX];
int top;

void push(int symbol)
{
   if(top>MAX)
   {
       printf("Stack overflow\n");
       exit(1);
   }
   stack[++top]=symbol;
}
//This function returns the priority of the operator
int priority(char symbol)
{
   switch(symbol)
   {
   case '(':
       return 0;
   case '+':
   case '-':
       return 1;
   case '*':
   case '/':
   case '%':
       return 2;
   case '^':
       return 3;
   default :
       return 0;
   }
}/*End of priority()*/
//This function is used to check to see is the char is a space
int white_space(char symbol)
{
   if( symbol == SPACE || symbol == TAB )
       return 1;
   else
       return 0;
}
int isEmpty()
{
   if(top==-1)
       return 1;
   else
       return 0;
}
long int pop()
{
   return (stack[top--]);
}
void intopost()
{
   int i,p=0,flag=0;
   char next;
   char symbol;
   for(i=0;i<strlen(infix);i++)
   {
       symbol=infix[i];
       if(!white_space(symbol))
       {
           switch(symbol)
           {
           case '(':
               push(symbol);
               break;
           case ')':
               while((next=pop())!='(')
                   postfix[p++] = next;
               break;
           case '+':
           case '-':
           case '*':
           case '/':
           case '%':
           case '^':
               while( !isEmpty( ) && priority(stack[top])>= priority(symbol) )
               {
                   postfix[p++]=' ';
                   postfix[p++]=pop();
               }
               push(symbol);
               break;
           case '\n':
               break;
           default: /*if an operand comes*/
               postfix[p++]=symbol;
               flag=1;
           }
           if(flag != 1)
               postfix[p++]=' ';
           flag=0;
       }
   }
   while(!isEmpty( ))
   {
       postfix[p++]=pop();
       postfix[p++]=' ';
   }
   postfix[p]='\0'; /*End postfix with'\0' to make it a string*/
}/*End of intopost()*/

long int eval()
{
   int temp1,temp2;
   int a,b,temp,result;
   unsigned int i;
   for(i=0;i<strlen(postfix);i++)
   {
       if(isalnum(postfix[i]))
       {
           temp1=postfix[i]-'0';
           while(isalnum(postfix[i+1]))
           {
               i++;
               temp2=postfix[i]-'0';
               temp1=temp1*10+temp2;
           }
           push(temp1);
       }
       else if(postfix[i] == 32)
       {
       }
       else
       {
           a=pop();
           b=pop();
           switch(postfix[i])
           {
           case '+':
               temp=b+a; break;
           case '-':
               temp=b-a;break;
           case '*':
               temp=b*a;break;
           case '/':
               temp=b/a;break;
           case '%':
               temp=b%a;break;
           case '^':
               temp=pow(b,a);
           }
           push(temp);
       }
   }
   result=pop();
   return result;
}/*End of eval */
int main()
{
   //Right here I declare the int value to be used to display the evaluated postix number
   int value;
   //set top to -1 for the stack
   top=-1;
   //here is where the program prints and receives an input from the user
   printf("Please input your infix expression: ");
   fgets(infix,MAX,stdin);
   //Right here is where the program takes the infix and converts it over to a postfix then prints out what the postfix expression is
   intopost();
   printf("Your infix to postfix expression is: %s\n",postfix);
   //These last two lines is where the the int value is set to equal what the funct eval() evaluated
   value=eval();
   printf("The evaluated postfix expression is: %d\n",value);
}

Screenshot of output:

Code 2

#include<stdio.h>
#include<ctype.h>

char stack[100];
int top = -1;
int eval_top = -1;
int eval_stack[100];

void push(char x) // Push char into stack
{
   stack[++top] = x;
}
char pop() // Pop char to top of stack
{
   if (top == -1)
       return -1;
   else
       return stack[top--];
}

/* functions for evaluation of postfix expression */
// push function
void eval_push(int x) { // Find push result
   eval_stack[++eval_top] = x;
}
// pop function
int eval_pop() { // Find pop result
   if (eval_top == -1) {
       return -1;
   } else {
       return eval_stack[eval_top--];
   }
}

int priority(char x) // check priority order
{
   if (x == '(')
       return 0;
   if (x == '+' || x == '-')
       return 1;
   if (x == '*' || x == '/')
       return 2;
}
// function to evaluate the postfix expression
void EvalPostfix(char postfix[]) {
   int temp1,temp2;
   int A, B;
   int val;
   char ch;
   int i;

   //find postfix
   for (i = 0; postfix[i] != ')'; i++) {
       ch = postfix[i];
       if (isdigit(ch))
       {
           temp1=ch - '0';
           i++;
           while(postfix[i] != ' ')
           {
               ch = postfix[i];
               temp2=ch - '0';
               temp1 = temp1 * 10 + temp2;
               i++;
           }
           eval_push(temp1);

       }
       else if (ch == '+' || ch == '-' || ch == '*' || ch == '/') {

           A = eval_pop();
           B = eval_pop();

           switch (ch)
           {
           case '*':
               val = B * A;
               break;

           case '/':
               val = B / A;
               break;

           case '+':
               val = B + A;
               break;

           case '-':
               val = B - A;
               break;
           }


           eval_push(val);//send value on top of stack
       }
   }
   printf("\n Result: %d \n", eval_pop());
}

int main()
{
   int i = 0;
   int j = 0;
   char * e, x;
   char postfix[100]; // store postfix for later evaluation
   char exp[100];
   printf("Infix expression : ");
   scanf("%s", exp); // asking the user to enter the infix expression
   printf("Postfix expression: ");
   while ( exp[j] != '\0')
   {
       if (isalnum( exp[j]))
       { // if character is alphabet or number , it is printed
           while(isalnum(exp[j]))
           {
               printf("%c",exp[j]);
               postfix[i++] = exp[j];
               j++;
           }
           j--;
       }
       else if ( exp[j] == '(') // if it is open parenthesis, it is pushed into the stack without any priority
           push( exp[j]);
       else if ( exp[j] == ')') // if it is closed parenthesis , pop the elements in the stack and print them until the we see ( symbol
       {
           while ((x = pop()) != '(')
           {
               printf("%c", x);
               postfix[i++] = x;
           }
       }
       else // if character is symbol like +, -, *, / then based on their priority character is pushed if it high priority otherwise high priority symbols are popped and it is pushed
       {
           while (priority(stack[top]) >= priority(exp[j])) {
               x = pop();
               printf("%c", x);
               postfix[i++] = x;
           }
           push(exp[j]);
       }
       printf(" ");
       postfix[i++] = ' ';
       j++;
   }
   while (top != -1) // printing remaining elements in the stack
   {
       x = pop();
       printf("%c", x);
       postfix[i++] = x;
   }
   postfix[i] = ')'; // this is to add at the end for detecting end by the evaluation function
   EvalPostfix(postfix);
}

Screenshot of output

If you have any doubt please comment below also don't forget to hit the thumbs up button thank you:)

Add a comment
Know the answer?
Add Answer to:
This code in C converts infix to postfix and evaluates it. The problem is that it...
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
  • 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...

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

  • The code below accepts and evaluates an integer expression with the following operators: +, _, *,...

    The code below accepts and evaluates an integer expression with the following operators: +, _, *, and /. Your task is to modify it to include the % remainder operator that has the same precedence as * and /. No need to rewrite the entire program, just insert the needed statements. import java.util.Stack; public class EvaluateExpression { public static void main(String[] args) {     // Check number of arguments passed     if (args.length != 1) {       System.out.println(         "Usage:...

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

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

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

  • 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