My Profile

Ahmednagar, Maharashtra, India
I, Das ShrikKrishna J. MCA III IMSCD&R, Ahmednagar.
Showing posts with label Check nesting of parentheses using stack(DS using C). Show all posts
Showing posts with label Check nesting of parentheses using stack(DS using C). Show all posts

Saturday, 30 July 2011

Program to check nesting of parentheses using stack

/* Program to check nesting of parentheses using stack */
#include<stdio.h>
#define MAX 20
#define true 1
#define false 0
int top = -1;
int stack[MAX];
push(char);
char pop();
main()
{
char exp[MAX],temp;
int i,valid=true;
printf("Enter an algebraic expression : ");
gets(exp);
for(i=0;i<strlen(exp);i++)
{
if(exp[i]=='(' || exp[i]=='{' || exp[i]=='[')
push( exp[i] );
if(exp[i]==')' || exp[i]=='}' || exp[i]==']')
if(top == -1) /* stack empty */
valid=false;
else
{
temp=pop();
if( exp[i]==')' && (temp=='{' || temp=='[') )
valid=false;
if( exp[i]=='}' && (temp=='(' || temp=='[') )
valid=false;
if( exp[i]==']' && (temp=='(' || temp=='{') )
valid=false;
}/*End of else */
}/*End of for*/
if(top>=0) /*stack not empty*/
valid=false;
if( valid==true )
printf("Valid expression\n");
else
printf("Invalid expression\n");
}/*End of main()*/
push(char item)
{
if(top == (MAX-1))
printf("Stack Overflow\n");
else
{
top=top+1;
stack[top] = item;
}
}/*End of push()*/
char pop()
{
if(top == -1)
printf("Stack Underflow\n");
else
return(stack[top--]);
}

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | cheap international calls