C++ program – evaluate an expression entered in postfix form

by Nideesh C on April 14, 2011 · 0 comments

in C++




#include <iostream.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
const int MAX = 50 ;
class postfix
{
	private :
 
		int stack[MAX] ;
		int top, nn ;
		char *s ;
	public :
		postfix( ) ;
		void setexpr ( char *str ) ;
		void push ( int item ) ;
		int pop( ) ;
		void calculate( ) ;
		void show( ) ;
} ;
postfix :: postfix( )
{
	top = -1 ;
}
void postfix :: setexpr ( char *str )
{
	s = str ;
}
void postfix :: push ( int item )
{
	if ( top == MAX - 1 )
		cout << endl << "Stack is full" ;
	else
	{
		top++ ;
		stack[top] = item ;
	}
}
int postfix :: pop( )
{
	if ( top == -1 )
	{
		cout << endl << "Stack is empty" ;
		return NULL ;
	}
	int data = stack[top] ;
	top-- ;
	return data ;
}
void postfix :: calculate( )
{
	int n1, n2, n3 ;
	while ( *s )
	{
		if ( *s == ' ' || *s == '\t' )
		{
			s++ ;
			continue ;
		}
		if ( isdigit ( *s ) )
		{
			nn = *s - '0' ;
			push ( nn ) ;
		}
		else
		{
			n1 = pop( ) ;
			n2 = pop( ) ;
			switch ( *s )
			{
				case '+' :
					n3 = n2 + n1 ;
					break ;
				case '-' :
					n3 = n2 - n1 ;
					break ;
				case '/' :
					n3 = n2 / n1 ;
					break ;
				case '*' :
					n3 = n2 * n1 ;
					break ;
				case '%' :
					n3 = n2 % n1 ;
					break ;
				case '$' :
					n3 = pow ( n2 , n1 ) ;
					break ;
				default :
					cout << "Unknown operator" ;
					exit ( 1 ) ;
			}
 
			push ( n3 ) ;
		}
		s++ ;
	}
}
void postfix :: show( )
{
	nn = pop ( ) ;
	cout << "Result is: " << nn ;
}
 
void main( )
{
	char expr[MAX] ;
	cout << "\nEnter postfix expression to be evaluated : " ;
	cin.getline ( expr, MAX ) ;
	postfix q ;
	q.setexpr ( expr ) ;
	q.calculate( ) ;
	q.show( ) ;
}



Not Satisfied ? Just search & get the result

Related Posts Plugin for WordPress, Blogger...
Be Sociable, Share!

Related posts:

  1. C++ program to implement Stack using Formula Based Representation
  2. C program to implement stack. Stack is a LIFO data strcuture LIFO – Last in First Out Perform PUSH(insert operation), POP(Delete operation) and Display stack
  3. C++ program to implement stack using Linked List
  4. Sample – Program to enter an integer and output it in the reversed form.
  5. C program to evaluate the given polynomial P(x)=AnXn + An-1Xn-1 + An-2Xn-2+… +A1X + A0, by reading its coefficients into an array. [Hint:Rewrite the polynomial as P(x) = a0 + x(a1+x(a2+x(a3+x(a4+x(...x(an-1+xan)))) and evaluate the function starting from the inner loop]

Leave a Comment

Previous post:

Next post: