Question

(9+3)*(8-5)/6*(3+8) in rpn expression in c++

(9+3)*(8-5)/6*(3+8) in rpn expression in c++

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

CODE:

#include<iostream>
#include<cctype>
#include<string>
#define MAX 20
using namespace std;
char S[MAX],top=-1;
void push(char ch)      //stack push operation
{
  
   top=top+1;
   S[top]=ch;
}
char pop()           //stack pop operation
{
   if(top==-1)
       return -1;
   else
       return S[top--];
}
int getWeight(char ch)      //method for getting precedence of operator
{
   if(ch=='(')
       return 0;
   if(ch=='-' || ch=='+')
       return 1;
   if(ch== '/' || ch== '*')
       return 2;      
}
int main()
{
   string str;     //declaring string for reading infix expression
   cout<<"Enter expression: ";
   getline(cin,str);    //reading expression from user
   cout<<"RPN expression is:"<<endl;
   for(int i=0;i<str.length();i++)
   {
       if(isalnum(str[i]))   //checking the character is alphanumeric or not
           push(str[i]);     //pushing character to stack
       else if(str[i]=='(') //if character is left paranthesis pushing character to stack
           push(str[i]);
       else if(str[i]==')')
       {
           while((str[i]=pop())!= '(') //poping stack until left paranthesis encountered
            {
               cout<<str[i];     //printing popped characters
           }
       }
       else
        {
           //if top of the stack is having heigher precendence than present operator
            while(getWeight(S[top])>=getWeight(str[i]))
           {
               cout<<pop();   //popping elements until top of the stack have lower presendence
           }   
            push(str[i]);      //pushing character to stack
        }          
   }
   while(top!=-1)    //popping remainging characters and printing them
    {
        cout<<pop();
    }
}

OUTPUT:

Enter expression: (9+3)*(8-5)/6* (3+8) RPN expression is: 93+85-*6/38+*

Add a comment
Know the answer?
Add Answer to:
(9+3)*(8-5)/6*(3+8) in rpn expression in c++
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