Stack Expression
      In this program a stack is used for evaluating an expression and stating if it is valid or not. A stack is a collection of items in Lifo order.
/*
	* This is a program on stack using C++ where u can evaluate wether an
	  expression has is valid or not

	* The are two important points to be kept in mind
		1. Your program should evaluate equal no. of right and left
		   braces i.e. left braces -  right brace = 0.
		2. For each left brace there is a right brace i.e.
		   for each opening brace there is ac losing brace.


	* Stack is an ordered collection of items into which new items
	  may be inserted and deletd at one end , called the TOP of the stack.

	* We can only delete or insert items from the top that is why it is
	  referred to as last in first out ( LIFO ). The last item enterd
	  is deleted first.


	* Over here we do this by simply using a stack.

*/

#include<stdio.h>
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
#include<math.h>
#include<CTYPE.h>

class stack
{
	public:
	double arr[100]; /* declaring the stack of a particular size */
	int top;
	int start , full ;
	int valid;

	public:
	stack()
	{
		top = start = -1;   /* initially the top and the
					starting point are same */

		full = 100 ;  /* the size of the array is
					initiallized to mark the end */
		valid = 1;  /* valid is used as a flag to mark wether overflow
			      or underflow of the stack  */
	}

	void push(double a);
	double pop();
	double oper(char ,double,double);
};

void stack::push(double a)
{

	if(top == full-1 )
	{
		printf("\n the stack is full cannot enter any more values");

	}
	else
	{
		top++ ;
		arr[top] = a ;

	}
}

double stack::pop()
{

	double i;

	if(top == start)
	{
		printf("\n the stack is empty");
		printf("\n a garbage value is printed");
		valid = 0;

	}
	else
	{
		i = arr[top];
		top--;
		valid = 1;

	}

	if(valid == 1)
	{
		return i;
	}
}

double stack::oper(char c,double op1,double op2)
{
	switch(c)
	{
		case '+': return(op1+op2);

		case '-': return(op1-op2);

		case '*': return(op1*op2);

		case '/': return(op1/op2);

		case '$': return(pow(op1,op2));

		default : printf("illegal operation");
				return 0;
	}
}



void main()
{
	clrscr();
	stack s;
	char exp[50] , i , pos=0;
	int flag = 1 , count = 0,k;
	double op1,op2;
	double value;

	printf("\n enter you expression");
	while((exp[pos++]=getchar()) != '\n');
	exp[--pos] = '\0';
	printf("\n the expession is \n %s",exp);

	for(k=0 ; exp[k] != '\0' ; k++)
	{
		if(isdigit(exp[k])) /* isdigit is used to check wether
					the character is a digit*/
		    s.push((double)(exp[k]-'0'));
		else
		{
			op1 = s.pop();
			op2 = s.pop();
			value = s.oper(exp[k],op1,op2);
			s.push(value);
			printf("%lf",value);
		}
	}




       getch();
}


									

Download Program
Did You Know ?
IP address is a numerical label that is assigned to devices participating in a computer network. Read More