C++ Program to evaluate a postfix expression
C++ Program to evaluate a postfix expression.
/************************************************************** Author: Arun Vishnu M V Web: www.arunmvishnu.com Description: C++ Program to evaluate a postfix expression. ***************************************************************/ #include; // For isdigit() #include ; // For clrscr() #include ; // For exit() #include ; // For gets() #include ; // To find the power # define MAX_STACK 150 class stacks { int value,item,top; int stack[MAX_STACK]; public: stacks()// Constructor { top=(-1); } void push(float); float pop(); }; // Function to PUSH the vale to the stack void stacks::push(float value) { if(top==MAX_STACK) { cout<<"Stack is full!\nOverflow!"; getch(); exit(0); } else top++; stack[top]=value; } // Function to POP the value from the stack float stacks::pop() { if(top<0) { cout<<"Stack is empty!\nUnderflow!"; getch(); exit(0); } else item=stack[top]; top--; return(item); } // MAIN Function int main() { clrscr(); stacks stk1; //Object of stack char expression[150],oper_string[8],ch; oper_string[0]='\0'; float value,operand1,operand2,val; int pos=0,p=0,iv; cout<<"Enter a postfix expression: "; gets(expression); while(expression[pos]!='\0') { ch=expression[pos]; //Converting the operaand string to float if((isspace(ch)) &&(oper_string[0]!='\0')) { oper_string[p]='\0'; stk1.push((atof(oper_string))); oper_string[0]='\0'; p=0; } else if(ch==' ') { pos++; continue; } else if((isdigit(ch))) { oper_string[p]=ch; p++; } // End of conversion else { operand1=stk1.pop(); operand2=stk1.pop(); switch(ch) { case '+': val=operand2+operand1; break; case '-': val=operand2-operand1; break; case '*': val=operand2*operand1; break; case '/': val=operand2/operand1; break; case '^': val=pow(operand2,operand1); break; default: break; } stk1.push(val); } pos++; } cout<<"\nValue= "<< stk1.pop(); getch(); return(0); }
Recent Comments