Question

In C language please: Having read a str infix such as: (7 - 3) / (2...

In C language please:

Having read a str infix such as: (7 - 3) / (2 + 2)

Convert from infix to postfix: 7 3 - 2 2 + /

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


ANSWER:-

#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)){
           postfix[j++]=ch;
       }else if(ch=='('){
           // if it open paranthesis, push it to stack
           push(ch);
       }else if(ch==')'){
           // if it is closing paranthesis, pop all the
           // numbers from stack and add it postfix
           while(s[top]!='('){
               postfix[j++]=pop();
           }
           top--;
       }else{
           /*
               if if is operator, if stack is empty or precedence of current operator is
               greater than precedence of top of the stack, then push it into stack.
               otherwise pop all the operators from stack until precedence of top of the stack is
               less than precedence of the current operator.
           */
           if(top==-1||precede(ch)>precede(s[top])){
               push(ch);
           }else{
               while(precede(ch)<=precede(s[top])&&top!=-1){
                   postfix[j++]=pop();
               }
               push(ch);
           }
       }
   }
   while(top!=-1){
       postfix[j++]=pop();
   }
   postfix[j]='\0';
   printf("Infix expression = %s\nPostfix expression = %s",infix,postfix);
}
void push(char a)
{
   s[++top]=a;
}
char pop(){
   return s[top--];
}
int precede(char a){
   if(a=='('||a==')'){
       return 1;
   }else if(a=='-'||a=='+'){
       return 2;
   }else if(a=='%'||a=='/'||a=='*'){
       return 3;
   }
}

OUTPUT:-

NOTE:- If you have any doubts, please comment below. Please give positive rating. THANK YOU!!!

Add a comment
Know the answer?
Add Answer to:
In C language please: Having read a str infix such as: (7 - 3) / (2...
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
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