Program to Checking well formedness of parenthesis using stack

				
					STACK IMPLEMENTED USING ARRAYS (USING HEADER FILE OF STACK OPERATIONS)
Step 1: Create a header file named stack.h. In this file we will declare the class and all the stack operations. The implementation of stack is using arrays.


#define size 10
class stk_class
{
private:
/*stack structure*/
struct stack
{
char s[size];
int top;
}st;
public:
stk_class();
void push(char item);
int stempty();
char pop();
};
stk_class::stk_class()
{
st.top=-1;
}
/* the push function
input:item which is to be pished
output:none –simply pushes the item onto the stack
called by: main
calls: one
*/
void stk_class::push(char item)
{
st.top++;
st.s[st.top]=item;
}
/*
the stempty function
input:none
output:returns 1 or 0 for stack empty or not
called by:none
*/
int stk_class::stempty()
{
if(st.top==-1)
return 1;

else
return 0;
}
/*
the stfull function
input:none
coutput:returns 1 or 0 for stack full or not
called by :main
calls:none
*/
int stk_class::stfull()
{
if(st.top==size)
return 1;
else
return 0;
}
/*
the pop function
input:none
output:returns the item which is poped from the stack
called by: main
calls:none
*/
char stk_class::pop()
{
char item;
item=st.s[st.top];
st.top--;
return(item);
}

				
			
				
					Step 2: Now we will create a stack application program. We have chosen an application as
“checking well formedness of parenthesis” for this application we will use stack operations.
These operations are used from the external file stack.h. Hence we will include this file in the
include file section. Here is an application program.
/************************************************************************
program for checking the well formedness of the parenthesis using stack as arrays.
************************************************************************/
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
#include “C:\TC\INCLUDE\stack.h”
#define size 10
/*
the main function
input:none
ouput:none
called by:O.S
calls:push,pop,stempty
*/

void main(void)
{
char item;
char ans,bracket[10];
stk_class obj;
int i;
clrscr();
cout<”\n\t\t program for stack application using separate
header file”; cout<<”\n enter the expression and put $at
end “;
cin>>bracket;
i=0;
if(bracket[i]==’)’)
cout<<”\n the expressin is invalid”;
else
{
do
{
ile(bracket[i]==’(‘)
{
obj.push(bracket[i]);
i++;
}
while(bracket[i]==’)’)
{
item=obj.pop();
i++;
}
}
while(brackt[i]!=’$’)
if(!obj.stempty())
cout<<”\n the expression is invalid”;
else
cout<<”\n the expression has well formed
parenthesis”;
}
getch();
}

				
			

Leave a Reply