Sunday, June 12, 2011

CHECKING FOR BALANCED PARENTHESES IN AN EXPRESSION


//c program
#include<stdio.h>
#include<conio.h>
#include<string.h>


struct stack
{
int data;
struct stack *next;
}*top;


void check(char exp[]);
void push();
void pop();
int isempty();
char readtopele();
void main()
{
char exp[50];
top=NULL;
clrscr();
printf("\t\t\tPROGRAM FOR CHECKING BALANCED PARENTHESIS\n");
printf("\nenter the expression(max 50 char)\n");
scanf("%s",exp);
check(exp);
getch();
}

void check(char exp[])
{
int len,i,empty,topele;
len=strlen(exp);
i=0;
while(i<len)
{
 if(exp[i]=='(')
    push();
 else if(exp[i]==')')
  {
   empty=isempty();
    if(empty==1)
     {
      printf("\nMISSING AN OPENING SYMBOL\nTHE EXPRESION IS NOT BALANCED\n");
      getch();
      exit(0);
     }
     else
     {
      topele=readtopele();
      if(topele=='(')
       pop();
      else
       {printf("\n\nMISMATCHED SYMBOL\nTHE EXPRESSIO IS NOT BALANCED\n");
getch();
exit(0);
       }
      }
   }
   i++;
}
empty=isempty();
if(empty==1)
{printf("\nTHE EXPRESSION IS PERFECTLY BALANCED!!!!");
 getch();
 exit(0);
}
else
 printf("\nTHE EXPRESSION IS NOT BALANCED\nMISSING A CLOSING BRACKET\n");
}


void push(void)
{
 struct stack *new;
 new=(struct stack*)malloc(sizeof(struct stack));
 new->data='(';
 new->next=top;
 top=new;
}


void pop()
{
 top=top->next;
}


int isempty()
{
 if(top==NULL)
  return 1;
 else
  return 0;
}


char readtopele()
{
return(top->data);
}

No comments:

Post a Comment